问:
How to automatically change text and pictures using a state machine in JavaScript
I have a character, "Pepe". My goal is to display Pepe's mood using a textbox for his state (his mood, "happy", "sad", etc.), another textbox for what he says, and an image that shows how he feels. What I want to do is change his current state with time. After a certain number of seconds, I want his state to change from "Happy" to "Sad", and then continue to change like a real living animal.   I have four states for Pepe: "Happy", "Sad", "Hungry" and "Angry". I have the JavaScript code below. In the HTML, I included buttons so if Pepe is "Hungry", a button can change Pepe from "Hungry" to "Happy". My problem is that I can't get the images to automatically change. I want it to be as random as possible. Any ideas?

```<code>var thePest

function pestConstructor(state,pepe,petimage,counter)
{

 this.state = state
    this.pepe = pepe
    this.petimage = petimage
    this.counter = counter
}
function startup()
{

 thePest = new pestConstructor("Happy","Hi!",
 "https://ih1.redbubble.net/image.141976807.7205/flat,800x800,075,t.jpg",0)

      display(thePest)
      setTimeout("Simulate(thePest)",1000)
}
function display(pest)
{

 var state = pest.state

 if( state == "Angry" )
      {
           pest.pepe = "AHHHH!!!"
           pest.petimage = "http://i0.kym-cdn.com/entries/icons/original/000/017/318/angry_pepe.jpg"
      }
      else if( state == "Happy" )
      {
           pest.pepe = "Hi!"
           pest.petimage = "https://ih1.redbubble.net/image.141976807.7205/flat,800x800,075,t.jpg"
      }
      else if( state == "Hungry" )
      {
           pest.pepe = "FOOD!"
           pest.petimage = "https://pbs.twimg.com/media/CS5XSd1UkAEfpUv.png"
      }
       else if( state == "Sad" )
      {
           pest.pepe = "I'm Sad"
           pest.petimage = "http://i0.kym-cdn.com/photos/images/original/000/945/016/648.png"
      }
      else
      {
          pest.petmood = "Dead"
      }

      document.getElementById("state").value = pest.state
      document.getElementById("pepe").value = pest.pepe
      document.getElementById("petimage").src = pest.petimage
      document.getElementById("counter").value = pest.counter
}
function Simulate(pest)
{

 pest.counter++
 var state = pest.state

      var n = Math.random(pest.state)

      if( state == "Happy" && n < 0.5 )
          pest.state = "Hungry"
      else if( state == "Hungry" && n < 0.4 )
          pest.state = "Angry"
      else if( state == "Angry" && n < 0.42 )
          pest.state = "Sad"
      else if( state == "Sad" && n < 0.43 )
          pest.state = "Sleepy"
      else if( state == "Sleepy" && n < 0.3 )
          pest.state = "Dead"

      display(thePest)
      setTimeout("Simulate(thePest)",1000)
}
function Feed(pest)
{

 var state = pest.state

  if( state == "Hungry" )
          pest.state = "Happy"

         display(thePest)
}
function Love(pest)
{

 var state = pest.state

  if( state == "Sad" )
          pest.state = "Happy"

         display(thePest)
}
function Mad(pest)
{

 var state = pest.state

  if( state == "Mad" )
          pest.state = "Happy"

         display(thePest)
}
function Annoy(pest)
{

 var state = pest.state

  if( state == "Happy" )
          pest.state = "Angry"

         display(thePest)
}
</script>`
</code>```

答:
Seems that the only issue was with the setTimeout function was wrapping the callback in double quotes.

var thePest

function pestConstructor(state,pepe,petimage,counter)
{

 this.state = state
    this.pepe = pepe
    this.petimage = petimage
    this.counter = counter
}
function startup()
{

 thePest = new pestConstructor("Happy","Hi!",
 "https://ih1.redbubble.net/image.141976807.7205/flat,800x800,075,t.jpg",0)

  display(thePest)
  setTimeout(()=>Simulate(thePest),1000)
}
function display(pest)
{

 var state = pest.state

 if( state == "Angry" )
      {
           pest.pepe = "AHHHH!!!"
           pest.petimage = "http://via.placeholder.com/350x150/ff0000/ffffff"
      }
      else if( state == "Happy" )
      {
           pest.pepe = "Hi!"
           pest.petimage = "http://via.placeholder.com/350x150/00ff00/ffffff"
      }
      else if( state == "Hungry" )
      {
           pest.pepe = "FOOD!"
           pest.petimage = "http://via.placeholder.com/350x150/fff0ff/000000"
      }
       else if( state == "Sad" )
      {
           pest.pepe = "I'm Sad"
           pest.petimage = "http://via.placeholder.com/350x150/0000ff/ffffff"
      }
      else
      {
          pest.petmood = "Dead"
      }

      console.log(pest.state, pest.pepe, pest.petimage, pest.counter);
      $("img").attr("src",pest.petimage);
}
function Simulate(pest)
{

 pest.counter++
 var state = pest.state

      var n = Math.random(pest.state)

      if( state == "Happy" && n < 0.5 )
          pest.state = "Hungry"
      else if( state == "Hungry" && n < 0.4 )
          pest.state = "Angry"
      else if( state == "Angry" && n < 0.42 )
          pest.state = "Sad"
      else if( state == "Sad" && n < 0.43 )
          pest.state = "Sleepy"
      else if( state == "Sleepy" && n < 0.3 )
          pest.state = "Dead"

      display(thePest)
      setTimeout("Simulate(thePest)",1000)
}
function Feed(pest)
{

 var state = pest.state

  if( state == "Hungry" )
          pest.state = "Happy"

         display(thePest)
}
function Love(pest)
{

 var state = pest.state

  if( state == "Sad" )
          pest.state = "Happy"

         display(thePest)
}
function Mad(pest)
{

 var state = pest.state

  if( state == "Mad" )
          pest.state = "Happy"

         display(thePest)
}
function Annoy(pest)
{

 var state = pest.state

  if( state == "Happy" )
          pest.state = "Angry"

         display(thePest)
}

startup();```
<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>
<img src="" /></code>```

Body:
I have a character, "Pepe". My goal is to display Pepe's mood using a textbox for his state (his mood, "happy", "sad", etc.), another textbox for what he says, and an image that shows how he feels. What I want to do is change his current state with time. After a certain number of seconds, I want his state to change from "Happy" to "Sad", and then continue to change like a real living animal.   I have four states for Pepe: "Happy", "Sad", "Hungry" and "Angry". I have the JavaScript code below. In the HTML, I included buttons so if Pepe is "Hungry", a button can change Pepe from "Hungry" to "Happy". My problem is that I can't get the images to automatically change. I want it to be as random as possible. Any ideas?

var thePest

function pestConstructor(state,pepe,petimage,counter)
{

 this.state = state
    this.pepe = pepe
    this.petimage = petimage
    this.counter = counter
}
function startup()
{

 thePest = new pestConstructor("Happy","Hi!",
 "https://ih1.redbubble.net/image.141976807.7205/flat,800x800,075,t.jpg",0)

      display(thePest)
      setTimeout("Simulate(thePest)",1000)
}
function display(pest)
{

 var state = pest.state

 if( state == "Angry" )
      {
           pest.pepe = "AHHHH!!!"
           pest.petimage = "http://i0.kym-cdn.com/entries/icons/original/000/017/318/angry_pepe.jpg"
      }
      else if( state == "Happy" )
      {
           pest.pepe = "Hi!"
           pest.petimage = "https://ih1.redbubble.net/image.141976807.7205/flat,800x800,075,t.jpg"
      }
      else if( state == "Hungry" )
      {
           pest.pepe = "FOOD!"
           pest.petimage = "https://pbs.twimg.com/media/CS5XSd1UkAEfpUv.png"
      }
       else if( state == "Sad" )
      {
           pest.pepe = "I'm Sad"
           pest.petimage = "http://i0.kym-cdn.com/photos/images/original/000/945/016/648.png"
      }
      else
      {
          pest.petmood = "Dead"
      }

      document.getElementById("state").value = pest.state
      document.getElementById("pepe").value = pest.pepe
      document.getElementById("petimage").src = pest.petimage
      document.getElementById("counter").value = pest.counter
}
function Simulate(pest)
{

 pest.counter++
 var state = pest.state

      var n = Math.random(pest.state)

      if( state == "Happy" && n < 0.5 )
          pest.state = "Hungry"
      else if( state == "Hungry" && n < 0.4 )
          pest.state = "Angry"
      else if( state == "Angry" && n < 0.42 )
          pest.state = "Sad"
      else if( state == "Sad" && n < 0.43 )
          pest.state = "Sleepy"
      else if( state == "Sleepy" && n < 0.3 )
          pest.state = "Dead"

      display(thePest)
      setTimeout("Simulate(thePest)",1000)
}
function Feed(pest)
{

 var state = pest.state

  if( state == "Hungry" )
          pest.state = "Happy"

         display(thePest)
}
function Love(pest)
{

 var state = pest.state

  if( state == "Sad" )
          pest.state = "Happy"

         display(thePest)
}
function Mad(pest)
{

 var state = pest.state

  if( state == "Mad" )
          pest.state = "Happy"

         display(thePest)
}
function Annoy(pest)
{

 var state = pest.state

  if( state == "Happy" )
          pest.state = "Angry"

         display(thePest)
}
</script>`

Body:
Seems that the only issue was with the setTimeout function was wrapping the callback in double quotes.

var thePest

function pestConstructor(state,pepe,petimage,counter)
{

 this.state = state
    this.pepe = pepe
    this.petimage = petimage
    this.counter = counter
}
function startup()
{

 thePest = new pestConstructor("Happy","Hi!",
 "https://ih1.redbubble.net/image.141976807.7205/flat,800x800,075,t.jpg",0)

  display(thePest)
  setTimeout(()=>Simulate(thePest),1000)
}
function display(pest)
{

 var state = pest.state

 if( state == "Angry" )
      {
           pest.pepe = "AHHHH!!!"
           pest.petimage = "http://via.placeholder.com/350x150/ff0000/ffffff"
      }
      else if( state == "Happy" )
      {
           pest.pepe = "Hi!"
           pest.petimage = "http://via.placeholder.com/350x150/00ff00/ffffff"
      }
      else if( state == "Hungry" )
      {
           pest.pepe = "FOOD!"
           pest.petimage = "http://via.placeholder.com/350x150/fff0ff/000000"
      }
       else if( state == "Sad" )
      {
           pest.pepe = "I'm Sad"
           pest.petimage = "http://via.placeholder.com/350x150/0000ff/ffffff"
      }
      else
      {
          pest.petmood = "Dead"
      }

      console.log(pest.state, pest.pepe, pest.petimage, pest.counter);
      $("img").attr("src",pest.petimage);
}
function Simulate(pest)
{

 pest.counter++
 var state = pest.state

      var n = Math.random(pest.state)

      if( state == "Happy" && n < 0.5 )
          pest.state = "Hungry"
      else if( state == "Hungry" && n < 0.4 )
          pest.state = "Angry"
      else if( state == "Angry" && n < 0.42 )
          pest.state = "Sad"
      else if( state == "Sad" && n < 0.43 )
          pest.state = "Sleepy"
      else if( state == "Sleepy" && n < 0.3 )
          pest.state = "Dead"

      display(thePest)
      setTimeout("Simulate(thePest)",1000)
}
function Feed(pest)
{

 var state = pest.state

  if( state == "Hungry" )
          pest.state = "Happy"

         display(thePest)
}
function Love(pest)
{

 var state = pest.state

  if( state == "Sad" )
          pest.state = "Happy"

         display(thePest)
}
function Mad(pest)
{

 var state = pest.state

  if( state == "Mad" )
          pest.state = "Happy"

         display(thePest)
}
function Annoy(pest)
{

 var state = pest.state

  if( state == "Happy" )
          pest.state = "Angry"

         display(thePest)
}

