问:
How to release memory after clear a Groupbox in c#
I have a groupbox named "radGroupBox1" that I want to open a user control in that.
This is my code:

```<code>radGroupBox1.Controls.Clear();

_main2 = new Forms.MainControl2();
radGroupBox1.Controls.Add(_main2);
_main2.Dock = DockStyle.Fill;
_main2.Frm = this;
_main2.Show();
</code>```

My problem is every time I execute this code , My memory increase. I check it in task manager. For example if you click 10 times on my button(run code) , Memory will increase 10 time. How can i release Memory allocated to previous object ?
Is there any way to Dispose it or force GC to release memory?

答:
As you can read in the documentation:

Calling the Clear method does not remove control handles from memory. You must explicitly call the Dispose method to avoid memory leaks.

So this means that you have to Dispose the user control yourself. Also, be sure that inside the user-control you are disposing any disposable resources.

```<code>radGroupBox1.Controls.Clear();
_main2?.Dispose();
_main2 = new Forms.MainControl2();
radGroupBox1.Controls.Add(_main2);
_main2.Dock = DockStyle.Fill;
_main2.Frm = this;
_main2.Show();
</code>```

Body:
I have a groupbox named "radGroupBox1" that I want to open a user control in that.
This is my code:

radGroupBox1.Controls.Clear();

_main2 = new Forms.MainControl2();
radGroupBox1.Controls.Add(_main2);
_main2.Dock = DockStyle.Fill;
_main2.Frm = this;
_main2.Show();

My problem is every time I execute this code , My memory increase. I check it in task manager. For example if you click 10 times on my button(run code) , Memory will increase 10 time. How can i release Memory allocated to previous object ?
Is there any way to Dispose it or force GC to release memory?

Body:
As you can read in the documentation:

Calling the Clear method does not remove control handles from memory. You must explicitly call the Dispose method to avoid memory leaks.

So this means that you have to Dispose the user control yourself. Also, be sure that inside the user-control you are disposing any disposable resources.

radGroupBox1.Controls.Clear();
_main2?.Dispose();
_main2 = new Forms.MainControl2();
radGroupBox1.Controls.Add(_main2);
_main2.Dock = DockStyle.Fill;
_main2.Frm = this;
_main2.Show();


来源: stackexchange

问:
Plot marker for each users location from database IP
I have a users table in my database that stores an ip address.
I have an api that gets the users latitude and longitude.

Firstly, I need to get every users lang and long.

At the moment, my code is only returning the last user in my database's lang and long.

This is my code for trying to return every clients long and langs:

```<code>$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {

$username_   = $users_['username'];
$client_ip   = $users_['ip'];

//This is for getting each users location on our map
$ip               = $client_ip;
$geocode          = file_get_contents("http://freegeoip.net/json/{$ip}");
$output           = json_decode($geocode);
$client_latitude  = $output->latitude;
$client_longitude = $output->longitude;

}
</code>```

Then I return this to my home PHP page using:

```<code>$response = array('client_latitude'=>$client_latitude,'client_longitude'=>$client_longitude);
echo json_encode($response);
</code>```

I recieve the AJAX request with the following JS / JQUERY code:

```<code>    <script>
    function fetchOnline() {
        $.ajax({
            url: "includes/get_dash_settings.php",
            context: document.body,
            type: 'POST',
            data: {get_data:true},
            success: function(value) {
                var data = JSON.parse(value);
                $('#lat').html(data['client_latitude']);
                $('#long').html(data['client_longitude']);
            },
            complete:function(){
               setTimeout(fetchOnline,5000);
            }
        })
    }

    $(document).ready(function() { setInterval(fetchOnline,5000); });
</script>
</code>```

And then finally, I try and display these in div's for testing.

Eventually, I want them to go in to the jVectorMap Markers JS code so It can plot markers on my map from each users lang and long.

But for now, It's not getting each users lang and long. Only the last user in my database's.

UPDATED CODE

The code Sumarai posted below isn't working.
It is not updating the div id - all-the-coordinates.
Does anyone know what's wrong with my version ?

I am using some different code to the question I asked. I have been using it from the start but didn't post it here because I didn't think it would be this difficult.

My new script is the same but I am calling them in separate files now because I am already calling an array in my other file (get_dash_settings).

This is my script in my main PHP file:

```<code>    <script>
    function fetchOnline() {
        $.ajax({
            url: "includes/get_dash_settings.php",
            context: document.body,
            type: 'POST',
            data: {get_data:true},
            success: function(value) {
                var data = JSON.parse(value);
                $('#totalUsers').html(data['totalUsers']);
                $('#totalOnline').html(data['totalOnline']);
                $('#freeModeStatus').html(data['freemode']);
                $('#bypassesStatus').html(data['bypasses']);
                $('#isOnline').html(data['client_is_online']);
            },
            complete:function(){
               setTimeout(fetchOnline,5000);
            }
        });

        $.ajax({
            url: "includes/get_dash_map.php",
            context: document.body,
            type: 'POST',
            data: {get_data_:true},
            success: function(value_) {
                const data_ = JSON.parse(value_);
                const $parent = $('#all-the-coordinates');
                for (const row of data) {
                    const $element = $('<span></span>');
                    $element.text(`${data_['client_latitude']}, ${data_['client_longitude']}`);
                    $parent.append($element);
                }
            },
            complete:function(){
               setTimeout(fetchOnline,5000);
            }
        });
    }

    $(document).ready(function() { setInterval(fetchOnline, 5000); });
</script>
</code>```

My get_dash_map.php:

```<code>$user_grab = mysqli_query($con, "SELECT * FROM users");

$response = [];

while($users_ = mysqli_fetch_array($user_grab)) {
    $client_ip   = $users_['ip'];

    //This is for getting each users location on our map
    $ip               = $client_ip;
    $geocode          = file_get_contents("http://freegeoip.net/json/{$ip}");
    $output           = json_decode($geocode);
    $client_latitude  = $output->latitude;
    $client_longitude = $output->longitude;

    $response[] = ['client_latitude' => $client_latitude,'client_longitude' => $client_longitude];
}

echo json_encode($response);`
</code>```

答:
Since you want to get a bunch of coordinates back, it makes sense to return them in an array of sorts. You are currently only getting the last one, because you are overwriting the values. Make an entry, then add that entry to the response as an array item. You can easily create a new array item with the [] suffix. $response[] = $x will add an array item to $response containing $x.

```<code>$user_grab = mysqli_query($con, "SELECT * FROM users");

$response = [];

while($users_ = mysqli_fetch_array($user_grab)) {
    $client_ip   = $users_['ip'];

    //This is for getting each users location on our map
    $ip               = $client_ip;
    $geocode          = file_get_contents("http://freegeoip.net/json/{$ip}");
    $output           = json_decode($geocode);
    $client_latitude  = $output->latitude;
    $client_longitude = $output->longitude;

    $response[] = [
        'client_latitude' => $client_latitude,
        'client_longitude' => $client_longitude
    ];
}

echo json_encode($response);
</code>```

You obviously need to change your javascript too, as it currently expects an Object back with two keys, but you now get an Array of Objects back.

```<code><script>
    function fetchOnline() {
        $.ajax({
            url: "includes/get_dash_settings.php",
            context: document.body,
            type: 'POST',
            data: {get_data:true},
            success: function(value) {
                const data = JSON.parse(value);
                const $parent = $('#all-the-coordinates');
                for (const row of data) {
                    const $element = $('<span></span>');
                    $element.text(`${row['client_latitude']}, ${row['client_longitude']}`);
                    $parent.append($element);
                }
            }
        })
    }

    $(document).ready(function() { setInterval(fetchOnline, 5000); });
</script>
</code>```

with in the html

```<code><div id="all-the-coordinates"></div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a users table in my database that stores an ip address.
I have an api that gets the users latitude and longitude.

Firstly, I need to get every users lang and long.

At the moment, my code is only returning the last user in my database's lang and long.

This is my code for trying to return every clients long and langs:

$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {

$username_   = $users_['username'];
$client_ip   = $users_['ip'];

//This is for getting each users location on our map
$ip               = $client_ip;
$geocode          = file_get_contents("http://freegeoip.net/json/{$ip}");
$output           = json_decode($geocode);
$client_latitude  = $output->latitude;
$client_longitude = $output->longitude;

}

Then I return this to my home PHP page using:

$response = array('client_latitude'=>$client_latitude,'client_longitude'=>$client_longitude);
echo json_encode($response);

I recieve the AJAX request with the following JS / JQUERY code:

And then finally, I try and display these in div's for testing.

Eventually, I want them to go in to the jVectorMap Markers JS code so It can plot markers on my map from each users lang and long.

But for now, It's not getting each users lang and long. Only the last user in my database's.

UPDATED CODE

The code Sumarai posted below isn't working.
It is not updating the div id - all-the-coordinates.
Does anyone know what's wrong with my version ?

I am using some different code to the question I asked. I have been using it from the start but didn't post it here because I didn't think it would be this difficult.

My new script is the same but I am calling them in separate files now because I am already calling an array in my other file (get_dash_settings).

This is my script in my main PHP file:

My get_dash_map.php:

$user_grab = mysqli_query($con, "SELECT * FROM users");

$response = [];

while($users_ = mysqli_fetch_array($user_grab)) {
    $client_ip   = $users_['ip'];

    //This is for getting each users location on our map
    $ip               = $client_ip;
    $geocode          = file_get_contents("http://freegeoip.net/json/{$ip}");
    $output           = json_decode($geocode);
    $client_latitude  = $output->latitude;
    $client_longitude = $output->longitude;

    $response[] = ['client_latitude' => $client_latitude,'client_longitude' => $client_longitude];
}

echo json_encode($response);`

Body:
Since you want to get a bunch of coordinates back, it makes sense to return them in an array of sorts. You are currently only getting the last one, because you are overwriting the values. Make an entry, then add that entry to the response as an array item. You can easily create a new array item with the [] suffix. $response[] = $x will add an array item to $response containing $x.

$user_grab = mysqli_query($con, "SELECT * FROM users");

$response = [];

while($users_ = mysqli_fetch_array($user_grab)) {
    $client_ip   = $users_['ip'];

    //This is for getting each users location on our map
    $ip               = $client_ip;
    $geocode          = file_get_contents("http://freegeoip.net/json/{$ip}");
    $output           = json_decode($geocode);
    $client_latitude  = $output->latitude;
    $client_longitude = $output->longitude;

    $response[] = [
        'client_latitude' => $client_latitude,
        'client_longitude' => $client_longitude
    ];
}

echo json_encode($response);

You obviously need to change your javascript too, as it currently expects an Object back with two keys, but you now get an Array of Objects back.

<script>
    function fetchOnline() {
        $.ajax({
            url: "includes/get_dash_settings.php",
            context: document.body,
            type: 'POST',
            data: {get_data:true},
            success: function(value) {
                const data = JSON.parse(value);
                const $parent = $('#all-the-coordinates');
                for (const row of data) {
                    const $element = $('<span></span>');
                    $element.text(`${row['client_latitude']}, ${row['client_longitude']}`);
                    $parent.append($element);
                }
            }
        })
    }

    $(document).ready(function() { setInterval(fetchOnline, 5000); });
</script>

with in the html

<div id="all-the-coordinates"></div>


问:
PIL.Image.fromarray produces distorted image after np.reshape
I have an array (numpy) of shape (10000,1296) that I want to save as 10,000 images of 36x36 size. All values in the array are in the range (0,255). So I have used this code to do that (which worked well):

```<code>for i, line in enumerate(myarray):
    img = Image.new('L',(36,36))
    img.putdata(line)
    img.save(str(i)+'.png')