startup();

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


来源: stackexchange

问:
How to display body and headers before sending POST request?
I use a library requests:

```<code>import requests

r = requests.post(url=url, data=data, headers=headers, auth=(self.api_key, ''))
</code>```

How to display body and headers before sending POST request? or display full request how it is sent?

Because server returns 400 HTTP with message Bad Request. So I need to see what is sending.

When I do:

```<code>print r.request.body
</code>```

It returns:

```<code>subcategory_id=1378&category_id=45&features=id&features=value&features=id&features=value&features=id&features=value&offer_type=18979
</code>```

But body is:

```<code>data = {
            'category_id': category_id,
            'subcategory_id': subcategory_id,
            'offer_type': offer_type,
            'features': [
                {"id": "7", "value": "12900"},
                {"id": "12", "value": "Title adadadadasdasdadad"},
                {"id": "16", "value": ["3360383821"]}
          ]
        }
</code>```

How is it possible?

答:
```<code>r.url
r.headers
r.body
</code>```

should work in the terminal, probably have to print it in a script

You also don't need "url=url", you can just leave it as "url", assuming that's where you've stored the base you're trying to post to.

ContentLicense: CC BY-SA 3.0

Body:
I use a library requests:

import requests

r = requests.post(url=url, data=data, headers=headers, auth=(self.api_key, ''))

How to display body and headers before sending POST request? or display full request how it is sent?

Because server returns 400 HTTP with message Bad Request. So I need to see what is sending.

When I do:

print r.request.body

It returns:

subcategory_id=1378&category_id=45&features=id&features=value&features=id&features=value&features=id&features=value&offer_type=18979

But body is:

data = {
            'category_id': category_id,
            'subcategory_id': subcategory_id,
            'offer_type': offer_type,
            'features': [
                {"id": "7", "value": "12900"},
                {"id": "12", "value": "Title adadadadasdasdadad"},
                {"id": "16", "value": ["3360383821"]}
          ]
        }

How is it possible?

Body:
r.url
r.headers
r.body

should work in the terminal, probably have to print it in a script

You also don't need "url=url", you can just leave it as "url", assuming that's where you've stored the base you're trying to post to.


问:
Asp.net mvc3: How to pull data from database and fill view model in one goal?
I need to pull the data from DB and fill the view model, is there any better way to do this?
Currently I'm doing something like this.</p>

```<code>ViewModel vm = new ViewModel();
var recentBill = context.Money.Take(10);
foreach (var r in recnetBill)
{
    vm.lst.Add(r);
}
</code>```

答:
Assuming your ViewModel looks like this:

```<code>public class ViewModel
{
   IEnumerable<Money> lst { get; set; }
   // other properties
}
</code>```

Just do this:

```<code>public ActionResult GetMonies()
{
   var monies = context.Money
                      .Take(10)
                      .ToList();

   var model = new ViewModel { lst = monies };

   return View(model);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to pull the data from DB and fill the view model, is there any better way to do this?
Currently I'm doing something like this.

ViewModel vm = new ViewModel();
var recentBill = context.Money.Take(10);
foreach (var r in recnetBill)
{
    vm.lst.Add(r);
}

Body:
Assuming your ViewModel looks like this:

public class ViewModel
{
   IEnumerable<Money> lst { get; set; }
   // other properties
}

Just do this:

public ActionResult GetMonies()
{
   var monies = context.Money
                      .Take(10)
                      .ToList();

   var model = new ViewModel { lst = monies };

   return View(model);
}


问:
git command "git checkout master || :"
I am trying to understand this git command.
I have got a software repository which has got submodules and that submodule points to another submodule. In order to check out, this command is used -

```<code>git submodule foreach --recursive 'git checkout master || :'
</code>```

This question is about understanding this command.
What does "|| :" means in this command? I am asking this question so that I can be more flexible in changing these commands according to the need.

In this command - foreach, means for each submodule found go and do a checkout of master but what "|| and :" means here.

答:
command_a || command_b leads bash to execute command_b only if command_a was not executed successfully (command_a returns exit code diffrent to 0). : is an alternative notation for true which is equal to exit code 0

So git checkout master || : will always return true even if git checkout master failed.

Just writing git submodule foreach --recursive 'git checkout master' would interrupt if the checkout was not successful for one of the submodules.

Title: git command "git checkout master || :"

Body:
I am trying to understand this git command.
I have got a software repository which has got submodules and that submodule points to another submodule. In order to check out, this command is used -

git submodule foreach --recursive 'git checkout master || :'

This question is about understanding this command.
What does "|| :" means in this command? I am asking this question so that I can be more flexible in changing these commands according to the need.

In this command - foreach, means for each submodule found go and do a checkout of master but what "|| and :" means here.


问:
Convert comma separated string of floats into list?
I need to define a function txtnum(L) that takes a string of comma separated floats such as "1.5,2.5,3.5" as a parameter and converts it into a list [1.5, 2.5, 3.5].

I have tried using .split(), .join(), map(), etc and cannot get anything to return a list that does NOT include quotations. I'm pretty new to Python and a little lost here.

How would I go about doing this?

答:
1.5,2.5,3.5 is a valid tuple literal in Python (without parentheses, yes, but it doesn't matter), so you can use ast.literal_eval on it:

```<code>In [1]: import ast

In [2]: s = '1.5,2.5,3.5'

In [3]: ast.literal_eval(s)
Out[3]: (1.5, 2.5, 3.5)
</code>```

If you really need a list, that's easy, too:

```<code>In [4]: list(ast.literal_eval(s))
Out[4]: [1.5, 2.5, 3.5]
</code>```

Body:
1.5,2.5,3.5 is a valid tuple literal in Python (without parentheses, yes, but it doesn't matter), so you can use ast.literal_eval on it:

In [1]: import ast

In [2]: s = '1.5,2.5,3.5'

In [3]: ast.literal_eval(s)
Out[3]: (1.5, 2.5, 3.5)

If you really need a list, that's easy, too:

In [4]: list(ast.literal_eval(s))
Out[4]: [1.5, 2.5, 3.5]


问:
How to get notified of a observer's dispose action in a custom Observable in RxJava2
In this thread, a question is posed about how to observe the unsubscribe event so that you can clean up and remove the listener after it's unsubscribed. However, in RxJava2, the method that the above thread no longer works.

```<code>def myObservable = Observable.create({ aEmitter ->
    val listener = {event ->
      aEmitter.onNext(event);
    }
    existingEventSource.addListener(listener)

    // Fails since aEmitter doesn't have an add() method nor does Subscriptions exist.
    aEmitter.add(Subscriptions.create(() -> existingEventSource.removeListener(listener)));
})
</code>```

What is the proper way of addressing this in RxJava2?

答:
Please look at the stringObservable Observable, how to handle subscriptions.

```<code>public class MyTest {
  @Mock private MyService mock;

  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void nam3e() {
    ArrayList<Listener> listeners = new ArrayList<>();

    doAnswer(
            invocation -> {
              Object[] args = invocation.getArguments();
              Listener arg = (Listener) args[0];

              listeners.add(arg);

              return null;
            })
        .when(mock)
        .addListener(any());

    Observable<String> stringObservable =
        Observable.create(
            e -> {
              Listener listener =
                  s -> {
                    e.onNext(s);
                  };

              mock.addListener(listener);

              e.setCancellable(
                  () -> {
                    mock.removeListener(listener);
                  });
            });

    TestObserver<String> test = stringObservable.test();

    Listener listener = listeners.get(0);
    listener.onNext("Wurst");

    test.assertNotComplete().assertValue("Wurst");
    verify(mock, times(1)).addListener(any());

    test.dispose();

    verify(mock, times(1)).removeListener(any());
  }

  public interface MyService {
    void addListener(Listener listener);

    void removeListener(Listener listener);
  }

  @FunctionalInterface
  public interface Listener {
    void onNext(String s);
  }
}
</code>```

Body:
In this thread, a question is posed about how to observe the unsubscribe event so that you can clean up and remove the listener after it's unsubscribed. However, in RxJava2, the method that the above thread no longer works.

def myObservable = Observable.create({ aEmitter ->
    val listener = {event ->
      aEmitter.onNext(event);
    }
    existingEventSource.addListener(listener)

    // Fails since aEmitter doesn't have an add() method nor does Subscriptions exist.
    aEmitter.add(Subscriptions.create(() -> existingEventSource.removeListener(listener)));
})

What is the proper way of addressing this in RxJava2?

Body:
Please look at the stringObservable Observable, how to handle subscriptions.

public class MyTest {
  @Mock private MyService mock;

  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void nam3e() {
    ArrayList<Listener> listeners = new ArrayList<>();

    doAnswer(
            invocation -> {
              Object[] args = invocation.getArguments();
              Listener arg = (Listener) args[0];

              listeners.add(arg);

              return null;
            })
        .when(mock)
        .addListener(any());

    Observable<String> stringObservable =
        Observable.create(
            e -> {
              Listener listener =
                  s -> {
                    e.onNext(s);
                  };

              mock.addListener(listener);

              e.setCancellable(
                  () -> {
                    mock.removeListener(listener);
                  });
            });

    TestObserver<String> test = stringObservable.test();

    Listener listener = listeners.get(0);
    listener.onNext("Wurst");

    test.assertNotComplete().assertValue("Wurst");
    verify(mock, times(1)).addListener(any());

    test.dispose();

    verify(mock, times(1)).removeListener(any());
  }

  public interface MyService {
    void addListener(Listener listener);

    void removeListener(Listener listener);
  }

  @FunctionalInterface
  public interface Listener {
    void onNext(String s);
  }
}


问:
Change color of span tag depending on value

I want to change the color of the message variable in the following HTML:

```<code><span id="mess" style="visibility:visible;">
                <text id="tex">{{ message }}</text>
</span
</code>```

I am using Jinja2 together with Flask - Python to pass a value to the {{ message }}
variable. Here is how I tried to do it:

```<code>$(document).ready(function(){

            if (document.getElementById('tex').value == 'Message sent !')
            {
                document.getElementById('tex').setAttribute("style", "color:green;");
            }
            else
            {
                document.getElementById('tex').setAttribute("style", "color:red;");
            }
});
</code>```

The result of the document.getElementById('tex').value is always undefined and the color of the text of the message variable is always red.

Is there a way with which I can accomplish that ? Thank you in advance.

答:
Lets use contains selector.

$(document).ready(function() {
  if ($('#tex:contains("Message sent !")').length) {
    $('#tex').css('color', 'green');
  } else {
    $('#tex').css('color', 'red');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="mess" style="visibility:visible;">
  <text id="tex">Message sent !</span>
</span></code>```