</code>```

I wanted to replace this code using the Image.fromarray method, but the resulting pictures are distorted beyond recognition compared to the original method. First I tried this:

```<code>myarray = myarray.reshape(10000,36,36)
for i, line in enumerate(myarray):
    img = Image.fromarray(line, 'L')
    img.save(str(i)+'.png')
</code>```

Which didn't work. So to debug I thought I would try just one item and did this:

```<code>Image.fromarray(myarray[0].reshape(36,36), 'L').save('test.png')
</code>```

And again - garbled distorted image.

So I figured either fromarray isn't working like I thought it should, or my reshape is too naive and messes up the data, but I am not able to fix this. Any ideas are welcome.

答:
PIL's L mode is a grayscale mode for data that represents luminance
(brightness).  The data is expected to be ints from 0 to 255. If you create a PIL Image by passing a NumPy array to Image.fromarray with mode='L', the dtype of the array should be uint8. Therefore use

```<code>myarray = myarray.astype('uint8')
</code>```

to ensure that the arrays passed to Image.fromarray have dtype uint8.

uint8s are unsigned 8-bit ints. float32s are 32-bit floats. They are 4 times as wide as a uint8. Image.fromarray views the underlying data in the NumPy array as uint8s, reads enough bytes to fill the image, and ignores the rest. So each 32-bit float becomes four 8-bit ints and each of those 8-bit ints colors a different pixel.

In other words, the following assert passes:

```<code>import numpy as np
from PIL import Image

line = np.arange(256).reshape(16, 16).astype('float32')
img = Image.fromarray(line, 'L')
line2 = np.asarray(img)
assert (line.view('uint8').ravel()[:256].reshape(16, 16) == line2).all()
</code>```

This is why using myarray without converting to uint8s creates a garbled image.

Alternatively, instead of converting myarray to uint8s you could
read the data in mode='F' (float mode):

```<code>import numpy as np
from PIL import Image