Body:
I want to change the color of the message variable in the following HTML:

                <text id="tex">{{ message }}</text>
</span

I am using Jinja2 together with Flask - Python to pass a value to the {{ message }}
variable. Here is how I tried to do it:

$(document).ready(function(){

            if (document.getElementById('tex').value == 'Message sent !')
            {
                document.getElementById('tex').setAttribute("style", "color:green;");
            }
            else
            {
                document.getElementById('tex').setAttribute("style", "color:red;");
            }
});

The result of the document.getElementById('tex').value is always undefined and the color of the text of the message variable is always red.

Is there a way with which I can accomplish that ? Thank you in advance.

Body:
Lets use contains selector.

$(document).ready(function() {
  if ($('#tex:contains("Message sent !")').length) {
    $('#tex').css('color', 'green');
  } else {
    $('#tex').css('color', 'red');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="mess" style="visibility:visible;">
  <text id="tex">Message sent !</span>
</span>


问:
Why is my code so slow?
Top-posted (sorry) answer, for those who don't have time to get into it but may have similar problems.

Rule #1, as always, move as much as you can out of loops.

2,  moving TField var := ADODataSet.FieldByname()  out of the loop
3, ADODataSet.DisableControls(); and ADODataSet.EnableControls(); around the loop
4, stringGrid.Rows[r].BeginUpdate() and EndUpdate() on each row (cannot do on teh whle control)
each of these shaved off a few seconds, but I got it down to "faster than the eye can see" by changing

```<code>loop
  stringGrid.RowCount := stringGrid.RowCount + 1;
end loop
</code>```

to putting stringGrid.RowCount := ADODataSet.RecordCount; before the loop

+1 and heartfelt thanks to all who helped.

(now I will go and see what I can do to optimize drawing a TChart, which is also slow ;-)

with about 3,600 rows in the table this takes 45 seconds to populate the string grid. What am I doing wrong?

```
   ADODataSet := TADODataSet.Create(Nil);
   ADODataSet.Connection := AdoConnection;

   ADODataSet.CommandText := 'SELECT * FROM measurements';
   ADODataSet.CommandType := cmdText;
   ADODataSet.Open();

   while not ADODataSet.eof do
   begin
      TestRunDataStringGrid.RowCount := TestRunDataStringGrid.RowCount + 1;

      measurementDateTime   := UnixToDateTime(ADODataSet.FieldByname('time_stamp').AsInteger);
      DoSQlCommandWithResultSet('SELECT * FROM start_time_stamp', AdoConnection, resultSet);
      startDateTime := UnixToDateTime(StrToInt64(resultSet.Strings[0]));
      elapsedTime   := measurementDateTime - startDateTime;
      TestRunDataStringGrid.Cells[0, Pred(TestRunDataStringGrid.RowCount)] := FormatDateTime('hh:mm:ss', elapsedTime);
      TestRunDataStringGrid.Cells[1, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('inputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[2, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('outputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[3, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('flowRate').AsFloat);
      TestRunDataStringGrid.Cells[4, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterPressure').AsFloat * convert);
      TestRunDataStringGrid.Cells[5, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterLevel').AsFloat);
      TestRunDataStringGrid.Cells[6, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('cod').AsFloat);
      ADODataSet.Next;
   end;

   ADODataSet.Close();
   ADODataSet.Free();
```

update:

```
Function  DoSQlCommandWithResultSet(const command : String; AdoConnection : TADOConnection; resultSet : TStringList): Boolean;
  var
        i : Integer;
        AdoQuery : TADOQuery;

begin
  Result := True;
  resultSet.Clear();

  AdoQuery := TADOQuery.Create(nil);
  try
    AdoQuery.Connection := AdoConnection;
    AdoQuery.SQL.Add(command);
    AdoQuery.Open();
    i := 0;
    while not  AdoQuery.eof do
    begin
      resultSet.Add(ADOQuery.Fields[i].Value);
      i := i + 1;
      AdoQuery.Next;
    end;

  finally
    AdoQuery.Close();
    AdoQuery.Free();
  end;
end;

```

答:
instead of calling ADODataSet.FieldByname('Fieldname') inside the loop you should declare local variables of type TField for each field, assign ADODataset.FindField('Fieldname') to the variables and use the variables inside the loop. FindFieldByName searches a list with every call.

Update:

```<code>procedure TForm1.Button1Click(Sender: TObject);
var
  InputTemp, OutputTemp: TField;
begin
  ADODataSet := TADODataSet.Create(Nil);
  try
    ADODataSet.Connection := ADOConnection;
    ADODataSet.CommandText := 'SELECT * FROM measurements';
    ADODataSet.Open;
    InputTemp := ADODataSet.FindField('inputTemperature');
    OutputTemp := ADODataSet.FindField('outputTemperature');
    // assign more fields here
    while not ADODataSet.Eof do begin
      // do something with the fields, for example:
      // GridCell := Format ('%3.2f', [InputTemp.AsFloat]);
      // GridCell := InputTemp.AsString;
      ADODataSet.Next;
    end;
  finally
    ADODataSet.Free;
  end;
end;
</code>```

Another option would be to drop the TADODataset Componont on the form (or use a TDataModule) and define the fields at designtime.

Title: Why is my code so slow?

Body:
Top-posted (sorry) answer, for those who don't have time to get into it but may have similar problems.

Rule #1, as always, move as much as you can out of loops.

2,  moving TField var := ADODataSet.FieldByname()  out of the loop
3, ADODataSet.DisableControls(); and ADODataSet.EnableControls(); around the loop
4, stringGrid.Rows[r].BeginUpdate() and EndUpdate() on each row (cannot do on teh whle control)
each of these shaved off a few seconds, but I got it down to "faster than the eye can see" by changing

loop
  stringGrid.RowCount := stringGrid.RowCount + 1;
end loop

to putting stringGrid.RowCount := ADODataSet.RecordCount; before the loop

+1 and heartfelt thanks to all who helped.

(now I will go and see what I can do to optimize drawing a TChart, which is also slow ;-)

with about 3,600 rows in the table this takes 45 seconds to populate the string grid. What am I doing wrong?

   ADODataSet := TADODataSet.Create(Nil);
   ADODataSet.Connection := AdoConnection;

   ADODataSet.CommandText := 'SELECT * FROM measurements';
   ADODataSet.CommandType := cmdText;
   ADODataSet.Open();

   while not ADODataSet.eof do
   begin
      TestRunDataStringGrid.RowCount := TestRunDataStringGrid.RowCount + 1;

      measurementDateTime   := UnixToDateTime(ADODataSet.FieldByname('time_stamp').AsInteger);
      DoSQlCommandWithResultSet('SELECT * FROM start_time_stamp', AdoConnection, resultSet);
      startDateTime := UnixToDateTime(StrToInt64(resultSet.Strings[0]));
      elapsedTime   := measurementDateTime - startDateTime;
      TestRunDataStringGrid.Cells[0, Pred(TestRunDataStringGrid.RowCount)] := FormatDateTime('hh:mm:ss', elapsedTime);
      TestRunDataStringGrid.Cells[1, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('inputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[2, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('outputTemperature').AsFloat);
      TestRunDataStringGrid.Cells[3, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('flowRate').AsFloat);
      TestRunDataStringGrid.Cells[4, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterPressure').AsFloat * convert);
      TestRunDataStringGrid.Cells[5, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('waterLevel').AsFloat);
      TestRunDataStringGrid.Cells[6, Pred(TestRunDataStringGrid.RowCount)] := FloatToStrWithPrecision(ADODataSet.FieldByname('cod').AsFloat);
      ADODataSet.Next;
   end;

   ADODataSet.Close();
   ADODataSet.Free();

update:

Function  DoSQlCommandWithResultSet(const command : String; AdoConnection : TADOConnection; resultSet : TStringList): Boolean;
  var
        i : Integer;
        AdoQuery : TADOQuery;

begin
  Result := True;
  resultSet.Clear();

  AdoQuery := TADOQuery.Create(nil);
  try
    AdoQuery.Connection := AdoConnection;
    AdoQuery.SQL.Add(command);
    AdoQuery.Open();
    i := 0;
    while not  AdoQuery.eof do
    begin
      resultSet.Add(ADOQuery.Fields[i].Value);
      i := i + 1;
      AdoQuery.Next;
    end;

  finally
    AdoQuery.Close();
    AdoQuery.Free();
  end;
end;

Body:
instead of calling ADODataSet.FieldByname('Fieldname') inside the loop you should declare local variables of type TField for each field, assign ADODataset.FindField('Fieldname') to the variables and use the variables inside the loop. FindFieldByName searches a list with every call.

Update:

procedure TForm1.Button1Click(Sender: TObject);
var
  InputTemp, OutputTemp: TField;
begin
  ADODataSet := TADODataSet.Create(Nil);
  try
    ADODataSet.Connection := ADOConnection;
    ADODataSet.CommandText := 'SELECT * FROM measurements';
    ADODataSet.Open;
    InputTemp := ADODataSet.FindField('inputTemperature');
    OutputTemp := ADODataSet.FindField('outputTemperature');
    // assign more fields here
    while not ADODataSet.Eof do begin
      // do something with the fields, for example:
      // GridCell := Format ('%3.2f', [InputTemp.AsFloat]);
      // GridCell := InputTemp.AsString;
      ADODataSet.Next;
    end;
  finally
    ADODataSet.Free;
  end;
end;

Another option would be to drop the TADODataset Componont on the form (or use a TDataModule) and define the fields at designtime.


问:
Download Neo4j server version 2.0.4
I could not find the Neo4j server version 2.0.4. The older releases that I could find are listed here https://neo4j.com/download/other-releases/. But the oldest release is 2.3.11. Does anyone know where I can find older versions?</p>

答:
You can download Neo4j Enterprise under it's free AGPL open source license directly from Neo4j's public distribution site if you need any version before 3.3.0.

DO NOT download Neo4j Enterprise 3.3.0+ binaries from this site - because they slipped in a commercial license.

Here are the direct links:

http://dist.neo4j.org/neo4j-enterprise-2.0.4-windows.zip

http://dist.neo4j.org/neo4j-enterprise-2.0.4-unix.tar.gz

Unzip or untar it and start it up.

If you want Neo4j Enterprise open source binaries after 3.3.0 - then you can get them from my company's distribution site we set up for our US federal government agency clients.

You can also compile the packages from source up until 3.3.0 - but they removed the 'packaging instructions' for Neo4j Enterprise in 3.3.0.

Here is a blog post I wrote explaining what changes after Neo4j Enterprise 3.3.0

https://blog.igovsol.com/2017/11/14/Neo4j-330-is-out-but-where-are-the-open-source-enterprise-binaries.html

I would just use those links above for Neo4j's official distribution.

Title: Download Neo4j server version 2.0.4


问:
Getting 'Void not assignable to boolean" error using .find() method
The problem comes from this line of code.

```<code>const t: GridType   = gridDef.find( a => { a.GridName == core.GridStyle; return a; } );
</code>```

The error I'm getting is this

ERROR in src/app/grid-builder/builder-scratch.ts(255,43): error TS2345: Argument
   of type '(this: void, a: GridType) => void' is not assignable to parameter of t
  ype '(this: void, value: GridType, index: number, obj: GridType[]) => boolean'.
    Type 'void' is not assignable to type 'boolean'.

I'm defining a class to extend to my Angular Components for dynamically creating grids which so far looks like this.

```<code>export class GridBuilder{
    Settings : GridInit;
    GridData : GridType[];
    Grid     : string    = '';

    constructor() {
        this.Settings.GridStyle = 'SiteGridA';
        this.GridData = GridDefs;
        this.buildGrid( this.Settings, this.GridData );
    }

    buildGrid( core: GridInit, gridData: GridType[] ) {
        const w: number     = multiply( core.Size.Width, core.Size.PixelRatio );
        const h: number     = multiply( core.Size.Height, core.Size.PixelRatio );
        const o: string     = checkOrientation( w, h );
        const c: CellSpecs  = calcCell( o, w );
        const t: GridType   = gridData.find( a => { a.GridName == core.GridStyle; return a; } );

        const cols: string  = calcArea( t.Columns, c );
        const rows: string  = calcArea( t.Rows, c );

        this.Grid = cols + '/' + rows;
    }
}
</code>```

The GridType[] being referred to looks like this

```<code>export interface GridType {
    GridName : string;
    Columns  : GridLine[];
    Rows     : GridLine[];
}

//other interfaces chaining into it
export interface GridLine {
    Names    : LineName[];
    Type     : string;
    CalcType : string;
    CSize    : CellSize;
}

export interface LineName { Name: string; }

export interface CellSize {
    Size?   : number;
    Repeat? : number;
    Min?    : number;
    Max?    : number;
}
</code>```

If we focus back on the constructor

```<code>constructor() {
    this.Settings.GridStyle = 'SiteGridA';
    this.GridData = GridDefs;
    this.buildGrid( this.Settings, this.GridData );
}
</code>```

what I'm trying accomplish is

Set parameter to SiteGridA to be matched in the .find() method to retrive data about the grid.

Saving the grid data to a variable that the .find() method will search through.

Pass variables into function to build grid.

The GridDefs is the definitions of the grids which looks pretty much like this

```<code>    export const GridDefs: GridType[] = [
    {
        GridName : 'SiteGridA',
        Columns  : [
            {
                Names    : [ { Name: 'left-bleed-start' } ],
                Type     : 'normal',
                CalcType : 'divide',
                CSize : { Size: 4 }
            },
            {
                Names    : [ { Name: 'left-bleed-end'}, { Name: 'content-col-start' } ],
                Type     : 'normal',
                CalcType : 'multiply',
                CSize : { Size: 32.5 }
            },
            {
                Names    : [ { Name: 'content-col-end' }, { Name: 'right-bleed-start' } ],
                Type     : 'normal',
                CalcType : 'divide',
                CSize : { Size: 4 }
            },
            {
                Names    : [ { Name: 'right-bleed-end' } ],
                Type     : 'end',
                CalcType : 'none',
                CSize : { Size: null }
            }
        ],
        Rows     : [
            {
                Names    : [ { Name: 'top-bleed-start' } ],
                Type     : 'normal',
                CalcType : 'divide',
                CSize : { Size: 4 }
            },
            {
                Names    : [ { Name: 'top-bleed-end' }, { Name: 'link-row-start' } ],
                Type     : 'normal',
                CalcType : 'multiply',
                CSize : { Size: 2 }
            },
            {
                Names    : [ {Name: 'link-row-end'}, { Name: 'content-row-start' } ],
                Type     : 'normal',
                CalcType : 'none',
                CSize : { Size: 0 }
            },
            {
                Names    : [ { Name: 'content-row-end' }, { Name: 'footer-row-start' } ],
                Type     : 'normal',
                CalcType : 'multiply',
                CSize : { Size: 4}
            },
            {
                Names    : [ { Name: 'footer-row-end' }, { Name: 'bottom-bleed-start' } ],
                Type     : 'normal',
                CalcType : 'divide',
                CSize : { Size: 4 }
            },
            {
                Names    : [ { Name: 'bottom-bleed-end' } ],
                Type     : 'end',
                CalcType : 'none',
                CSize : { Size: null }
            }
        ]
    },
    {
        GridName : 'LinkContainerA',
        Columns  : [
            {
                Names    : [ { Name: 'main-link-col-start' } ],
                Type     : 'normal',
                CalcType : 'none',
                CSize : { Size: 0 }
            },
            {
                Names    : [ { Name: 'main-link-col-end' }, { Name: 'feature-link-start' } ],
                Type     : 'normal',
                CalcType : 'percent',
                CSize : { Size: 50 }
            },
            {
                Names    : [ { Name: 'feature-link-end' } ],
                Type     : 'end',
                CalcType : 'none',
                CSize : { Size: null }
            }

        ],
        Rows     : [
            {
                Names    : [ { Name: 'content-row-sart' } ],
                Type     : 'normal',
                CalcType : 'none',
                CSize : { Size: 0 }
            },
            {
                Names    : [ { Name: 'content-row-end' } ],
                Type     : 'end',
                CalcType : 'none',
                CSize : { Size: null }
            }
        ]
    }
]
</code>```

The GridName property is what I'm attempting to match the GridStyle parameter in the Settings variable to inside the line of code causing the error.

So far I've tried adding OnInit to see if maybe loading the grid Data before the constructor kicked in would help. I tried 1 and 3 = signs, I tried switching const for let.  I  really don't know what to do beyond  this.  I've used the .find() method in similar instances and haven't had a problem.  How can I fix this?

答:
After filling all the missing parts, I'm getting different error than the one in your question:

```<code>const t: GridType   = gridData.find( a => { a.GridName == core.GridStyle; return a; } );

Argument of type '(this: void, a: GridType) => GridType'
   is not assignable to parameter of type
     '(value: GridType, index: number, obj: GridType[]) => boolean'.
          Type 'GridType' is not assignable to type 'boolean'.
</code>```

Now it says Type 'GridType' is not assignable to type 'boolean'. This is because the callback you are passing to find

```<code>{ a.GridName == core.GridStyle; return a; }
</code>```

returns a which has GridType, and find expects a callback that returns boolean.

The error in your question says

```<code>Type 'void' is not assignable to type 'boolean'.
</code>```

That's probably because originally it was written as

```<code>const t: GridType   = gridData.find( a => { a.GridName == core.GridStyle; } );
</code>```

and when you have code in braces without return statement, it's assumed to return void.

If you need to find a grid with particular style, you need to return a result of comparison a.GridName == code.GridStyle. You can do that with a simple expression without surrounding braces after =>, like this:

```<code>const t: GridType   = gridData.find( a => a.GridName == core.GridStyle );
</code>```

or with braces and return statement that returns correct (and correctly typed) value, like this:

```<code>const t: GridType   = gridData.find( a => { return a.GridName == core.GridStyle; } );
</code>```

Body:
The problem comes from this line of code.

const t: GridType   = gridDef.find( a => { a.GridName == core.GridStyle; return a; } );

The error I'm getting is this

ERROR in src/app/grid-builder/builder-scratch.ts(255,43): error TS2345: Argument
   of type '(this: void, a: GridType) => void' is not assignable to parameter of t
  ype '(this: void, value: GridType, index: number, obj: GridType[]) => boolean'.
    Type 'void' is not assignable to type 'boolean'.

I'm defining a class to extend to my Angular Components for dynamically creating grids which so far looks like this.

export class GridBuilder{
    Settings : GridInit;
    GridData : GridType[];
    Grid     : string    = '';

    constructor() {
        this.Settings.GridStyle = 'SiteGridA';
        this.GridData = GridDefs;
        this.buildGrid( this.Settings, this.GridData );
    }

    buildGrid( core: GridInit, gridData: GridType[] ) {
        const w: number     = multiply( core.Size.Width, core.Size.PixelRatio );
        const h: number     = multiply( core.Size.Height, core.Size.PixelRatio );
        const o: string     = checkOrientation( w, h );
        const c: CellSpecs  = calcCell( o, w );
        const t: GridType   = gridData.find( a => { a.GridName == core.GridStyle; return a; } );

        const cols: string  = calcArea( t.Columns, c );
        const rows: string  = calcArea( t.Rows, c );

        this.Grid = cols + '/' + rows;
    }
}

The GridType[] being referred to looks like this

export interface GridType {
    GridName : string;
    Columns  : GridLine[];
    Rows     : GridLine[];
}

//other interfaces chaining into it
export interface GridLine {
    Names    : LineName[];
    Type     : string;
    CalcType : string;
    CSize    : CellSize;
}

export interface LineName { Name: string; }

export interface CellSize {
    Size?   : number;
    Repeat? : number;
    Min?    : number;
    Max?    : number;
}

If we focus back on the constructor

constructor() {
    this.Settings.GridStyle = 'SiteGridA';
    this.GridData = GridDefs;
    this.buildGrid( this.Settings, this.GridData );
}

what I'm trying accomplish is

Set parameter to SiteGridA to be matched in the .find() method to retrive data about the grid.

Saving the grid data to a variable that the .find() method will search through.

Pass variables into function to build grid.

The GridDefs is the definitions of the grids which looks pretty much like this

    export const GridDefs: GridType[] = [
    {
        GridName : 'SiteGridA',
        Columns  : [
            {
                Names    : [ { Name: 'left-bleed-start' } ],
                Type     : 'normal',
                CalcType : 'divide',
                CSize : { Size: 4 }
            },
            {
                Names    : [ { Name: 'left-bleed-end'}, { Name: 'content-col-start' } ],
                Type     : 'normal',
                CalcType : 'multiply',
                CSize : { Size: 32.5 }
            },
            {
                Names    : [ { Name: 'content-col-end' }, { Name: 'right-bleed-start' } ],
                Type     : 'normal',
                CalcType : 'divide',
                CSize : { Size: 4 }
            },
            {
                Names    : [ { Name: 'right-bleed-end' } ],
                Type     : 'end',
                CalcType : 'none',
                CSize : { Size: null }
            }
        ],
        Rows     : [
            {
                Names    : [ { Name: 'top-bleed-start' } ],
                Type     : 'normal',
                CalcType : 'divide',
                CSize : { Size: 4 }
            },
            {
                Names    : [ { Name: 'top-bleed-end' }, { Name: 'link-row-start' } ],
                Type     : 'normal',
                CalcType : 'multiply',
                CSize : { Size: 2 }
            },
            {
                Names    : [ {Name: 'link-row-end'}, { Name: 'content-row-start' } ],
                Type     : 'normal',
                CalcType : 'none',
                CSize : { Size: 0 }
            },
            {
                Names    : [ { Name: 'content-row-end' }, { Name: 'footer-row-start' } ],
                Type     : 'normal',
                CalcType : 'multiply',
                CSize : { Size: 4}
            },
            {
                Names    : [ { Name: 'footer-row-end' }, { Name: 'bottom-bleed-start' } ],
                Type     : 'normal',
                CalcType : 'divide',
                CSize : { Size: 4 }
            },
            {
                Names    : [ { Name: 'bottom-bleed-end' } ],
                Type     : 'end',
                CalcType : 'none',
                CSize : { Size: null }
            }
        ]
    },
    {
        GridName : 'LinkContainerA',
        Columns  : [
            {
                Names    : [ { Name: 'main-link-col-start' } ],
                Type     : 'normal',
                CalcType : 'none',
                CSize : { Size: 0 }
            },
            {
                Names    : [ { Name: 'main-link-col-end' }, { Name: 'feature-link-start' } ],
                Type     : 'normal',
                CalcType : 'percent',
                CSize : { Size: 50 }
            },
            {
                Names    : [ { Name: 'feature-link-end' } ],
                Type     : 'end',
                CalcType : 'none',
                CSize : { Size: null }
            }

        ],
        Rows     : [
            {
                Names    : [ { Name: 'content-row-sart' } ],
                Type     : 'normal',
                CalcType : 'none',
                CSize : { Size: 0 }
            },
            {
                Names    : [ { Name: 'content-row-end' } ],
                Type     : 'end',
                CalcType : 'none',
                CSize : { Size: null }
            }
        ]
    }
]

The GridName property is what I'm attempting to match the GridStyle parameter in the Settings variable to inside the line of code causing the error.

So far I've tried adding OnInit to see if maybe loading the grid Data before the constructor kicked in would help. I tried 1 and 3 = signs, I tried switching const for let.  I  really don't know what to do beyond  this.  I've used the .find() method in similar instances and haven't had a problem.  How can I fix this?

Body:
After filling all the missing parts, I'm getting different error than the one in your question:

const t: GridType   = gridData.find( a => { a.GridName == core.GridStyle; return a; } );

Argument of type '(this: void, a: GridType) => GridType'
   is not assignable to parameter of type
     '(value: GridType, index: number, obj: GridType[]) => boolean'.
          Type 'GridType' is not assignable to type 'boolean'.

Now it says Type 'GridType' is not assignable to type 'boolean'. This is because the callback you are passing to find

{ a.GridName == core.GridStyle; return a; }

returns a which has GridType, and find expects a callback that returns boolean.

The error in your question says

Type 'void' is not assignable to type 'boolean'.

That's probably because originally it was written as

const t: GridType   = gridData.find( a => { a.GridName == core.GridStyle; } );

and when you have code in braces without return statement, it's assumed to return void.

If you need to find a grid with particular style, you need to return a result of comparison a.GridName == code.GridStyle. You can do that with a simple expression without surrounding braces after =>, like this:

const t: GridType   = gridData.find( a => a.GridName == core.GridStyle );

or with braces and return statement that returns correct (and correctly typed) value, like this:

const t: GridType   = gridData.find( a => { return a.GridName == core.GridStyle; } );


问:
PHP MySQL optimal way to perform multiple dependent queries
I need to query (read) some data, and analyze it before performing another query (read) on a different table.

I've looked at mysqli multiple statements but they don't have documentation for situations where the second query depends on the result of the first query.

It seems my current code of doing two queries might not be optimal. Is there a more optimal way to do this?

```<code>//FIRST QUERY
$query1= "SELECT color FROM products WHERE type = '$productType';";
$result = $conn->query($query1);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $colorProduct = $row["color"];
    }
}

//ANALYZE SEARCH RESULT FROM FIRST QUERY
if ($colorProduct == "green") {
    $colorType = "greenColorType";
}
//a lot more analysis

//SECOND QUERY
$query2 = "SELECT price FROM Vendors WHERE color = '$colorType';";
$result2 = $conn->query($query2);

if ($result2->num_rows > 0) {
    while($row = $result2->fetch_assoc()) {
        $priceOfProduct = priceOfProduct . $row["price"];
    }
}

$conn->close();
</code>```

Thank you in advance.

答:
Looks like your color values in the vendors table all have ColorType added after the actual colour name, which you are dealing with in PHP, before making a second query.

Mysql can do this for you. Here's an example:

```<code>"SELECT a.color, b.price FROM products a, vendors b WHERE a.type = '$productType' AND a.color = SUBSTR(b.color,1,LENGTH(a.color);"
</code>```

The WHERE clause specifies a match on your $productType variable with the type column of table a (products) and a match between the color value in table a and the beginning of the color value in table b. It uses the LENGTH statement to match regardless of the length of the color in table a. So if color in table a is darkblue and table b is darkblueColorType it will match, and if the values are red and redColorType it will still match.

Body:
I need to query (read) some data, and analyze it before performing another query (read) on a different table.

I've looked at mysqli multiple statements but they don't have documentation for situations where the second query depends on the result of the first query.

It seems my current code of doing two queries might not be optimal. Is there a more optimal way to do this?

//FIRST QUERY
$query1= "SELECT color FROM products WHERE type = '$productType';";
$result = $conn->query($query1);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $colorProduct = $row["color"];
    }
}

//ANALYZE SEARCH RESULT FROM FIRST QUERY
if ($colorProduct == "green") {
    $colorType = "greenColorType";
}
//a lot more analysis

//SECOND QUERY
$query2 = "SELECT price FROM Vendors WHERE color = '$colorType';";
$result2 = $conn->query($query2);

if ($result2->num_rows > 0) {
    while($row = $result2->fetch_assoc()) {
        $priceOfProduct = priceOfProduct . $row["price"];
    }
}

$conn->close();

Thank you in advance.

Body:
Looks like your color values in the vendors table all have ColorType added after the actual colour name, which you are dealing with in PHP, before making a second query.

Mysql can do this for you. Here's an example:

"SELECT a.color, b.price FROM products a, vendors b WHERE a.type = '$productType' AND a.color = SUBSTR(b.color,1,LENGTH(a.color);"

The WHERE clause specifies a match on your $productType variable with the type column of table a (products) and a match between the color value in table a and the beginning of the color value in table b. It uses the LENGTH statement to match regardless of the length of the color in table a. So if color in table a is darkblue and table b is darkblueColorType it will match, and if the values are red and redColorType it will still match.


问:
Split string on a number, preserving the number
I have a string which will always be at least a number, but can also contain letters before and/or after the number:

```<code>"4"
"Section 2"
"4 Section"
"Section 5 Aisle"
</code>```

I need to split the string like this:

```<code>"4" becomes "4"
"Section 2" becomes "Section ","2"
"4 Aisle" becomes "4"," Aisle"
"Section 5 Aisle" becomes "Section ","5"," Aisle"
</code>```

How can I do this with Ruby 1.9.2?

答:
String#split will keep any groups from the delimiter regexp in the result array.

```<code>parts = whole.split(/(\d+)/)
</code>```

Body:
I have a string which will always be at least a number, but can also contain letters before and/or after the number:

"4"
"Section 2"
"4 Section"
"Section 5 Aisle"

I need to split the string like this:

"4" becomes "4"
"Section 2" becomes "Section ","2"
"4 Aisle" becomes "4"," Aisle"
"Section 5 Aisle" becomes "Section ","5"," Aisle"

How can I do this with Ruby 1.9.2?

Body:
String#split will keep any groups from the delimiter regexp in the result array.

parts = whole.split(/(\d+)/)


问:
Django ajax returning null
I'm using Django to handle a form that sends a post request to a view and ajax is supposed to return that without refreshing the page.
Here's my Jquery with ajax:

```<code>$('.createFolder').on('submit', function(event){
  event.preventDefault();
  var folderName = $('#folderName').val();
  $.ajax({
    url: '{% url 'project:createFolder' %}',
    type: 'post',
    data: {
      'folderName': folderName,
      csrfmiddlewaretoken: '{{ csrf_token }}'
    },
    dataType: 'json',
    success: function(json) {
      alert(json);
    }
  });
});
</code>```

Here's my view:

```<code>class createFolder(TemplateView):
template_name = "project/createFolder.html"

def post(self, request):
    folderName = request.GET.get('folderName')
    return JsonResponse(folderName, safe=False)
</code>```

When running this the response I get displays "null". I'm not sure what is wrong here. Can anyone advise?

Thanks

答:
Since you are making a POST request, you should fetch the data from request.POST instead of request.GET.

```<code>folderName = request.POST.get(‘folderName’)
</code>```

Title: Django ajax returning null

Body:
I'm using Django to handle a form that sends a post request to a view and ajax is supposed to return that without refreshing the page.
Here's my Jquery with ajax:

$('.createFolder').on('submit', function(event){
  event.preventDefault();
  var folderName = $('#folderName').val();
  $.ajax({
    url: '{% url 'project:createFolder' %}',
    type: 'post',
    data: {
      'folderName': folderName,
      csrfmiddlewaretoken: '{{ csrf_token }}'
    },
    dataType: 'json',
    success: function(json) {
      alert(json);
    }
  });
});

Here's my view:

class createFolder(TemplateView):
template_name = "project/createFolder.html"

def post(self, request):
    folderName = request.GET.get('folderName')
    return JsonResponse(folderName, safe=False)

When running this the response I get displays "null". I'm not sure what is wrong here. Can anyone advise?

Thanks

Body:
Since you are making a POST request, you should fetch the data from request.POST instead of request.GET.

folderName = request.POST.get(‘folderName’)


问:
WIN32 How to make multiple checkboxes and manage them differently?
I am trying to write a program in c++ win32 in which i need to have multiple check boxes. To be more specific, this program has multiple "pages" (after the user clicks the next button i delete any child windows and replace them with new ones).
So, to keep the code understandable, i need a function that when is called brings up a couple of fields (i know how to handle those) and some check boxes. The problem is that i don't know how to manage the HWND for each one and so any box i click just runs the same code (and does not check any of the boxes).
MSDN does not offer much help and the only source of information i found was this how to make checkbox in win32?
This is the part in my code in which the problem arrives.

```<code>/* checked_box1 , checked_box2 are globals */
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam,
LPARAM lParam)
{
    switch (message)
{
    case WM_CREATE:
        draw_obtions_screen(hwnd);
        break;
    case WM_COMMAND:
        checked_box1 = IsDlgButtonChecked(draw_object, 1);
        if (checked_box1) {
            CheckDlgButton(hwnd, 1, BST_UNCHECKED);
         SetWindowText(hwnd, TEXT("y"));
        } else {
         CheckDlgButton(hwnd, 1, BST_CHECKED);
         SetWindowText(hwnd,"x");
        }
        checked_box2 = IsDlgButtonChecked(draw_object1, 1);
        if (checked_box2) {
            CheckDlgButton(hwnd, 1, BST_UNCHECKED);
         SetWindowText(hwnd, TEXT("Y"));
        } else {
         CheckDlgButton(hwnd, 1, BST_CHECKED);
         SetWindowText(hwnd,"X");
        }
    case WM_DESTROY:
        PostQuitMessage (0);
        break;
    default:
        return DefWindowProc (hwnd, message, wParam, lParam);
}

return 0;
}

 ......

/* HWND draw_object,draw_object1 are global. The function is also prev declared*/
void draw_obtions_screen(HWND hwnd)
{
     draw_object = CreateWindow ("BUTTON","check",
                   WS_VISIBLE  | WS_CHILD | BS_CHECKBOX,
                   110, 10 ,100 ,30,
                   hwnd, NULL,NULL,NULL);
     CheckDlgButton(hwnd, 1, BST_CHECKED);

     draw_object1 = CreateWindow ("BUTTON","check another",
                   WS_VISIBLE  | WS_CHILD | BS_CHECKBOX,
                   110, 60 ,130 ,30,
                   hwnd, NULL,NULL,NULL);
    CheckDlgButton(hwnd, 1, BST_UNCHECKED);
}
</code>```

The code changes the title of the window to "X" (on any box i click) and then nothing.

I will apreciate any kind of information source or answer. Also please leave some information sources for me to further learn. Thanks!

答:
You assign the child ID through the HMENU parameter to CreateWindowo for any window that has the WS_CHILD style (that is, a child window gets a ID rather than  a menu).

That ID is then sent as part of all the WM_COMMAND messages.

Body:
I am trying to write a program in c++ win32 in which i need to have multiple check boxes. To be more specific, this program has multiple "pages" (after the user clicks the next button i delete any child windows and replace them with new ones).
So, to keep the code understandable, i need a function that when is called brings up a couple of fields (i know how to handle those) and some check boxes. The problem is that i don't know how to manage the HWND for each one and so any box i click just runs the same code (and does not check any of the boxes).
MSDN does not offer much help and the only source of information i found was this how to make checkbox in win32?
This is the part in my code in which the problem arrives.

/* checked_box1 , checked_box2 are globals */
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam,
LPARAM lParam)
{
    switch (message)
{
    case WM_CREATE:
        draw_obtions_screen(hwnd);
        break;
    case WM_COMMAND:
        checked_box1 = IsDlgButtonChecked(draw_object, 1);
        if (checked_box1) {
            CheckDlgButton(hwnd, 1, BST_UNCHECKED);
         SetWindowText(hwnd, TEXT("y"));
        } else {
         CheckDlgButton(hwnd, 1, BST_CHECKED);
         SetWindowText(hwnd,"x");
        }
        checked_box2 = IsDlgButtonChecked(draw_object1, 1);
        if (checked_box2) {
            CheckDlgButton(hwnd, 1, BST_UNCHECKED);
         SetWindowText(hwnd, TEXT("Y"));
        } else {
         CheckDlgButton(hwnd, 1, BST_CHECKED);
         SetWindowText(hwnd,"X");
        }
    case WM_DESTROY:
        PostQuitMessage (0);
        break;
    default:
        return DefWindowProc (hwnd, message, wParam, lParam);
}

return 0;
}

 ......

/* HWND draw_object,draw_object1 are global. The function is also prev declared*/
void draw_obtions_screen(HWND hwnd)
{
     draw_object = CreateWindow ("BUTTON","check",
                   WS_VISIBLE  | WS_CHILD | BS_CHECKBOX,
                   110, 10 ,100 ,30,
                   hwnd, NULL,NULL,NULL);
     CheckDlgButton(hwnd, 1, BST_CHECKED);

     draw_object1 = CreateWindow ("BUTTON","check another",
                   WS_VISIBLE  | WS_CHILD | BS_CHECKBOX,
                   110, 60 ,130 ,30,
                   hwnd, NULL,NULL,NULL);
    CheckDlgButton(hwnd, 1, BST_UNCHECKED);
}

The code changes the title of the window to "X" (on any box i click) and then nothing.

I will apreciate any kind of information source or answer. Also please leave some information sources for me to further learn. Thanks!


问:
Open Pikaday in a AngulasJS directive
It's being difficult to display the Pikaday in a AngularJS directive. For exemple:

index.html:

```<code><my-directive></my-directive>
</code>```

controller.js

```<code>MyApp.directive('myDirective', function(){
    return{
        restrict: 'E',
        templateUrl: ".../my-directive.html",
    };
});
</code>```

my-directive.html:

```<code><input  id="view_service" type="text" readonly>
<div id="view_service_cont"></div>
</code>```

Pikaday config:

```<code>const view_datepiker = new Pikaday({
    field: document.getElementById('view_service'),
    container: document.getElementById('view_service_cont'),
    format: 'DD/MM/YYYY',
    firstDay: 1,
    minDate: new Date(2017, 0, 1), //Será necessário automatizar a data do calendário
    maxDate: new Date(2019, 12, 31),
    yearRange: [2017,2019],
    onSelect: function() {
        $scope.reset_pax();
        $scope.$digest();
        $scope.sale_form.date_selected = view_datepiker.getDate();
        //$('#datepicker').css('border-color','#78FA89');
        //$('#pax_num_container').css('border-color','#cccccc');
    },
    i18n: {
                previousMonth : 'Último mês',
                nextMonth     : 'Próximo mês',
                months        : ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
                weekdays      : ['Domingo','Segunda-Feira','Terça-Feira','Quarta-Feira','Quinta-Feira','Sexta-Feira','Sábado'],
                weekdaysShort : ['Dom','Seg','Ter','Qua','Qui','Sex','Sab']
            },
    disableDayFn: function(theDate) {
        theDate = theDate.toISOString().split('T')[0];
        if ($scope.current_service.availabilities.hasOwnProperty(theDate)) {
            return 0;
        }else {
            return 1;
        }
    }
});
</code>```

When I tested the input directly in the index.html, it worked fine. But now I have created this directive to make the things simpler and when I click in the  field the datepiker does not show up.

Does anybody know how to show the Pikaday in a AngularJS directive?

答:
Investigation: I've added this code:

```<code>console.log($('#view_service')[0]);
</code>```

When the element <input id="view_service" type="text" readonly> is in the index.html the console log returns the following text: <input id="view_service" type="text" readonly>

When the same element is in a angularJS directive it returns: undefined

My Suggestion Since the page takes some time to load, the Pikaday configuration loads before the directive, so the element was not loaded on the DOM.

Solution: I put the Pikaday configuration after the code responsible to inform when the page is loaded and it worked fine.

I hope it can help people with the same issue!

Title: Open Pikaday in a AngulasJS directive

Body:
It's being difficult to display the Pikaday in a AngularJS directive. For exemple:

index.html:

<my-directive></my-directive>

controller.js

MyApp.directive('myDirective', function(){
    return{
        restrict: 'E',
        templateUrl: ".../my-directive.html",
    };
});

my-directive.html:

<input  id="view_service" type="text" readonly>

Pikaday config:

const view_datepiker = new Pikaday({
    field: document.getElementById('view_service'),
    container: document.getElementById('view_service_cont'),
    format: 'DD/MM/YYYY',
    firstDay: 1,
    minDate: new Date(2017, 0, 1), //Será necessário automatizar a data do calendário
    maxDate: new Date(2019, 12, 31),
    yearRange: [2017,2019],
    onSelect: function() {
        $scope.reset_pax();
        $scope.$digest();
        $scope.sale_form.date_selected = view_datepiker.getDate();
        //$('#datepicker').css('border-color','#78FA89');
        //$('#pax_num_container').css('border-color','#cccccc');
    },
    i18n: {
                previousMonth : 'Último mês',
                nextMonth     : 'Próximo mês',
                months        : ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
                weekdays      : ['Domingo','Segunda-Feira','Terça-Feira','Quarta-Feira','Quinta-Feira','Sexta-Feira','Sábado'],
                weekdaysShort : ['Dom','Seg','Ter','Qua','Qui','Sex','Sab']
            },
    disableDayFn: function(theDate) {
        theDate = theDate.toISOString().split('T')[0];
        if ($scope.current_service.availabilities.hasOwnProperty(theDate)) {
            return 0;
        }else {
            return 1;
        }
    }
});

When I tested the input directly in the index.html, it worked fine. But now I have created this directive to make the things simpler and when I click in the  field the datepiker does not show up.

Does anybody know how to show the Pikaday in a AngularJS directive?

Body:
Investigation: I've added this code:

console.log($('#view_service')[0]);

When the element <input id="view_service" type="text" readonly> is in the index.html the console log returns the following text: <input id="view_service" type="text" readonly>

When the same element is in a angularJS directive it returns: undefined

My Suggestion Since the page takes some time to load, the Pikaday configuration loads before the directive, so the element was not loaded on the DOM.

Solution: I put the Pikaday configuration after the code responsible to inform when the page is loaded and it worked fine.

I hope it can help people with the same issue!


问:
Remove padding in horizontal progress bar
In our application we need an indeterminate progress bar, like so:

We can achieve this by setting a negative margin on the ProgressBar, like this:

```<code><ProgressBar
    android:id="@+id/progressbar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:indeterminate="true"
    android:marginTop="-7dp"
    android:visibility="@{loading ? View.VISIBLE : View.GONE}" />
</code>```

BUT because ConstraintLayout does not support negative margins, it will look like this:

OK, the negative margin was a hack. Let's replace it with a different hack, shall we? Let's introduce our custom view CustomProgressBar, which extends ProgressBar and overrides its onDraw method, like this:

```<code>@Override
protected void onDraw(Canvas canvas) {
    int marginTop = dpToPx(7);
    canvas.translate(0, -marginTop);
    super.onDraw(canvas);
}
</code>```

But all of this smells like bad code. There has to be a better solution!
What would you recommend?

答:
Solution that feels less like a hack: Wrap a huge ProgressBar in a smaller FrameLayout. That way the FrameLayout constrains its height, but the ProgressBar still shows in full.

```<code><FrameLayout
    android:layout_width="match_parent"
    android:layout_height="4dp">

    <ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="32dp"
        android:layout_gravity="center" />

</FrameLayout>
</code>```

Body:
In our application we need an indeterminate progress bar, like so:

We can achieve this by setting a negative margin on the ProgressBar, like this:

<ProgressBar
    android:id="@+id/progressbar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:indeterminate="true"
    android:marginTop="-7dp"
    android:visibility="@{loading ? View.VISIBLE : View.GONE}" />

BUT because ConstraintLayout does not support negative margins, it will look like this:

OK, the negative margin was a hack. Let's replace it with a different hack, shall we? Let's introduce our custom view CustomProgressBar, which extends ProgressBar and overrides its onDraw method, like this:

@Override
protected void onDraw(Canvas canvas) {
    int marginTop = dpToPx(7);
    canvas.translate(0, -marginTop);
    super.onDraw(canvas);
}

But all of this smells like bad code. There has to be a better solution!
What would you recommend?

Body:
Solution that feels less like a hack: Wrap a huge ProgressBar in a smaller FrameLayout. That way the FrameLayout constrains its height, but the ProgressBar still shows in full.

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="4dp">

    <ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="32dp"
        android:layout_gravity="center" />

</FrameLayout>


问:
list indices must be integers or slices, not list from 2D array python
I get this error from python:

```<code>TypeError: list indices must be integers or slices, not list
</code>```

when using this code:

```<code>a1, a2, a3, a4, a5, a6, a7, a8, b1, b2, b3, b4, b5, b6, b7, b8 = "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "g1", "g2", "g3", "g4", "g5", "g6", "g7", "g8", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8"
bord = [[a1, a2, a3, a4, a5, a6, a7, a8], [b1, b2, b3, b4, b5, b6, b7, b8], [c1, c2, c3, c4, c5, c6, c7, c8], [d1, d2, d3, d4, d5, d6, d7, d8], [e1, e2, e3, e4, e5, e6, e7, e8], [f1, f2, f3, f4, f5, f6, f7, f8], [g1, g2, g3, g4, g5, g6, g7, g8], [h1, h2, h3, h4, h5, h6, h7, h8]]

for y in bord:
    for x in bord[y]:
        print(bord[y][x])
</code>```

so I have created an 8 by 8 board (2D list) with chess like names for positions.
I want to execute a piece of code for every individual square of the board.

the first for loop will select 1 row at a time (therefor y as y axis)
then the second for loop will select 1 column at a time (therefor x as x axis)

For a test I just printed the position of the 2D list with:

```<code>print(bord[y][x])
</code>```

答:
```<code>for y in bord:
    for x in bord[y]:
        print(bord[y][x])
</code>```

This is wrong, the correct way of doing the above is this:

```<code>for y in bord:
    for x in y:
        print(x)
</code>```

This because for x in arr iterates over the array and saves the element in variable x, if you wanted to do the style of bord[y][x], do the following:

```<code>for y in range(len(bord)):
    for x in range(len(bord[y])):
        print(bord[y][x])
</code>```

The range() function in this instance creates an array from 0..len(board) - 1, so let's say bord is 5 elements in size, we would be doing range(5). That is the same as doing for x in [0, 1, 2, 3, 4]. So it iterates over that array and saves the current element in the variable x.

So just to conclude.

You can do either:

```<code>for y in bord:
    for x in y:
        print(x)
</code>```

or

```<code>for y in range(len(bord)):
    for x in range(len(bord[y])):
        print(bord[y][x])
</code>```

You can use either, whichever you prefer. There is probably a reason for using one or the other but I am unaware of it, if someone wants to edit this to provide that reason please do.

Hope this helps!

Body:
I get this error from python:

TypeError: list indices must be integers or slices, not list

when using this code:

a1, a2, a3, a4, a5, a6, a7, a8, b1, b2, b3, b4, b5, b6, b7, b8 = "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "g1", "g2", "g3", "g4", "g5", "g6", "g7", "g8", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8"
bord = [[a1, a2, a3, a4, a5, a6, a7, a8], [b1, b2, b3, b4, b5, b6, b7, b8], [c1, c2, c3, c4, c5, c6, c7, c8], [d1, d2, d3, d4, d5, d6, d7, d8], [e1, e2, e3, e4, e5, e6, e7, e8], [f1, f2, f3, f4, f5, f6, f7, f8], [g1, g2, g3, g4, g5, g6, g7, g8], [h1, h2, h3, h4, h5, h6, h7, h8]]

for y in bord:
    for x in bord[y]:
        print(bord[y][x])

so I have created an 8 by 8 board (2D list) with chess like names for positions.
I want to execute a piece of code for every individual square of the board.

the first for loop will select 1 row at a time (therefor y as y axis)
then the second for loop will select 1 column at a time (therefor x as x axis)

For a test I just printed the position of the 2D list with:

print(bord[y][x])

Body:
for y in bord:
    for x in bord[y]:
        print(bord[y][x])

This is wrong, the correct way of doing the above is this:

for y in bord:
    for x in y:
        print(x)

This because for x in arr iterates over the array and saves the element in variable x, if you wanted to do the style of bord[y][x], do the following:

for y in range(len(bord)):
    for x in range(len(bord[y])):
        print(bord[y][x])

The range() function in this instance creates an array from 0..len(board) - 1, so let's say bord is 5 elements in size, we would be doing range(5). That is the same as doing for x in [0, 1, 2, 3, 4]. So it iterates over that array and saves the current element in the variable x.

So just to conclude.

You can do either:

for y in bord:
    for x in y:
        print(x)

or

for y in range(len(bord)):
    for x in range(len(bord[y])):
        print(bord[y][x])

You can use either, whichever you prefer. There is probably a reason for using one or the other but I am unaware of it, if someone wants to edit this to provide that reason please do.

Hope this helps!


问:
Can a html5 app download HTML files and store them locally?
Is it possible to download html files and images from a server and store them in the same disk location as the html file doing the downloading?

I need to do this because I have an app that is a database of HTML files and these files change from time to time. When updates occur, it would be good if the HTML5 app prompted the user to do an update and if accepted, the file were downloaded and replaced the old file set.

The app has to work offline, hence the need to download the data.

答: In most browsers, yes. Read about the cache manifest http://diveintohtml5.ep.io/offline.html</p>


问:
how to save rdd to different S3 buckets simultaniously
I want to know how to save the computed rdd to different locations.
Also extend the same for notifying without computation.

```<code>rdd = <do some action>
</code>```

as I know rdd.saveAstextFile("s3://<location1>") will store to location1,
but if I want to store to location2 also how to do it?
I am not sure whether persist/cache ( my understanding is it will cache/persist in master node) will work as rdd size is very big.

Please help.

答:
my understanding is it will cache/persist in master node.

Where did you find this? This is not correct. As per the spark documentation below is the explanation.

One of the most important capabilities in Spark is persisting (or caching) a dataset in memory across operations. When you persist an RDD, each node stores any partitions of it that it computes in memory and reuses them in other actions on that dataset (or datasets derived from it). This allows future actions to be much faster (often by more than 10x). Caching is a key tool for iterative algorithms and fast interactive use.

Also,

The cache() method is a shorthand for using the default storage level, which is StorageLevel.MEMORY_ONLY

i.e cache() is similar to persist(StorageLevel.MEMORY_ONLY).
Follow this link to decide which storage level to use as per your requirement.
https://spark.apache.org/docs/2.1.0/programming-guide.html#which-storage-level-to-choose

You can use below for saving at two location:

```<code>rdd.cache()
rdd.saveAstextFile("s3://<location1>")
rdd.saveAstextFile("s3://<location2>")
</code>```

More details are here : https://spark.apache.org/docs/2.1.0/programming-guide.html#rdd-persistence

Body:
I want to know how to save the computed rdd to different locations.
Also extend the same for notifying without computation.

rdd = <do some action>

as I know rdd.saveAstextFile("s3://<location1>") will store to location1,
but if I want to store to location2 also how to do it?
I am not sure whether persist/cache ( my understanding is it will cache/persist in master node) will work as rdd size is very big.

Please help.

Body:
my understanding is it will cache/persist in master node.

Where did you find this? This is not correct. As per the spark documentation below is the explanation.

One of the most important capabilities in Spark is persisting (or caching) a dataset in memory across operations. When you persist an RDD, each node stores any partitions of it that it computes in memory and reuses them in other actions on that dataset (or datasets derived from it). This allows future actions to be much faster (often by more than 10x). Caching is a key tool for iterative algorithms and fast interactive use.

Also,

The cache() method is a shorthand for using the default storage level, which is StorageLevel.MEMORY_ONLY

i.e cache() is similar to persist(StorageLevel.MEMORY_ONLY).
Follow this link to decide which storage level to use as per your requirement.
https://spark.apache.org/docs/2.1.0/programming-guide.html#which-storage-level-to-choose

You can use below for saving at two location:

rdd.cache()
rdd.saveAstextFile("s3://<location1>")
rdd.saveAstextFile("s3://<location2>")

More details are here : https://spark.apache.org/docs/2.1.0/programming-guide.html#rdd-persistence


问:
How do I access netsuite data using SQL language
A company uses netsuites to make purchase orders and store sales information. The only way this company is able to access this information at the moment is through building netsuites reports

Is there a way SQL language could be written to access the netsuites data as some of the questions asked by the business need something a bit more complex than what netsuites reporting provides - and sound very easy using SQL language

I have experience in Oracle, mysql, and many other SQL languages so I would like to know how to set up a connection to the companies netsuites data so I can help write custom queries

答:
You can access Netsuite backend using a number of different tools and it allows running Oracle SQL directly.

Netsuite provides JDBC, ADO.NET and ODBC if it was included in your licensing purchase.  You can find the downloads from the main menu - lower left hand of the screen in Settings - Set Up SuiteAnalytics Connect.

ADO.net however is pretty worthless in SSIS as it doesn't allow parameter mapping or SQL from a variable value. I have yet to get the ODBC driver to work correctly - it can connect and show columns of a table but it won't validate saying "The ODBC Source.Outputs[ODBC Source Error Output].Columns[...] on the error output has properties that do not match the properties of its corresponding data source column."

The other options I'm looking into are Cozyroc and Kinsgwaysoft adapters for Netsuite. You could also do SOAP or REST connections if desired.


问:
Why in firestore will a if let statement change the type of a document variable?
I was just hoping for an explanation re: what is happening below.
In the first if let statement where document = document flatmap no longer is a member of DocumentSnapshot whereas in the second if let i'm obviously able to call flatmap on the document in the if let statement. I just don't quite get why that is.

I checked the type and they are both DocumentSnapshots the only difference is one is an optional.

Thx.

```<code> var docref:DocumentReference?
 docref = db.collection("users").document(uid)
 docref?.getDocument { (document, error) in

      if let document = document{

       //document.flatmap won't work
       //value of DocumentSnapshot has no member flatmap

      }

      if let profile = document.flatMap({$0.data()})
      {

         self.model.currentLoggedInUser?.id = profile["id"] as! String

      }
</code>```

答:
if let document = document unwraps the previous document, and binds it to a new constant document, that shadows the previous document within the { ... }.

If document had type T? before, the new, shadowing document has type T.

It's similar to regular variable shadowing:

```<code>let a = 1

if true {
    let a = 2 //shadows the outer `a`
    print(a) // => 2
}
</code>```

In all, this code behaves similar to this:

```<code>let document: Document? = MaybeReturnADocument()

if document != nil { // Illustrative only, don't do this!
    let document: Document = document! // shadows the outer document of type `Document?`
    ...
}
</code>```

Body:
I was just hoping for an explanation re: what is happening below.
In the first if let statement where document = document flatmap no longer is a member of DocumentSnapshot whereas in the second if let i'm obviously able to call flatmap on the document in the if let statement. I just don't quite get why that is.

I checked the type and they are both DocumentSnapshots the only difference is one is an optional.

Thx.

 var docref:DocumentReference?
 docref = db.collection("users").document(uid)
 docref?.getDocument { (document, error) in

      if let document = document{

       //document.flatmap won't work
       //value of DocumentSnapshot has no member flatmap

      }

      if let profile = document.flatMap({$0.data()})
      {

         self.model.currentLoggedInUser?.id = profile["id"] as! String

      }

Body:
if let document = document unwraps the previous document, and binds it to a new constant document, that shadows the previous document within the { ... }.

If document had type T? before, the new, shadowing document has type T.

It's similar to regular variable shadowing:

let a = 1

if true {
    let a = 2 //shadows the outer `a`
    print(a) // => 2
}

In all, this code behaves similar to this:

let document: Document? = MaybeReturnADocument()

if document != nil { // Illustrative only, don't do this!
    let document: Document = document! // shadows the outer document of type `Document?`
    ...
}


问:
Converting c++ to c#
1) My program runs fine in c++, im just trying to convert it to c#, Need help converting the ifstream part
c++ code:

```<code>ifstream data;
data.open("data.txt");
if (data.fail()) {
    cout << "Error opening file\n";
    exit(1);
}
</code>```

So far this is what i got from research is to use filestream and streamreader
c# code: Just want to make sure its equivalent.

```<code>        if(!File.Exists(data))
        {
            Console.Write("{0} does not exist.", data);
            return 0;
        }
        FileStream fsIn = new FileStream(data, FileMode.Open,
         FileAccess.Read, FileShare.Read);
        using (StreamReader sr = new StreamReader(fsIn))
</code>```

2) Next part where im stuck on, is on the function where its suppose to get the data from the .txt file and store into an array (the data.txt file is added from solution of the project so no url to the file was required)(using visual studio)
c++ code:

void read_file(ifstream& fsIn, float h_temp[], int array_size, int& valid_entries_high, int& valid_entries_low, float l_temp[])
{

```<code>while (!data.eof()) // eof = end of file
{
    data >> h_temp[valid_entries_high];
    valid_entries_high++;

    data >> l_temp[valid_entries_low];
    valid_entries_low++;

    if (valid_entries_high + valid_entries_low == array_size) {
        cout << "Array's full,\n";
        break;
    }
}
    if (valid_entries_high == valid_entries_low)
    {
        cout << "file is valid" << endl;
    }
    else
    {
        exit(1);
    }
    //check make sure theyre the same length
</code>```

}

This is where im stuck on with my c#:
 public static void read_file(FileStream fsIn, float[] h_temp, int array_size, ref int valid_entries_high, ref int valid_entries_low, float[] l_temp)
        {

```<code>        while (!fsIn.EndofStream()) // eof = end of file
        {
            fsIn >> h_temp[valid_entries_high];
            valid_entries_high++;

            fsIn >> l_temp[valid_entries_low];
            valid_entries_low++;

            if (valid_entries_high + valid_entries_low == array_size)
            {
                Console.WriteLine("Array's full,\n");
                break;
            }
        }
        if (valid_entries_high == valid_entries_low)
        {
            Console.WriteLine("file is valid");
        }
        else
        {
            Environment.Exit(1);
        }

    }
</code>```

converting that input << sign into c# and also why .EndofStream wont work? Im using sysmtem.io like the tutorial said but it says Filestream does not contain a definition for 'endofstream'. Also is ifstream& the same as FileStream ref?
Any advice will be greatly apperciated!

答:
We have no idea what your file format looks like but I'll make an assumption that you want to read each line into an array element...

```<code>using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] lines = File.ReadAllLines(@"c:\Developer\TestFile.txt");
            foreach (var line in lines)
            {
                Console.WriteLine(line);
            }
            Console.ReadLine();
        }
    }
}
</code>```

If you have a specific format then you'd need to provide us with more detail, Bu I can recommend the FileHelpers library from GitHub as an ideal way to import delimited data if that's what you're looking for.

And yeah, like Neil Butterworth said coding in a new language exactly as you would in C++ isn't the way forward. .NET is a framework that does the majority of heavy lifting for you and in a very intuitive way. Don't try to re-write rudimentary code.  I wouldn't even be doing that in C++, I'd be using Boost or Qt and only go down to the low level for rare scenarios.
Incidentally, before you start trying to write your own code to sort and query data structures in memory, learn about LINQ and spend the time you save doing more important things.

Title: Converting c++ to c#

Body:
1) My program runs fine in c++, im just trying to convert it to c#, Need help converting the ifstream part
c++ code:

ifstream data;
data.open("data.txt");
if (data.fail()) {
    cout << "Error opening file\n";
    exit(1);
}

So far this is what i got from research is to use filestream and streamreader
c# code: Just want to make sure its equivalent.

        if(!File.Exists(data))
        {
            Console.Write("{0} does not exist.", data);
            return 0;
        }
        FileStream fsIn = new FileStream(data, FileMode.Open,
         FileAccess.Read, FileShare.Read);
        using (StreamReader sr = new StreamReader(fsIn))

2) Next part where im stuck on, is on the function where its suppose to get the data from the .txt file and store into an array (the data.txt file is added from solution of the project so no url to the file was required)(using visual studio)
c++ code:

void read_file(ifstream& fsIn, float h_temp[], int array_size, int& valid_entries_high, int& valid_entries_low, float l_temp[])
{

while (!data.eof()) // eof = end of file
{
    data >> h_temp[valid_entries_high];
    valid_entries_high++;

    data >> l_temp[valid_entries_low];
    valid_entries_low++;

    if (valid_entries_high + valid_entries_low == array_size) {
        cout << "Array's full,\n";
        break;
    }
}
    if (valid_entries_high == valid_entries_low)
    {
        cout << "file is valid" << endl;
    }
    else
    {
        exit(1);
    }
    //check make sure theyre the same length

}

This is where im stuck on with my c#:
 public static void read_file(FileStream fsIn, float[] h_temp, int array_size, ref int valid_entries_high, ref int valid_entries_low, float[] l_temp)
        {

        while (!fsIn.EndofStream()) // eof = end of file
        {
            fsIn >> h_temp[valid_entries_high];
            valid_entries_high++;

            fsIn >> l_temp[valid_entries_low];
            valid_entries_low++;

            if (valid_entries_high + valid_entries_low == array_size)
            {
                Console.WriteLine("Array's full,\n");
                break;
            }
        }
        if (valid_entries_high == valid_entries_low)
        {
            Console.WriteLine("file is valid");
        }
        else
        {
            Environment.Exit(1);
        }

    }

converting that input << sign into c# and also why .EndofStream wont work? Im using sysmtem.io like the tutorial said but it says Filestream does not contain a definition for 'endofstream'. Also is ifstream& the same as FileStream ref?
Any advice will be greatly apperciated!

Body:
We have no idea what your file format looks like but I'll make an assumption that you want to read each line into an array element...

using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] lines = File.ReadAllLines(@"c:\Developer\TestFile.txt");
            foreach (var line in lines)
            {
                Console.WriteLine(line);
            }
            Console.ReadLine();
        }
    }
}

If you have a specific format then you'd need to provide us with more detail, Bu I can recommend the FileHelpers library from GitHub as an ideal way to import delimited data if that's what you're looking for.

And yeah, like Neil Butterworth said coding in a new language exactly as you would in C++ isn't the way forward. .NET is a framework that does the majority of heavy lifting for you and in a very intuitive way. Don't try to re-write rudimentary code.  I wouldn't even be doing that in C++, I'd be using Boost or Qt and only go down to the low level for rare scenarios.
Incidentally, before you start trying to write your own code to sort and query data structures in memory, learn about LINQ and spend the time you save doing more important things.


问:
How to do regression as opposed to classification using logistic regression and scikit learn
The target variable that I need to predict are probabilities (as opposed to labels). The corresponding column in my training data are also in this form. I do not want to lose information by thresholding the targets to create a classification problem out of it.

If I train the logistic regression classifier with binary labels, sk-learn logistic regression API allows obtaining the probabilities at prediction time. However, I need to train it with probabilities. Is there a way to do this in scikits-learn, or a suitable Python package that scales to 100K data points of 1K dimension.

答:
I want the regressor to use the structure of the problem. One such
  structure is that the targets are probabilities.

You can't have cross-entropy loss with non-indicator probabilities in scikit-learn; this is not implemented and not supported in API. It is a scikit-learn's limitation.