line = np.arange(256).reshape(16, 16).astype('float32')
img = Image.fromarray(line, 'F').convert('L')
img.save('/tmp/out.png')
</code>```

which yields

See this page for a list of all the possible PIL modes.

Body:
I have an array (numpy) of shape (10000,1296) that I want to save as 10,000 images of 36x36 size. All values in the array are in the range (0,255). So I have used this code to do that (which worked well):

for i, line in enumerate(myarray):
    img = Image.new('L',(36,36))
    img.putdata(line)
    img.save(str(i)+'.png')

I wanted to replace this code using the Image.fromarray method, but the resulting pictures are distorted beyond recognition compared to the original method. First I tried this:

myarray = myarray.reshape(10000,36,36)
for i, line in enumerate(myarray):
    img = Image.fromarray(line, 'L')
    img.save(str(i)+'.png')

Which didn't work. So to debug I thought I would try just one item and did this:

Image.fromarray(myarray[0].reshape(36,36), 'L').save('test.png')

And again - garbled distorted image.

So I figured either fromarray isn't working like I thought it should, or my reshape is too naive and messes up the data, but I am not able to fix this. Any ideas are welcome.

Body:
PIL's L mode is a grayscale mode for data that represents luminance
(brightness).  The data is expected to be ints from 0 to 255. If you create a PIL Image by passing a NumPy array to Image.fromarray with mode='L', the dtype of the array should be uint8. Therefore use

myarray = myarray.astype('uint8')

to ensure that the arrays passed to Image.fromarray have dtype uint8.

uint8s are unsigned 8-bit ints. float32s are 32-bit floats. They are 4 times as wide as a uint8. Image.fromarray views the underlying data in the NumPy array as uint8s, reads enough bytes to fill the image, and ignores the rest. So each 32-bit float becomes four 8-bit ints and each of those 8-bit ints colors a different pixel.

In other words, the following assert passes:

import numpy as np
from PIL import Image

line = np.arange(256).reshape(16, 16).astype('float32')
img = Image.fromarray(line, 'L')
line2 = np.asarray(img)
assert (line.view('uint8').ravel()[:256].reshape(16, 16) == line2).all()

This is why using myarray without converting to uint8s creates a garbled image.

Alternatively, instead of converting myarray to uint8s you could
read the data in mode='F' (float mode):

import numpy as np
from PIL import Image

line = np.arange(256).reshape(16, 16).astype('float32')
img = Image.fromarray(line, 'F').convert('L')
img.save('/tmp/out.png')

which yields

See this page for a list of all the possible PIL modes.


问:
Compare current date and db column dates and highlight the cell in JTable
I am retrieving date from a database, comparing it with current date, and if current date is 7 days less or equals the date from the database then I want to highlight the cell in JTable in which results are displayed.

Any idea how I can achieve this? Below is my code :

```<code>    java.util.Date dnow = new java.util.Date();
    if (dnow.equals(rs.getString("dbdate")){

        table.setCellSelectionEnabled(true); //Enable single cell selection
        table.addRowSelectionInterval(1, 1); // select rows
        table.setColumnSelectionInterval(1, 1);
        cell.setBackground(Color.RED);
    }
    else{

       // same as above if code
    }
</code>```

答:
Two things you need to fix in this code:

ResultSet shall return Date instead of String

```<code>rs.getDate("dbdate");
</code>```

Date Comparison is wrong at dnow.equals(rs.getString("dbdate"). Look at https://docs.oracle.com/javase/7/docs/api/java/util/Date.html

Body:
I am retrieving date from a database, comparing it with current date, and if current date is 7 days less or equals the date from the database then I want to highlight the cell in JTable in which results are displayed.

Any idea how I can achieve this? Below is my code :

    java.util.Date dnow = new java.util.Date();
    if (dnow.equals(rs.getString("dbdate")){

        table.setCellSelectionEnabled(true); //Enable single cell selection
        table.addRowSelectionInterval(1, 1); // select rows
        table.setColumnSelectionInterval(1, 1);
        cell.setBackground(Color.RED);
    }
    else{

       // same as above if code
    }

Body:
Two things you need to fix in this code:

ResultSet shall return Date instead of String

rs.getDate("dbdate");

Date Comparison is wrong at dnow.equals(rs.getString("dbdate"). Look at https://docs.oracle.com/javase/7/docs/api/java/util/Date.html


问:
TypeError: object of type 'NoneType' has no len() when iterating through files
I'm trying to iterate two text files. I have two text files one is for 'username' and another is for 'password'.

It works when I use functions with single argument. here's the code but not when it comes to use 2 or more than 1 argument.

Here's my code:

```<code>import os
import time
import getpass
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def Quora_bot():

    username = None
    password = None

    chromedriver  = 'F:\All  Folders\chromedriver\shit.exe'

#Uncomment this block if you don't want images to load(makes the procss a little bit faster)
    '''
    chromeOptions = webdriver.ChromeOptions()
    prefs = {"profile.managed_default_content_settings.images":2}
    chromeOptions.add_experimental_option("prefs",prefs)
    browser = webdriver.Chrome(chromedriver, chrome_options=chromeOptions)
    '''

    browser = webdriver.Chrome(chromedriver)
    browser.get("http://www.quora.com")       # Quora home page
    time.sleep(10)

    # Logging into Quora
    form = browser.find_element_by_class_name('regular_login')
    email = form.find_element_by_name("email")
    password = form.find_element_by_name("password")
    button_element = browser.find_element_by_xpath("//*[@value='Login']")
    email.send_keys(username)
    password.send_keys(password)

with open('newfile.txt') as u:
      for line in u:
        rr = line

with open('password.txt') as p:
     for linee in p:
       pp = linee

Quora_bot()
username = rr
password = pp
</code>```

And I'm getting this error.

```<code>    F:\Python_Installer\python.exe C:/Users/user/PycharmProjects/Quora_Bot/westing.py
Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/Quora_Bot/westing.py", line 45, in <module>
    Quora_bot()
  File "C:/Users/user/PycharmProjects/Quora_Bot/westing.py", line 32, in Quora_bot
    email.send_keys(username)
  File "F:\Python_Installer\lib\site-packages\selenium\webdriver\remote\webelement.py", line 348, in send_keys
    {'text': "".join(keys_to_typing(value)),
  File "F:\Python_Installer\lib\site-packages\selenium\webdriver\common\utils.py", line 150, in keys_to_typing
    for i in range(len(val)):
TypeError: object of type 'NoneType' has no len()

Process finished with exit code 1
</code>```

答:
So that we do not end up having everything in the comments let me summarize for you

Don't overwrite inbuild keyword such as for or object

your for_game()' function which is (i guess) should resetletterandanimal` is not resetting the global variables but only locally. So it is pointless since it does nothing in the end.

Assuming you defined valsomewhere  where we can't see, make sure it is defined as an object which as a length attribute like a string or list ( i guess most/ all iterables have. At the moment it seems like it is None so either you defined it as Noneor maybe set it equal to a function wich has no return statement.

I dont think your with statements are working the way you want them either, since you never read the content of the file but only keep the object. you need to read it with content = file.read()

But again without the necessary code, we can not help you anymore.

Body:
I'm trying to iterate two text files. I have two text files one is for 'username' and another is for 'password'.

It works when I use functions with single argument. here's the code but not when it comes to use 2 or more than 1 argument.

Here's my code:

import os
import time
import getpass
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def Quora_bot():

    username = None
    password = None

    chromedriver  = 'F:\All  Folders\chromedriver\shit.exe'

#Uncomment this block if you don't want images to load(makes the procss a little bit faster)
    '''
    chromeOptions = webdriver.ChromeOptions()
    prefs = {"profile.managed_default_content_settings.images":2}
    chromeOptions.add_experimental_option("prefs",prefs)
    browser = webdriver.Chrome(chromedriver, chrome_options=chromeOptions)
    '''

    browser = webdriver.Chrome(chromedriver)
    browser.get("http://www.quora.com")       # Quora home page
    time.sleep(10)

    # Logging into Quora
    form = browser.find_element_by_class_name('regular_login')
    email = form.find_element_by_name("email")
    password = form.find_element_by_name("password")
    button_element = browser.find_element_by_xpath("//*[@value='Login']")
    email.send_keys(username)
    password.send_keys(password)

with open('newfile.txt') as u:
      for line in u:
        rr = line

with open('password.txt') as p:
     for linee in p:
       pp = linee

Quora_bot()
username = rr
password = pp

And I'm getting this error.

    F:\Python_Installer\python.exe C:/Users/user/PycharmProjects/Quora_Bot/westing.py
Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/Quora_Bot/westing.py", line 45, in <module>
    Quora_bot()
  File "C:/Users/user/PycharmProjects/Quora_Bot/westing.py", line 32, in Quora_bot
    email.send_keys(username)
  File "F:\Python_Installer\lib\site-packages\selenium\webdriver\remote\webelement.py", line 348, in send_keys
    {'text': "".join(keys_to_typing(value)),
  File "F:\Python_Installer\lib\site-packages\selenium\webdriver\common\utils.py", line 150, in keys_to_typing
    for i in range(len(val)):
TypeError: object of type 'NoneType' has no len()

Process finished with exit code 1


问:
Right syntax to get parameters values from html string chain
what is the correct syntax in this case to get parameters values for a function with two arguments.

At first my removeRow(id) function need only one parameter to do process.

html code:

```<code>"<a href=javascript:removeRow("+sport.id+"); class='btn btn-xs btn-warning'>remove</a>"
</code>```

js code:
// Remove row

```<code>function removeRow(sportId) {
    if ( 'undefined' != typeof sportId) {
        console.log(sportId);
    } else alert('Unknown id.');
}
</code>```

Now, i want this function to take two parameters(syntax???)

html code:

```<code>"<a href=javascript:removeRow("+sport.id+","+ event.id+"); class='btn btn-xs btn-warning'>remove</a>"
</code>```

js code:

```<code>// Remove row
function removeRow(sportId,eventId) {
    if ( 'undefined' != typeof sportId) {
        console.log(sportId+ " " +  eventId);
    } else alert('Unknown id.');
}
</code>```

答:
You need to quote the IDs and escape the quotes like this:

```<code>"<a href='javascript:removeRow(\""+sport.id+"\",\""+event.id+"\")' class='btn btn-xs btn-warning'>remove</a>"
</code>```

but I strongly recommend you do NOT use a javascript href and also that you use data attributes instead

```<code>'<a href="#" onclick="return removeRow(this)" data-sportid="'+sport.id+'" data-eventid="'+event.id+'" class="btn btn-xs btn-warning">remove</a>'
</code>```

and use

```<code>function removeRow(link) {
  var sportId = link.getAttribute("data-sportid"),
      eventId = link.getAttribute("data-eventid");
  if ( 'undefined' != typeof sportId) {
    console.log(sportId+ " " + eventId);
  }
  else alert('Unknown id.');
  return false; // cancel the link
}
</code>```

To do the same unobtrusively

```<code>window.onload=function() {
  var sportLinks = document.querySelectoraAll(".sport");
  for (var i=0;i<sportLinks.length;i++) {
    sportLinks[i].onclick=function removeRow(e) {
      e.preventdefault(); // cancel link event
      var sportId = link.getAttribute("data-sportid"),
          eventId = link.getAttribute("data-eventid");
      if ( 'undefined' != typeof sportId) {
        console.log(sportId+ " " + eventId);
      }
      else alert('Unknown id.');
    }
  }
}
</code>```

adding a class:

```<code>'<a href="#" data-sportid="'+sport.id+'" data-eventid="'+event.id+'" class="sport btn btn-xs btn-warning">remove</a>'
</code>```

Body:
what is the correct syntax in this case to get parameters values for a function with two arguments.

At first my removeRow(id) function need only one parameter to do process.

html code:

"remove"

js code:
// Remove row

function removeRow(sportId) {
    if ( 'undefined' != typeof sportId) {
        console.log(sportId);
    } else alert('Unknown id.');
}

Now, i want this function to take two parameters(syntax???)

html code:

"remove"

js code:

// Remove row
function removeRow(sportId,eventId) {
    if ( 'undefined' != typeof sportId) {
        console.log(sportId+ " " +  eventId);
    } else alert('Unknown id.');
}

Body:
You need to quote the IDs and escape the quotes like this:

"<a href='javascript:removeRow(\""+sport.id+"\",\""+event.id+"\")' class='btn btn-xs btn-warning'>remove</a>"

but I strongly recommend you do NOT use a javascript href and also that you use data attributes instead

'<a href="#" onclick="return removeRow(this)" data-sportid="'+sport.id+'" data-eventid="'+event.id+'" class="btn btn-xs btn-warning">remove</a>'

and use

function removeRow(link) {
  var sportId = link.getAttribute("data-sportid"),
      eventId = link.getAttribute("data-eventid");
  if ( 'undefined' != typeof sportId) {
    console.log(sportId+ " " + eventId);
  }
  else alert('Unknown id.');
  return false; // cancel the link
}

To do the same unobtrusively

window.onload=function() {
  var sportLinks = document.querySelectoraAll(".sport");
  for (var i=0;i<sportLinks.length;i++) {
    sportLinks[i].onclick=function removeRow(e) {
      e.preventdefault(); // cancel link event
      var sportId = link.getAttribute("data-sportid"),
          eventId = link.getAttribute("data-eventid");
      if ( 'undefined' != typeof sportId) {
        console.log(sportId+ " " + eventId);
      }
      else alert('Unknown id.');
    }
  }
}

adding a class:

'<a href="#" data-sportid="'+sport.id+'" data-eventid="'+event.id+'" class="sport btn btn-xs btn-warning">remove</a>'


问:
(Tensorflow) How to use load_csv_without_header with target_dtype as a String value?
So I want to load a csv file that has no header. All the data in the csv is text. I can't figure out how to use

tf.contrib.learn.datasets.base.load_csv_without_header(filename=TRAINING,target_dtype="""I want this to be a string""",features_dtype="""This too""")

but it always throws errors. I've used dtypes.string, np.string (which doesn't exist), tf.string, and a bunch of casting but most of the tf.cast thing here need an "x" value.

How can I import my csv file (with strings!)? I don't mind using a different method. Is there also a way to convert a string to numpy.float32?

I would also prefer if the strings could be converted to a different format (like float32, or similar. Is that possible?) and then convert them back at the end.

答:
Yes, you can try using tf.text_line_reader, which has a parameter skip_header_lines.

This example probably does more than what you need, but you can get the gist of what's required easily. The key constraint is that each row should have the same number of columns in your CSV

Since you are required to provide defaults for each cell in the row, if your rows contain both strings and floats/ints, you are better off providing all the defaults as Strings and then converting the needed parts into floats. The other way won't work.


问:
Creating new columns using a for loop
I am new to R (Economist with background in Stata) and I am having trouble getting a nested for loop to work for me. I know the issue is that I don't have a good understanding of how to use the loop counter as part of a variable name.

A bit of background. I have data frame with data on average rental rates for homes of different size (1 bedroom, 2 bedroom, etc) and data on annual earnings (mean, median, and various percentiles). I am trying to generate a series of new columns containing the ratio of these two things (rental rate / mean earnings).

Specifically my variables are:

beds1, beds2, beds3, beds4

mean, median, p10, p25, p75, p90

So you see I need to generate 24 new columns of cost/earnings data. I could write out 24 lines of code but I don't want to. More importantly, I want to learn an efficient way of doing this in R. In Stata I could do this very simply using a nested for loop, but I can't get it to work in R. Here is my code so far.

```<code>for (i in 1:4) {
    stat <- c("median", "mean", "p10", "p25", "p75","p90")
    for (x in stat) {
        df$beds[i]_[x] <- round((df$beds[i]/df$[x]),digits=3)
    }
}
</code>```

When I run this code the error I get is

```<code>Error: unexpected input in:
"    for (x in stat) {
    df$beds[i]_"
>     }
Error: unexpected '}' in "    }"
> }
Error: unexpected '}' in "}"
</code>```

I have tried to use the double brackets [[]] but that didn't change the results. If anyone has some insight into why the dynamic variables names aren't working please let me know. Even better, since I guess loops are evil in R, if anyone knows a way to use lapply to get this done, I would love to hear that too.

EDIT

Thanks @Spacedman for the comment. I think I am getting what you're saying. So does that mean that there simply isn't anyway to do what I want to do in R?

```<code>var1 <- c("beds1", "beds2")
var2 <- c("mean", "median")

for (i in 1:2) {
    for (j in 1:2) {
        df$var1[i]_var2[j] <- df$var1[i]/df$var2[j]
    }
}
</code>```

I think this should grab the elements of the lists var1 and var2 so that  when i=1 and j=1, df$var1[i]/df$var2[j] should mean df$beds1/df$mean. Or would R get mad and think I was trying to divide strings?

FINAL EDIT WITH ANSWER FROM @SPACEEMAN

Thanks @Spacedman. I loved your spoiler and thank you for providing additional help. I didn't fully grasp the difference between the two ways of referring to columns after your last post, but I think I have a better idea now. I did a bit of tweaking and now I have something that works perfectly. Thanks again!

```<code>beds <- c("beds1", "beds2", "beds3", "beds4")
stat <- c("median", "mean", "p10", "p25", "p75","p90")

for(i in beds){
    for(x in stat){
        res = paste0(i,"_",x)
        df[[res]]=round(df[[i]]/df[[x]],digits=3)
    }
}
</code>```

答:
R is not a macro expansion language like other languages you might be used to.

x[i], if i=123, does not "expand" into x123. It gets the value of the 123rd element of the vector, x.

So df$beds[i] tries to get the i'th element of a vector df$beds.

You need to know two things:

How to construct strings from other strings.

For this you can use paste0:

```<code>> for(i in 1:4){
+  print(paste0("beds",i))
+ }
[1] "beds1"
[1] "beds2"
[1] "beds3"
[1] "beds4"
</code>```

How to access columns by names.

For this you can use double square brackets. In a list:

```<code>> z = list()
> n = "thing"
</code>```

Double squabs evaluate their index and use that. So:

```<code>> z[[n]] = 99
</code>```

Will set z$thing, but dollar sign indexing is literal, so:

```<code>> z$n = 123
</code>```

will set z$n:

```<code>> z
$thing
[1] 99

$n
[1] 123
</code>```

hopefully that's enough hints to get you through. It should all be covered in basic R tutorials online.

Spoiler

If you want to work out how to do it yourself, look away now...

First, lets create a sample data frame - you should include something like this in your question so we have common test data to work on. I'll just have three beds and two stats:

```<code>> df = data.frame(
     beds1=c(1,2,3),
     beds2=c(5,2,3),
     beds3=c(6,6,6),
     mean=c(8,4,3),
     median=c(1,7,4))
> df
      beds1 beds2 beds3 mean median
    1     1     5     6    8      1
    2     2     2     6    4      7
    3     3     3     6    3      4
</code>```

Now the work. We loop over the bed number and the character stats. The bed column name is stored in bed by pasting "beds" to the number i. We compute the name of the result column (res) for a given bed number and stat by pasting "beds" to i and "_" and the name of the stat in x.

Then set the new resulting column to the value by dividing the beds number by the stat. We use [[z]] to get the columns by name:

```<code>> for(i in 1:3){
  stats=c("mean","median")
  for(x in stats){
    bed = paste0("beds",i)
    res = paste0("beds",i,"_",x)
    df[[res]]=round(df[[bed]]/df[[x]],digits=3)
  }
 }
</code>```

Resulting in....

```<code>> df
  beds1 beds2 beds3 mean median beds1_mean beds1_median beds2_mean beds2_median
1     1     5     6    8      1      0.125        1.000      0.625        5.000
2     2     2     6    4      7      0.500        0.286      0.500        0.286
3     3     3     6    3      4      1.000        0.750      1.000        0.750
  beds3_mean beds3_median
1       0.75        6.000
2       1.50        0.857
3       2.00        1.500
>
</code>```

Title: Creating new columns using a for loop

Body:
I am new to R (Economist with background in Stata) and I am having trouble getting a nested for loop to work for me. I know the issue is that I don't have a good understanding of how to use the loop counter as part of a variable name.

A bit of background. I have data frame with data on average rental rates for homes of different size (1 bedroom, 2 bedroom, etc) and data on annual earnings (mean, median, and various percentiles). I am trying to generate a series of new columns containing the ratio of these two things (rental rate / mean earnings).

Specifically my variables are:

beds1, beds2, beds3, beds4

mean, median, p10, p25, p75, p90

So you see I need to generate 24 new columns of cost/earnings data. I could write out 24 lines of code but I don't want to. More importantly, I want to learn an efficient way of doing this in R. In Stata I could do this very simply using a nested for loop, but I can't get it to work in R. Here is my code so far.

for (i in 1:4) {
    stat <- c("median", "mean", "p10", "p25", "p75","p90")
    for (x in stat) {
        df$beds[i]_[x] <- round((df$beds[i]/df$[x]),digits=3)
    }
}

When I run this code the error I get is

Error: unexpected input in:
"    for (x in stat) {
    df$beds[i]_"
>     }
Error: unexpected '}' in "    }"
> }
Error: unexpected '}' in "}"