In general, according to scikit-learn's docs a loss function is of the form Loss(prediction, target), where prediction is the model's output, and target is the ground-truth value.

In the case of logistic regression, prediction is a value on (0,1) (i.e., a "soft label"), while target is 0 or 1 (i.e., a "hard label").

For logistic regression you can approximate probabilities as target by oversampling instances according to probabilities of their labels. e.g. if for given sample class_1 has probability 0.2, and class_2 has probability0.8, then generate 10 training instances (copied sample): 8 withclass_2as "ground truth target label" and 2 withclass_1`.

Obviously it is workaround and is not extremely efficient, but it should work properly.

If you're ok with upsampling approach, you can pip install eli5, and use eli5.lime.utils.fit_proba with a Logistic Regression classifier from scikit-learn.

Alternative solution is to implement (or find implementation?) of LogisticRegression in Tensorflow, where you can define loss function as you like it.

In compiling this solution I worked using answers from scikit-learn - multinomial logistic regression with probabilities as a target variable and scikit-learn classification on soft labels. I advise those for more insight.


问:
Is anyone using meta-meta-classes / meta-meta-meta-classes in Python/ other languages?
I recently discovered metaclasses in python.

Basically a metaclass in python is a class that creates a class. There are many useful reasons why you would want to do this - any kind of class initialisation for example. Registering classes on factories, complex validation of attributes, altering how inheritance works, etc. All of this becomes not only possible but simple.

But in python, metaclasses are also plain classes. So, I started wondering if the abstraction could usefully go higher, and it seems to me that it can and that:

a metaclass corresponds to or implements a role in a pattern (as in GOF pattern languages).

a meta-metaclass is the pattern itself (if we allow it to create tuples of classes representing abstract roles, rather than just a single class)

a meta-meta-metaclass is a pattern factory, which corresponds to the GOF pattern groupings, e.g. Creational,  Structural, Behavioural. A factory where you could describe a case of a certain type of problem and it would give you a set of classes that solved it.

a meta-meta-meta-metaclass (as far as I could go), is a pattern factory factory, a factory to which you could perhaps describe the type of your problem and it would give you a pattern factory to ask.

I have found some stuff about this online, but mostly not very useful. One problem is that different languages define metaclasses slightly differently.

Has anyone else used metaclasses like this in python/elsewhere, or seen this used in the wild, or thought about it? What are the analogues in other languages? E.g. in C++ how deep can the template recursion go?

I'd very much like to research it further.

答:
This reminds me of the eternal quest some people seem to be on to make a "generic implementation of a pattern."  Like a factory that can create any object (including another factory), or a general-purpose dependency injection framework that is far more complex to manage than simply writing code that actually does something.

I had to deal with people intent on abstraction to the point of navel-gazing when I was managing the Zend Framework project.  I turned down a bunch of proposals to create components that didn't do anything, they were just magical implementations of GoF patterns, as though the pattern were a goal in itself, instead of a means to a goal.

There's a point of diminishing returns for abstraction.  Some abstraction is great, but eventually you need to write code that does something useful.

Otherwise it's just turtles all the way down.

OwnerDisplayName: Bill Karwin