I have tried to use the double brackets [[]] but that didn't change the results. If anyone has some insight into why the dynamic variables names aren't working please let me know. Even better, since I guess loops are evil in R, if anyone knows a way to use lapply to get this done, I would love to hear that too.

EDIT

Thanks @Spacedman for the comment. I think I am getting what you're saying. So does that mean that there simply isn't anyway to do what I want to do in R?

var1 <- c("beds1", "beds2")
var2 <- c("mean", "median")

for (i in 1:2) {
    for (j in 1:2) {
        df$var1[i]_var2[j] <- df$var1[i]/df$var2[j]
    }
}

I think this should grab the elements of the lists var1 and var2 so that  when i=1 and j=1, df$var1[i]/df$var2[j] should mean df$beds1/df$mean. Or would R get mad and think I was trying to divide strings?

FINAL EDIT WITH ANSWER FROM @SPACEEMAN

Thanks @Spacedman. I loved your spoiler and thank you for providing additional help. I didn't fully grasp the difference between the two ways of referring to columns after your last post, but I think I have a better idea now. I did a bit of tweaking and now I have something that works perfectly. Thanks again!

beds <- c("beds1", "beds2", "beds3", "beds4")
stat <- c("median", "mean", "p10", "p25", "p75","p90")

for(i in beds){
    for(x in stat){
        res = paste0(i,"_",x)
        df[[res]]=round(df[[i]]/df[[x]],digits=3)
    }
}

Body:
R is not a macro expansion language like other languages you might be used to.

x[i], if i=123, does not "expand" into x123. It gets the value of the 123rd element of the vector, x.

So df$beds[i] tries to get the i'th element of a vector df$beds.

You need to know two things:

How to construct strings from other strings.

For this you can use paste0:

> for(i in 1:4){
+  print(paste0("beds",i))
+ }
[1] "beds1"
[1] "beds2"
[1] "beds3"
[1] "beds4"

How to access columns by names.

For this you can use double square brackets. In a list:

> z = list()
> n = "thing"

Double squabs evaluate their index and use that. So:

> z[[n]] = 99

Will set z$thing, but dollar sign indexing is literal, so:

> z$n = 123

will set z$n:

> z
$thing
[1] 99

$n
[1] 123

hopefully that's enough hints to get you through. It should all be covered in basic R tutorials online.

Spoiler

If you want to work out how to do it yourself, look away now...

First, lets create a sample data frame - you should include something like this in your question so we have common test data to work on. I'll just have three beds and two stats:

> df = data.frame(
     beds1=c(1,2,3),
     beds2=c(5,2,3),
     beds3=c(6,6,6),
     mean=c(8,4,3),
     median=c(1,7,4))
> df
      beds1 beds2 beds3 mean median
    1     1     5     6    8      1
    2     2     2     6    4      7
    3     3     3     6    3      4

Now the work. We loop over the bed number and the character stats. The bed column name is stored in bed by pasting "beds" to the number i. We compute the name of the result column (res) for a given bed number and stat by pasting "beds" to i and "_" and the name of the stat in x.

Then set the new resulting column to the value by dividing the beds number by the stat. We use [[z]] to get the columns by name:

> for(i in 1:3){
  stats=c("mean","median")
  for(x in stats){
    bed = paste0("beds",i)
    res = paste0("beds",i,"_",x)
    df[[res]]=round(df[[bed]]/df[[x]],digits=3)
  }
 }

Resulting in....

> df
  beds1 beds2 beds3 mean median beds1_mean beds1_median beds2_mean beds2_median
1     1     5     6    8      1      0.125        1.000      0.625        5.000
2     2     2     6    4      7      0.500        0.286      0.500        0.286
3     3     3     6    3      4      1.000        0.750      1.000        0.750
  beds3_mean beds3_median
1       0.75        6.000
2       1.50        0.857
3       2.00        1.500
>


问:
Put space between end of page and button on iphone
Hello guys i have trouble with my code. I have a bootstrap button and thats is fine but how can i put space between the button and end of the page. because its only on iphone the problem. Its very weird because when im holding in normal its good the button but when i turn my iphone there is no space anymore.

This is my button:

```<code><div class="row">
    <div class="text-center">
        <button type="button" class="learn btn btn-info">Learn more</button>
    </div>
</div>
</code>```

答:
Maybe put CSS like this to your button :</p>

```<code>button.learn {
    margin-bottom: 10px;
    // Or :
    padding-bottom: 10px;
}
</code>```

Body:
Hello guys i have trouble with my code. I have a bootstrap button and thats is fine but how can i put space between the button and end of the page. because its only on iphone the problem. Its very weird because when im holding in normal its good the button but when i turn my iphone there is no space anymore.

This is my button:

        <button type="button" class="learn btn btn-info">Learn more</button>

Body:
Maybe put CSS like this to your button :

button.learn {
    margin-bottom: 10px;
    // Or :
    padding-bottom: 10px;
}


问:
Angular CLI and TypeScript outDir
I've just worked through the Angular CLI Heroes tutorial here.  I've followed all tutorials and completed the HTTP tutorial.

All great learning about Angular 4 and TypeScript but one thing that struck me throughout the course was the javascript being compiled into the src folder.  It would be nice if there was some "next steps" tutorial about packaging things up for a deployment - but that is potentially outside the scope of Angular.

I want to change this but not 100% sure on everything I need to do.

Ideally it would be to compile to separate folder and include all files necessary to run the website.

I've looked at the tsconfig.json file and added an outDir setting:

```<code>{
  "compilerOptions": {
    "target": "es5",
    "outDir": "../dist/app",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}
</code>```

When I run npm start the code seems to build to the dist folder, but when the application runs, all I get in the browser is Cannot GET /

I am missing a few things including index.html - but I don't know what files I need exactly.  So my questions are:

What files outside of my compiled app folder are required to run the website?

Can I modify the project files to achieve this using Angular CLI?

答:
To host your app you need the following:

Run npm run build -- -prod (it does the same as ng build -prod but it can be sometimes better because in this case you do not need to setup the angular CLI globally, e.g. this is good for CI builder). This will create a folder that is configured in .angular-cli.json. By default it is dist folder

Take this folder and put its content to the server's root

Ideally you should not change any of the settings apart from .angular-cli.json. Why? Because you need to be expert in Webpack, TypeScript configuration and many other things. Furthermore, the changes you would make will most likely be not supported by future angular-cli versions. Please check the project wiki and I am sure you will find answers to all of your questions / requirements.

This answer still does not cover your server configuration. You should have a 404 fallback there, most likely compression and caching, maybe some proxied endpoints. However this is a huge topic which is not connected to angular-cli.

Title: Angular CLI and TypeScript outDir

Body:
I've just worked through the Angular CLI Heroes tutorial here.  I've followed all tutorials and completed the HTTP tutorial.

All great learning about Angular 4 and TypeScript but one thing that struck me throughout the course was the javascript being compiled into the src folder.  It would be nice if there was some "next steps" tutorial about packaging things up for a deployment - but that is potentially outside the scope of Angular.

I want to change this but not 100% sure on everything I need to do.

Ideally it would be to compile to separate folder and include all files necessary to run the website.

I've looked at the tsconfig.json file and added an outDir setting:

{
  "compilerOptions": {
    "target": "es5",
    "outDir": "../dist/app",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}

When I run npm start the code seems to build to the dist folder, but when the application runs, all I get in the browser is Cannot GET /

I am missing a few things including index.html - but I don't know what files I need exactly.  So my questions are:

What files outside of my compiled app folder are required to run the website?

Can I modify the project files to achieve this using Angular CLI?


问:
Haskell High Order Functions
I'm a little bit confuse about high order function and I wanted to do a stupid example to see if I understood well but still I can't compile without errors, i.e I guess I'm missing something. My very basic example is as follow, I create a function that adds up two number, and then I create an other function which uses my previous function and sum up an other number.</p>

```<code>Sum2 :: Double -> Double -> Double
Sum2  a b = a + b

Sum3 :: (Double -> Double -> Double) -> Double -> Double
Sum3 a b c = (Sum2 a b) + c

test1:: Double
test1 = Sum3 2.0 3.0 4.0
</code>```

答:
There is no question, but I'll guess the OP wants some explanation about why this is not working:

```<code>Sum3 :: (Double -> Double -> Double) -> Double -> Double
Sum3 a b c = (Sum2 a b) + c
</code>```

First, functions should have a lowercase name. Second, the type above is the type of a function with two arguments:

```<code>sum3 :: (Double -> Double -> Double) -> Double -> Double
        ----- first arg ------------    -2nd--    -result type-
</code>```

So, one should write

```<code>sum3 f a = ...
</code>```

where f is the function passed as first argument Double -> Double -> Double, and a is the second argument number. Since f is a function taking two arguments, we need to use it accordingly, e.g.

```<code>sum3 f a = f a a
-- or
sum3 f a = f a 12
-- or
sum3 f a = f (a+12) (f 32 a)
</code>```

I have no idea about what you are trying to achieve, the above ones are only examples.

Finally, the name sum3 is unintuitive, we should use something else.

Title: Haskell High Order Functions

Body:
I'm a little bit confuse about high order function and I wanted to do a stupid example to see if I understood well but still I can't compile without errors, i.e I guess I'm missing something. My very basic example is as follow, I create a function that adds up two number, and then I create an other function which uses my previous function and sum up an other number.

Sum2 :: Double -> Double -> Double
Sum2  a b = a + b

Sum3 :: (Double -> Double -> Double) -> Double -> Double
Sum3 a b c = (Sum2 a b) + c

test1:: Double
test1 = Sum3 2.0 3.0 4.0

Body:
There is no question, but I'll guess the OP wants some explanation about why this is not working:

Sum3 :: (Double -> Double -> Double) -> Double -> Double
Sum3 a b c = (Sum2 a b) + c

First, functions should have a lowercase name. Second, the type above is the type of a function with two arguments:

sum3 :: (Double -> Double -> Double) -> Double -> Double
        ----- first arg ------------    -2nd--    -result type-

So, one should write

sum3 f a = ...

where f is the function passed as first argument Double -> Double -> Double, and a is the second argument number. Since f is a function taking two arguments, we need to use it accordingly, e.g.

sum3 f a = f a a
-- or
sum3 f a = f a 12
-- or
sum3 f a = f (a+12) (f 32 a)

I have no idea about what you are trying to achieve, the above ones are only examples.

Finally, the name sum3 is unintuitive, we should use something else.


问:
How to connect mysql tables
I have two tables in same database, one for pictures and the other table for picture comments. How can i write a sql command to get all the comments belonging to each particular picture?</p>

答:
```<code> $mysqli = new mysqli("example.com", "user", "password", "database");
 $query = "SELECT picture_table.pic_id, picture_comment_table.*
                FROM picture_table LEFT JOIN picture_comment_table
                ON picture_table.pic_id = picture_comment_table.pic_id";
 $stmt = $mysqli->prepare($query);
 !$stmt ? die('error') : "";
 $stmt->execute();
</code>```

I used left join since there are some pictures without comments that is not going to be selected in case of an inner join.

also note that if you have more than one comment row for a picture, the result will have more than 1 row for that picture, which a thing you should handle Whether in the application layer (your php code) or in the sql statement.

Title: How to connect mysql tables

Body:
 $mysqli = new mysqli("example.com", "user", "password", "database");
 $query = "SELECT picture_table.pic_id, picture_comment_table.*
                FROM picture_table LEFT JOIN picture_comment_table
                ON picture_table.pic_id = picture_comment_table.pic_id";
 $stmt = $mysqli->prepare($query);
 !$stmt ? die('error') : "";
 $stmt->execute();

I used left join since there are some pictures without comments that is not going to be selected in case of an inner join.

also note that if you have more than one comment row for a picture, the result will have more than 1 row for that picture, which a thing you should handle Whether in the application layer (your php code) or in the sql statement.


问:
log4net message text problem
I'm trying to make log4net work using File Appender.

I use specified pattern layout for messages, but the problem is that I get no text in my log file. only '??' symbols

It seems that the the message text somehow gets corrupted before being written to file.

I'm using Visual Studio 2008 on windows Server 2008. The log4net is initialised in global.asax

here is my config for log4net

```<code><section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"></section>
. . .
<log4net debug="true">
    <appender name="INFOFileAppender" type="log4net.Appender.FileAppender">
        <lockingmodel type="log4net.Appender.FileAppender+MinimalLock"/>
      <threshold value="INFO" />
      <file value="AOKlogs.txt" />
        <appendtofile value="true" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <root>
        <level value="ALLL" />
        <appender-ref ref="INFOFileAppender" />
    </root>
  </log4net>
</code>```

I've tried both rollingfile and simple file appender without luck.

UPDATE
I enabled debugging and configured log4net to write debug log to txt file. and here is what it says:

i enabled debugging log to txt file and here is what it says:

log4net: log4net assembly [log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821]. Loaded from [C:\Users\ScarryComp\AppData\Local\Temp\Temporary ASP.NET Files\website1\7e2bf4c4\4d1a1e05\assembly\dl3\c6bded9b\0086655c_d353c601\log4net.DLL]. (.NET Runtime [2.0.50727.4952] on Microsoft Windows NT 6.1.7600.0)
log4net: DefaultRepositorySelector: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: DefaultRepositorySelector: Creating repository for assembly [App_Code.ch9yol_l, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]
log4net: DefaultRepositorySelector: Assembly [App_Code.ch9yol_l, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\Users\ScarryComp\AppData\Local\Temp\Temporary ASP.NET Files\website1\7e2bf4c4\4d1a1e05\App_Code.ch9yol_l.dll]
log4net: DefaultRepositorySelector: Assembly [App_Code.ch9yol_l, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: DefaultRepositorySelector: Assembly [App_Code.ch9yol_l, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: DefaultRepositorySelector: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
log4net: XmlConfigurator: configuring repository [log4net-default-repository] using .config file section
log4net: XmlConfigurator: Application config file is [C:\Users\ScarryComp\Documents\Visual Studio 2008\WebSites\WebSite1\web.config]
log4net: XmlConfigurator: Configuring Repository [log4net-default-repository]
log4net: XmlHierarchyConfigurator: Configuration update mode [Merge].
log4net: XmlHierarchyConfigurator: Logger [root] Level string is [ALL].
log4net: XmlHierarchyConfigurator: Logger [root] level set to [name="ALL",value=-2147483648].
log4net: XmlHierarchyConfigurator: Loading Appender [INFOFileAppender] type: [log4net.Appender.FileAppender]
log4net: XmlHierarchyConfigurator: Setting Property [LockingModel] to object [log4net.Appender.FileAppender+MinimalLock]
log4net: XmlHierarchyConfigurator: Setting Property [Threshold] to Level value [ALL]
log4net: XmlHierarchyConfigurator: Setting Property [File] to String value [AOKlogs.txt]
log4net: XmlHierarchyConfigurator: Setting Property [AppendToFile] to Boolean value [True]
log4net: XmlHierarchyConfigurator: Parameter [layout] specified subtype [log4net.Layout.PatternLayout]
log4net: PatternParser: Converter [literal] Option [
                ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: XmlHierarchyConfigurator: Setting Property [Layout] to PatternLayout value [log4net.Layout.PatternLayout]
log4net: FileAppender: Opening file for writing [C:\Users\ScarryComp\Documents\Visual Studio 2008\WebSites\WebSite1\AOKlogs.txt] append [True]
log4net: XmlHierarchyConfigurator: Created Appender [INFOFileAppender]
log4net: XmlHierarchyConfigurator: Adding appender named [INFOFileAppender] to logger [root].
log4net: XmlHierarchyConfigurator: Loading Appender [Console] type: [log4net.Appender.ConsoleAppender]
log4net: PatternParser: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: PatternParser: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: XmlHierarchyConfigurator: Setting Property [ConversionPattern] to String value [%d %-5l - %m%n]
log4net: PatternParser: Converter [d] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: PatternParser: Converter [literal] Option [ ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: PatternParser: Converter [l] Option [] Format [min=5,max=2147483647,leftAlign=True]
log4net: PatternParser: Converter [literal] Option [ - ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: PatternParser: Converter [m] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: PatternParser: Converter [n] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: XmlHierarchyConfigurator: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: XmlHierarchyConfigurator: Created Appender [Console]
log4net: XmlHierarchyConfigurator: Adding appender named [Console] to logger [root].
log4net: XmlHierarchyConfigurator: Hierarchy Threshold []

I changed added Console appender but I still don't see text in my logs :(

UPDATE 2:
File appenders didn't work but trace appender appeared to be ok. However, that would be nice if someboydy could explain what could happen to file appenders so the question remains kinda opened

答:
I could imagine that you have an encoding problem. Log4net uses an ANSI encoding by default, if your server (or service) and your machine do not use the same encoding you would not be able to read the text in the file.

You could try to configure the encoding like this:

```<code><appender name="INFOFileAppender" type="log4net.Appender.FileAppender">
    <encoding value="unicodeFFFE" />
    ...
</code>```

ContentLicense: CC BY-SA 2.5

Title: log4net message text problem

Body:
I'm trying to make log4net work using File Appender.

I use specified pattern layout for messages, but the problem is that I get no text in my log file. only '??' symbols

It seems that the the message text somehow gets corrupted before being written to file.

I'm using Visual Studio 2008 on windows Server 2008. The log4net is initialised in global.asax

here is my config for log4net

. . .
<log4net debug="true">
    <appender name="INFOFileAppender" type="log4net.Appender.FileAppender">
        <lockingmodel type="log4net.Appender.FileAppender+MinimalLock"/>
      <threshold value="INFO" />
      <file value="AOKlogs.txt" />
        <appendtofile value="true" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <root>
        <level value="ALLL" />
        <appender-ref ref="INFOFileAppender" />
    </root>
  </log4net>

I've tried both rollingfile and simple file appender without luck.

UPDATE
I enabled debugging and configured log4net to write debug log to txt file. and here is what it says:

i enabled debugging log to txt file and here is what it says:

log4net: log4net assembly [log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821]. Loaded from [C:\Users\ScarryComp\AppData\Local\Temp\Temporary ASP.NET Files\website1\7e2bf4c4\4d1a1e05\assembly\dl3\c6bded9b\0086655c_d353c601\log4net.DLL]. (.NET Runtime [2.0.50727.4952] on Microsoft Windows NT 6.1.7600.0)
log4net: DefaultRepositorySelector: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: DefaultRepositorySelector: Creating repository for assembly [App_Code.ch9yol_l, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]
log4net: DefaultRepositorySelector: Assembly [App_Code.ch9yol_l, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\Users\ScarryComp\AppData\Local\Temp\Temporary ASP.NET Files\website1\7e2bf4c4\4d1a1e05\App_Code.ch9yol_l.dll]
log4net: DefaultRepositorySelector: Assembly [App_Code.ch9yol_l, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: DefaultRepositorySelector: Assembly [App_Code.ch9yol_l, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: DefaultRepositorySelector: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
log4net: XmlConfigurator: configuring repository [log4net-default-repository] using .config file section
log4net: XmlConfigurator: Application config file is [C:\Users\ScarryComp\Documents\Visual Studio 2008\WebSites\WebSite1\web.config]
log4net: XmlConfigurator: Configuring Repository [log4net-default-repository]
log4net: XmlHierarchyConfigurator: Configuration update mode [Merge].
log4net: XmlHierarchyConfigurator: Logger [root] Level string is [ALL].
log4net: XmlHierarchyConfigurator: Logger [root] level set to [name="ALL",value=-2147483648].
log4net: XmlHierarchyConfigurator: Loading Appender [INFOFileAppender] type: [log4net.Appender.FileAppender]
log4net: XmlHierarchyConfigurator: Setting Property [LockingModel] to object [log4net.Appender.FileAppender+MinimalLock]
log4net: XmlHierarchyConfigurator: Setting Property [Threshold] to Level value [ALL]
log4net: XmlHierarchyConfigurator: Setting Property [File] to String value [AOKlogs.txt]
log4net: XmlHierarchyConfigurator: Setting Property [AppendToFile] to Boolean value [True]
log4net: XmlHierarchyConfigurator: Parameter [layout] specified subtype [log4net.Layout.PatternLayout]
log4net: PatternParser: Converter [literal] Option [
                ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: XmlHierarchyConfigurator: Setting Property [Layout] to PatternLayout value [log4net.Layout.PatternLayout]
log4net: FileAppender: Opening file for writing [C:\Users\ScarryComp\Documents\Visual Studio 2008\WebSites\WebSite1\AOKlogs.txt] append [True]
log4net: XmlHierarchyConfigurator: Created Appender [INFOFileAppender]
log4net: XmlHierarchyConfigurator: Adding appender named [INFOFileAppender] to logger [root].
log4net: XmlHierarchyConfigurator: Loading Appender [Console] type: [log4net.Appender.ConsoleAppender]
log4net: PatternParser: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: PatternParser: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: XmlHierarchyConfigurator: Setting Property [ConversionPattern] to String value [%d %-5l - %m%n]
log4net: PatternParser: Converter [d] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: PatternParser: Converter [literal] Option [ ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: PatternParser: Converter [l] Option [] Format [min=5,max=2147483647,leftAlign=True]
log4net: PatternParser: Converter [literal] Option [ - ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: PatternParser: Converter [m] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: PatternParser: Converter [n] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: XmlHierarchyConfigurator: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: XmlHierarchyConfigurator: Created Appender [Console]
log4net: XmlHierarchyConfigurator: Adding appender named [Console] to logger [root].
log4net: XmlHierarchyConfigurator: Hierarchy Threshold []

I changed added Console appender but I still don't see text in my logs :(

UPDATE 2:
File appenders didn't work but trace appender appeared to be ok. However, that would be nice if someboydy could explain what could happen to file appenders so the question remains kinda opened

Body:
I could imagine that you have an encoding problem. Log4net uses an ANSI encoding by default, if your server (or service) and your machine do not use the same encoding you would not be able to read the text in the file.

You could try to configure the encoding like this:

<appender name="INFOFileAppender" type="log4net.Appender.FileAppender">
    <encoding value="unicodeFFFE" />
    ...


问:
How to create a Bokeh Tap tool to select all points of the ColumnDataSource sharing the same value in a given column
I have a bunch of data plotted in a scatter plot using a ColumnDataSource and one column is the X coordinates another the Y coordinates. There's a third column with a patient ID that may have duplicates. I'd like to create a Tap derived tool that would select all other x,y coordinates that share the same value in the patient ID column.

```<code>'x'  'y' 'ID'
 1    2   'p1'
 2    3   'p1'
 2    5   'p2'
 0    1   'p2'
</code>```

So basically if I click in my bokeh scatter plot the coordinate (1,2) I'd get points at (1,2) and (2,3) selected with all others unselected much like how you find the lasso and boxselect tools behaving.

答:
Here is an example solution using CustomJS with bokeh 0.12.6. Essentially when the user selects a glyph, you know which row that corresponds to. Look up the associated id value and then add all other data points with the same id to the selected attribute of a ColumnDataSource.

You can also create an equivalent call back using python only. However that will require the use of a bokeh server. The code will also be quite similar.

from bokeh.plotting import figure, output_file, show
    from bokeh.models import ColumnDataSource, CustomJS

```<code># output to static HTML file
output_file("line.html")

p = figure(plot_width=400, plot_height=400,tools=["tap"])

x =[1,2,2,0]
y = [2,3,5,1]
n_id = ['p1','p1','p2','p2']
data = {'x':x,'y':y,'id':n_id}
source = ColumnDataSource(data)

# source callback
code = """
    var data = source.data,
        selected = source.selected['1d']['indices'],
        select_inds = [selected[0]];
    if(selected.length == 1){
        // only consider case where one glyph is selected by user
        selected_id = data['id'][selected[0]]
        for (var i = 0; i < data['x'].length; ++i){
            if(data['id'][i] == selected_id){
                // add all points to selected if their ids coincide with original
                // glyph that was clicked.
                select_inds.push(i)
            }
        }
    }
    source.selected['1d']['indices'] = select_inds
    source.change.emit();
"""
callback = CustomJS(args={'source':source},code=code)
source.callback=callback
p.circle('x','y',source=source, size=20, color="navy", alpha=0.5)
# show the results
show(p)
</code>```

In recent versions of bokeh the notation for accessing the selected indices has been simplified somewhat. For compatibility with bokeh 0.13.0, the JS callback could become:

code = """
    var data = source.data,
        selected = source.selected.indices,
        select_inds = [];
    if(selected.length == 1){
        // only consider case where one glyph is selected by user
        selected_id = data['id'][selected[0]]
        for (var i = 0; i < data['x'].length; ++i){
            if(data['id'][i] == selected_id){
                // add all points to selected if their ids coincide with original
                // glyph that was clicked.
                select_inds.push(i)
            }
        }
    }
    source.selected.indices = select_inds
    source.change.emit();
"""
```

Body:
I have a bunch of data plotted in a scatter plot using a ColumnDataSource and one column is the X coordinates another the Y coordinates. There's a third column with a patient ID that may have duplicates. I'd like to create a Tap derived tool that would select all other x,y coordinates that share the same value in the patient ID column.

'x'  'y' 'ID'
 1    2   'p1'
 2    3   'p1'
 2    5   'p2'
 0    1   'p2'

So basically if I click in my bokeh scatter plot the coordinate (1,2) I'd get points at (1,2) and (2,3) selected with all others unselected much like how you find the lasso and boxselect tools behaving.

Body:
Here is an example solution using CustomJS with bokeh 0.12.6. Essentially when the user selects a glyph, you know which row that corresponds to. Look up the associated id value and then add all other data points with the same id to the selected attribute of a ColumnDataSource.

You can also create an equivalent call back using python only. However that will require the use of a bokeh server. The code will also be quite similar.

from bokeh.plotting import figure, output_file, show
    from bokeh.models import ColumnDataSource, CustomJS

# output to static HTML file
output_file("line.html")

p = figure(plot_width=400, plot_height=400,tools=["tap"])

x =[1,2,2,0]
y = [2,3,5,1]
n_id = ['p1','p1','p2','p2']
data = {'x':x,'y':y,'id':n_id}
source = ColumnDataSource(data)

# source callback
code = """
    var data = source.data,
        selected = source.selected['1d']['indices'],
        select_inds = [selected[0]];
    if(selected.length == 1){
        // only consider case where one glyph is selected by user
        selected_id = data['id'][selected[0]]
        for (var i = 0; i < data['x'].length; ++i){
            if(data['id'][i] == selected_id){
                // add all points to selected if their ids coincide with original
                // glyph that was clicked.
                select_inds.push(i)
            }
        }
    }
    source.selected['1d']['indices'] = select_inds
    source.change.emit();
"""
callback = CustomJS(args={'source':source},code=code)
source.callback=callback
p.circle('x','y',source=source, size=20, color="navy", alpha=0.5)
# show the results
show(p)

In recent versions of bokeh the notation for accessing the selected indices has been simplified somewhat. For compatibility with bokeh 0.13.0, the JS callback could become:

code = """
    var data = source.data,
        selected = source.selected.indices,
        select_inds = [];
    if(selected.length == 1){
        // only consider case where one glyph is selected by user
        selected_id = data['id'][selected[0]]
        for (var i = 0; i < data['x'].length; ++i){
            if(data['id'][i] == selected_id){
                // add all points to selected if their ids coincide with original
                // glyph that was clicked.
                select_inds.push(i)
            }
        }
    }
    source.selected.indices = select_inds
    source.change.emit();
"""

ContentLicense: CC BY-SA 4.0


问:
Codeigniter: INSERT multiple values, UPDATE if already exists
I have a codeigniter query that Insert three foreign keys and 1 amount.

This is my query in the model:

```<code>public function create()
{
  $insert_data = array(
    'student_id' => $this->input->post('feestudentstudent'),
    'schoolyear_id' => $this->input->post('feestudentschoolyear'),
    'feetype_id' => $this->input->post('feestudentfeetype'),
    'feestudent_amount' => $this->input->post('feestudentamount')
  );
  $status = $this->db->insert('tbl_feestudent', $insert_data);
}
</code>```

What I want is if the following three columns inserted is the same, the student_id, schoolyear_id and feetype_id values exists in the same row it will not insert a new row and the amount will just add to the amount of the existing row.

Take Note: It's okay that student_id, and schoolyear_id is the same, what I want is if all the three including feetype_id is the same it will add the amount.

答:
you can put this code on your model

```<code>public function isExists($key,$valkey,$tabel)
{
    $this->db->from($tabel);
    $this->db->where($key,$valkey);
    $num = $this->db->count_all_results();
    if($num == 0)
    {
        return FALSE;
    }else{
        return TRUE;
    }
}
</code>```

and in your controller,you can access those function,so it would be like

```<code>public function create()
{
   $student_id = $this->input->post('feestudentstudent');

   $insert_data = array(
  'student_id' => $this->input->post('feestudentstudent'),
  'schoolyear_id' => $this->input->post('feestudentschoolyear'),
  'feetype_id' => $this->input->post('feestudentfeetype'),
  'feestudent_amount' => $this->input->post('feestudentamount')
  );

  $update_data = array(
  'schoolyear_id' => $this->input->post('feestudentschoolyear'),
  'feetype_id' => $this->input->post('feestudentfeetype'),
  'feestudent_amount' => $this->input->post('feestudentamount')
  );

  //call the function
  $check = $this->(your model)->isExists('student_id',$student_id,'tbl_feestudent');

  if($check)
  {
    $this->db->where('student_id',$student_id);
    $this->db->update('tbl_feestudent', $update_data);
  }
  else
  {
    $this->db->insert('tbl_feestudent', $insert_data);
  }

}
</code>```

Hope this helps :D

Body:
I have a codeigniter query that Insert three foreign keys and 1 amount.

This is my query in the model:

public function create()
{
  $insert_data = array(
    'student_id' => $this->input->post('feestudentstudent'),
    'schoolyear_id' => $this->input->post('feestudentschoolyear'),
    'feetype_id' => $this->input->post('feestudentfeetype'),
    'feestudent_amount' => $this->input->post('feestudentamount')
  );
  $status = $this->db->insert('tbl_feestudent', $insert_data);
}

What I want is if the following three columns inserted is the same, the student_id, schoolyear_id and feetype_id values exists in the same row it will not insert a new row and the amount will just add to the amount of the existing row.

Take Note: It's okay that student_id, and schoolyear_id is the same, what I want is if all the three including feetype_id is the same it will add the amount.

Body:
you can put this code on your model

public function isExists($key,$valkey,$tabel)
{
    $this->db->from($tabel);
    $this->db->where($key,$valkey);
    $num = $this->db->count_all_results();
    if($num == 0)
    {
        return FALSE;
    }else{
        return TRUE;
    }
}

and in your controller,you can access those function,so it would be like

public function create()
{
   $student_id = $this->input->post('feestudentstudent');

   $insert_data = array(
  'student_id' => $this->input->post('feestudentstudent'),
  'schoolyear_id' => $this->input->post('feestudentschoolyear'),
  'feetype_id' => $this->input->post('feestudentfeetype'),
  'feestudent_amount' => $this->input->post('feestudentamount')
  );

  $update_data = array(
  'schoolyear_id' => $this->input->post('feestudentschoolyear'),
  'feetype_id' => $this->input->post('feestudentfeetype'),
  'feestudent_amount' => $this->input->post('feestudentamount')
  );

  //call the function
  $check = $this->(your model)->isExists('student_id',$student_id,'tbl_feestudent');

  if($check)
  {
    $this->db->where('student_id',$student_id);
    $this->db->update('tbl_feestudent', $update_data);
  }
  else
  {
    $this->db->insert('tbl_feestudent', $insert_data);
  }

}

Hope this helps :D


问:
How do I link the data-key attribute of two elements using javascript?
I'd been following the #javascript30 course in which he links the data-key of a div with the data-key of an audio using javascript and a keydown event as follows

html

```<code><div data-key = "65" class = "key">
<kbd> A </kbd> <br> <span> Boom </span>
</div>

<audio data-key = "65" src = "sounds/boom.wav" id = "boom"> </audio>
</code>```

javascript

```<code>function playSound(e)
{
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
audio.play();
}
</code>```

Now I want to play the audio when I click on the div but I don't know how to start. I've attempted this, but it says Uncaught ReferenceError: key is not defined. So how do I get it to play the audio on a click event?

NOTE: I have eight different audio files for eight different divs. Corresponding pairs have the same data-key.

```<code>$(".key").click(function()
{
const audio = document.getElementById(`${this.data-key}`)
console.log(audio);
audio.play();
});
</code>```

答:
There are many ways to do this, using what's familiar to you use this.dataset.key or $(this).data('key'):

$(".key").click(function() {
  const audio = document.querySelector(`audio[data-key="${this.dataset.key}"]`);
  console.log(audio);
  audio.play();
});

function playSound(e) {
  const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
  audio.play();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-key="65" class="key">
  <kbd> A </kbd> <br> <span> Boom </span>
</div>

<audio data-key="65" src="sounds/boom.wav" id="boom"> </audio></code>```

Body:
I'd been following the #javascript30 course in which he links the data-key of a div with the data-key of an audio using javascript and a keydown event as follows

html

 A
  Boom

<audio data-key = "65" src = "sounds/boom.wav" id = "boom"> </audio>

javascript

function playSound(e)
{
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
audio.play();
}

Now I want to play the audio when I click on the div but I don't know how to start. I've attempted this, but it says Uncaught ReferenceError: key is not defined. So how do I get it to play the audio on a click event?

NOTE: I have eight different audio files for eight different divs. Corresponding pairs have the same data-key.

$(".key").click(function()
{
const audio = document.getElementById(`${this.data-key}`)
console.log(audio);
audio.play();
});

Body:
There are many ways to do this, using what's familiar to you use this.dataset.key or $(this).data('key'):

$(".key").click(function() {
  const audio = document.querySelector(`audio[data-key="${this.dataset.key}"]`);
  console.log(audio);
  audio.play();
});

function playSound(e) {
  const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
  audio.play();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-key="65" class="key">
  <kbd> A </kbd> <br> <span> Boom </span>
</div>

<audio data-key="65" src="sounds/boom.wav" id="boom"> </audio>


问:
how do i select and update info in an xml file
so i know how to load the the data from the selected gridview in to text boxes but how do i make it so it will update the selected place info and not make a new place in the file and also delete a selected place from file if i want to.

this is how i currently load to the datagrid

```<code>ds.ReadXml("Database.xml");

string filter = "";
filter = "userdata" + " LIKE '*" + "u" + "*'";
DataView dv = new DataView(ds.Tables[0]);
dv.RowFilter = filter;
dataGridView1.DataSource = dv;
dataGridView1.Columns[4].Visible = false;
</code>```

and how i load in to the text boxes depending on which is clicked

```<code>if (e.RowIndex >= 0)
{

DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
Nametb.Text = row.Cells["name"].Value.ToString();
Locationtb.Text = row.Cells["Location"].Value.ToString();
Infotb.Text = row.Cells["Info"].Value.ToString();
dayvisitcb.Text = row.Cells["Dayvisited"].Value.ToString();

}
</code>```

this is my xml

```<code><root>
  <place>
    <Name>home</Name>
    <Location>x-292 z 277</Location>
    <Info>home</Info>
    <Dayvisited>10</Dayvisited>
  </place>
  <place>
    <Name>town</Name>
    <Location>x 990 z-2485</Location>
    <Info>gas station</Info>
    <Dayvisited>12</Dayvisited>
  </place>
  <place>
    <Name>crossing</Name>
    <Location>x 90 z-2998</Location>
    <Info>working stiff</Info>
    <Dayvisited>11</Dayvisited>
  </place>
</root>
</code>```

this file will contain random names and will contain hundreds of places. but so far i can load places to grid,select a place and the details go in to text boxes for editing but then i can only add it to the list and not just update the selected place or delete it

答:
You better leverage DataBinding. That will do all the heavy lifting, without the need of any coding yourself. You only have to Read and Write the XML file in your dataset.

First in your project add an new item, DataSet (found in Data category), name it Database. Add a DataTable by right clicking on the desgin surface, choose Add > DataTable.  Name your DataTable place. Next add in your table the 4 columns Name, Location, Info and Dayvisited.

In the Properties of the Dataset, empty the field Namespace.

When you're done this will be your result:

Build the project.

Open your Winform in Design mode.

From the Toolbox drag from the category Data the components BindingSource, BindingNavigator, DataGridView and DataSet on your form.

For the DataSource choose the Typed dataset database you created in the previous step.

Click the bindingSource and set the property DataSource to database. Set DataMember to place.

Click the bindingnavigator. Set the property Bindingsource to binsdingSource1 (assuming you left its default name untouced ).

Click the datagridview. Set the property DataSource to bindingSource1.

Add the Textboxes for each field. For each textbox in the properties open the DataBindings category and for the Text property select bindingSource1 -> Name (repeat for the other properties).

Add a button to your form to Load the dataset. This is the code that goes in its click event:

```<code>database2.ReadXml("Database.xml");
this.button2.Enabled = true;
button1.Enabled = false;
</code>```

Add a button to your form to Save the dataset. This is the code that goes in its click event:

```<code>database2.WriteXml("Database.xml");
</code>```

When you're all done this is what your Project should look like:

When you run it and click the load button, select records, add a new record with the navigator and click save, this will be your result:

Body:
so i know how to load the the data from the selected gridview in to text boxes but how do i make it so it will update the selected place info and not make a new place in the file and also delete a selected place from file if i want to.

this is how i currently load to the datagrid

ds.ReadXml("Database.xml");

string filter = "";
filter = "userdata" + " LIKE '*" + "u" + "*'";
DataView dv = new DataView(ds.Tables[0]);
dv.RowFilter = filter;
dataGridView1.DataSource = dv;
dataGridView1.Columns[4].Visible = false;

and how i load in to the text boxes depending on which is clicked

if (e.RowIndex >= 0)
{

DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
Nametb.Text = row.Cells["name"].Value.ToString();
Locationtb.Text = row.Cells["Location"].Value.ToString();
Infotb.Text = row.Cells["Info"].Value.ToString();
dayvisitcb.Text = row.Cells["Dayvisited"].Value.ToString();

}

this is my xml

<root>
  <place>
    <Name>home</Name>
    <Location>x-292 z 277</Location>
    <Info>home</Info>
    <Dayvisited>10</Dayvisited>
  </place>
  <place>
    <Name>town</Name>
    <Location>x 990 z-2485</Location>
    <Info>gas station</Info>
    <Dayvisited>12</Dayvisited>
  </place>
  <place>
    <Name>crossing</Name>
    <Location>x 90 z-2998</Location>
    <Info>working stiff</Info>
    <Dayvisited>11</Dayvisited>
  </place>
</root>

this file will contain random names and will contain hundreds of places. but so far i can load places to grid,select a place and the details go in to text boxes for editing but then i can only add it to the list and not just update the selected place or delete it

Body:
You better leverage DataBinding. That will do all the heavy lifting, without the need of any coding yourself. You only have to Read and Write the XML file in your dataset.

First in your project add an new item, DataSet (found in Data category), name it Database. Add a DataTable by right clicking on the desgin surface, choose Add > DataTable.  Name your DataTable place. Next add in your table the 4 columns Name, Location, Info and Dayvisited.

In the Properties of the Dataset, empty the field Namespace.

When you're done this will be your result:

Build the project.

Open your Winform in Design mode.

From the Toolbox drag from the category Data the components BindingSource, BindingNavigator, DataGridView and DataSet on your form.

For the DataSource choose the Typed dataset database you created in the previous step.

Click the bindingSource and set the property DataSource to database. Set DataMember to place.

Click the bindingnavigator. Set the property Bindingsource to binsdingSource1 (assuming you left its default name untouced ).

Click the datagridview. Set the property DataSource to bindingSource1.

Add the Textboxes for each field. For each textbox in the properties open the DataBindings category and for the Text property select bindingSource1 -> Name (repeat for the other properties).

Add a button to your form to Load the dataset. This is the code that goes in its click event:

database2.ReadXml("Database.xml");
this.button2.Enabled = true;
button1.Enabled = false;

Add a button to your form to Save the dataset. This is the code that goes in its click event:

database2.WriteXml("Database.xml");

When you're all done this is what your Project should look like:

When you run it and click the load button, select records, add a new record with the navigator and click save, this will be your result:


问:
python print all function calls to know the script flow
How can I print every function/method call ?
I have tried to use : python -m trace --trace but it prints also the function inner code... I just want functions names that were called.
using traceback in code prints the last function called before calling the command itself, and the code contains many classes...

答:
You may find -l useful.

main.py:

```<code>def foo():
    pass

def bar():
    pass

foo()
bar()
</code>```

Doing

```<code>$ python -m trace -l main.py
</code>```

outputs

```<code>functions called:
filename: C:\Python34\lib\trace.py, modulename: trace, funcname: _unsettrace
filename: main.py, modulename: main, funcname: <module>
filename: main.py, modulename: main, funcname: bar
filename: main.py, modulename: main, funcname: foo
</code>```

Depending on the number of functions you have, you may find a decorator more suitable:

```<code>def print_deco(func):
    def inner(*args, **kwargs):
        print(func.__name__)
        return func(*args, **kwargs)
    return inner

@print_deco
def foo():
    pass

@print_deco
def bar():
    pass

foo()
bar()

# foo
# bar
</code>```

Body:
You may find -l useful.

main.py:

def foo():
    pass

def bar():
    pass

foo()
bar()

Doing

$ python -m trace -l main.py

outputs

functions called:
filename: C:\Python34\lib\trace.py, modulename: trace, funcname: _unsettrace
filename: main.py, modulename: main, funcname: <module>
filename: main.py, modulename: main, funcname: bar
filename: main.py, modulename: main, funcname: foo

Depending on the number of functions you have, you may find a decorator more suitable:

def print_deco(func):
    def inner(*args, **kwargs):
        print(func.__name__)
        return func(*args, **kwargs)
    return inner

@print_deco
def foo():
    pass

@print_deco
def bar():
    pass

foo()
bar()

# foo
# bar


问:
Is it possible to render table at end tag
Let's say I have a large table (a couple of thousand rows) and I want the whole table to render as fast as possible.

Is it possible to somehow delay rendering of a table until the whole table is downloaded ? Otherwise the width calculations after each row seem to take up too much time.

When I use IE without a declared doctype the browser seem to wait until it gets the table’s closing tag. However when I do declare a doctype the table start rendering at once and therefore have to calculate the table width after each new row.
I don't want to use table-layout:fixed since I don’t want the content to line break where it shouldn’t.

It only seem to be a significant time difference in IE(8)?

(Pagination is not an option)

Thanks!

答:
You can do the following:
use table-layout:fixed on the table, while the data is being downloaded.

And after the closing tag of the table, add a small script, that removes the css.

Example:

```<code><table style='table-layout:fixed' id='data_table'>
<!-- All your data -->
</table>
<script type='text/javascript'>
    document.getElementById('data_table').style.tableLayout = 'auto';
</script>
</code>```

Body:
You can do the following:
use table-layout:fixed on the table, while the data is being downloaded.

And after the closing tag of the table, add a small script, that removes the css.

Example:

<table style='table-layout:fixed' id='data_table'>
<!-- All your data -->
</table>
<script type='text/javascript'>
    document.getElementById('data_table').style.tableLayout = 'auto';
</script>


问:
Can't make AES encryption to be working between PHP and C#
I had spent 3 days, trying to implement a simple encrypted communication in my Unity 3D application. The thing is, that response from the php script is giving me weird characters.

That's my C# code:

```<code>private const string key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

public static string Decrypt(string data)
{
    byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);

    byte[] toDecrypt = Convert.FromBase64String(data);
    RijndaelManaged aes = new RijndaelManaged();

    aes.Key = keyArray;
    aes.Mode = CipherMode.ECB;
    aes.Padding = PaddingMode.Zeros;
    aes.KeySize = 128;
    aes.BlockSize = 128;

    ICryptoTransform cTransform = aes.CreateDecryptor();
    byte[] resultBytes = cTransform.TransformFinalBlock(toDecrypt, 0, toDecrypt.Length);

    return UTF8Encoding.UTF8.GetString(resultBytes);
}

private void Start()
{
    StartCoroutine(test());
}

private IEnumerator test()
{
    for (;;)
    {
        WWW www = new WWW("http://x.com/game/getInfo.php?text=" + Security.Encrypt("test"));
        yield return www;
        Debug.Log(Security.Decrypt(www.text));
        yield return new WaitForSeconds(4f);
    }
}
</code>```

And my php code:

```<code><?php
$key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

function Encrypt($string){
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_ECB));
}

function Decrypt($string){
    return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($string), MCRYPT_MODE_ECB);
}

$toEncrypt = Decrypt($_GET['text']);
echo Encrypt(toEncrypt);
?>
</code>```

Everytime Debug.Log prints another string like "a'�@н���:�j" or "��e?e���\ �V��", instead of "test". I have no idea why. I tried encoding it in UTF8, using openssl methods, changing key length, and I'm still getting these weird characters.

Is there anything I omitted here?

答:
You're not using the same key. Your "key" is a sequence of 32 characters. When encoding that key, you get a byte array of 32 bytes. This is a "key" of 256 bits. When you set aes.KeySize = 128;, this changes the key size that you want, which also generates a completely different key (example).

If you want to use AES-256, then you have to remove aes.KeySize = 128;. Just changing 128 to 256 wouldn't change anything (exmaple).

Security considerations:

The key needs to be similar to random noise. You can generate a random key and store it in encoded form (Hex/Base64) in the source code, but only if the source code or the resulting executable are never given to other parties.

Never use ECB mode. It's deterministic and therefore not semantically secure. You should at the very least use a randomized mode like CBC or CTR. It is better to authenticate your ciphertexts so that attacks like a padding oracle attack are not possible. This can be done with authenticated modes like GCM or EAX, or with an encrypt-then-MAC scheme.

Body:
I had spent 3 days, trying to implement a simple encrypted communication in my Unity 3D application. The thing is, that response from the php script is giving me weird characters.

That's my C# code:

private const string key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

public static string Decrypt(string data)
{
    byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);

    byte[] toDecrypt = Convert.FromBase64String(data);
    RijndaelManaged aes = new RijndaelManaged();

    aes.Key = keyArray;
    aes.Mode = CipherMode.ECB;
    aes.Padding = PaddingMode.Zeros;
    aes.KeySize = 128;
    aes.BlockSize = 128;

    ICryptoTransform cTransform = aes.CreateDecryptor();
    byte[] resultBytes = cTransform.TransformFinalBlock(toDecrypt, 0, toDecrypt.Length);

    return UTF8Encoding.UTF8.GetString(resultBytes);
}

private void Start()
{
    StartCoroutine(test());
}

private IEnumerator test()
{
    for (;;)
    {
        WWW www = new WWW("http://x.com/game/getInfo.php?text=" + Security.Encrypt("test"));
        yield return www;
        Debug.Log(Security.Decrypt(www.text));
        yield return new WaitForSeconds(4f);
    }
}

And my php code:

<?php
$key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

function Encrypt($string){
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $string, MCRYPT_MODE_ECB));
}

function Decrypt($string){
    return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($string), MCRYPT_MODE_ECB);
}

$toEncrypt = Decrypt($_GET['text']);
echo Encrypt(toEncrypt);
?>

Everytime Debug.Log prints another string like "a'�@н���:�j" or "��e?e���\ �V��", instead of "test". I have no idea why. I tried encoding it in UTF8, using openssl methods, changing key length, and I'm still getting these weird characters.

Is there anything I omitted here?


问:
preg_split every character, but don't split if is quote
I'm using the following code to split my UTF-8 strings to characters:

```<code>$characters = preg_split('//u', $word, -1, PREG_SPLIT_NO_EMPTY);
</code>```

In some cases, a character might have a single quote after it. for example: hel'lo. I want to keep that quote with the character before it.

Using the regex above, my array is this:

```<code>Array
(
    [0] => h
    [1] => e
    [2] => l
    [3] => '
    [4] => l
    [5] => o
)
</code>```

And I want the array to be:

```<code>Array
(
    [0] => h
    [1] => e
    [2] => l'
    [3] => l
    [4] => o
)
</code>```

How can I do it?
Thanks!

(the single quote can be at the beginning of the string, at the end of it and in the middle of it).

答:
Rather than split, you can do preg_match_all using

```<code>'?\p{L}'?
</code>```

i.e. an optional ' before and after the Unicode letter:

```<code>preg_match_all("/'?\\p{L}'?/u", $str, $matches);
</code>```

RegEx Demo

Body:
I'm using the following code to split my UTF-8 strings to characters:

$characters = preg_split('//u', $word, -1, PREG_SPLIT_NO_EMPTY);

In some cases, a character might have a single quote after it. for example: hel'lo. I want to keep that quote with the character before it.

Using the regex above, my array is this:

Array
(
    [0] => h
    [1] => e
    [2] => l
    [3] => '
    [4] => l
    [5] => o
)

And I want the array to be:

Array
(
    [0] => h
    [1] => e
    [2] => l'
    [3] => l
    [4] => o
)

How can I do it?
Thanks!

(the single quote can be at the beginning of the string, at the end of it and in the middle of it).

Body:
Rather than split, you can do preg_match_all using

'?\p{L}'?

i.e. an optional ' before and after the Unicode letter:

preg_match_all("/'?\\p{L}'?/u", $str, $matches);

RegEx Demo


问:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'message' in 'field list' (SQL: insert into `messages`
the message controller

please help me find the error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'message' in
'field list' (SQL: insert into messages

答:
You're trying to insert a value to messages column in the database but SQL is complaining that it doesn't exist.

Open phpmyadmin and check if you do indeed have column named messages in the table, if not create one.