问:
How should I handle thread updates to an internal Dictionary, possibly after thread.delegate exits?
I have N threads that are each saving data to a private Dictionary<string,myObject> myUploadObject variable with instance-object scope.

Once there is sufficient data in that dictionary, or after 2 minutes pass, I'll upload that collection to the server.

I've never encountered this multi-threaded situation and not sure how to approach this. Here is how I'm launching my initial code:

```<code>        PerfmonClient agent = new PerfmonClient(Machine, Start, Stop, Interval, MaxIterations);
        Thread newThread = null;
        Console.WriteLine("Creating new thread: " + agent.ToThreadName());
        ThreadStart threadDelegate = new ThreadStart(agent.TestLoop);
        newThread = new Thread(threadDelegate);
        agent.AssociatedThread = newThread;
        AgentDictionary.Add(agent.ToThreadName(), agent);
        newThread.Start();
</code>```

Now I'm trying to get data out of within the agent object and send it to the server.  I would normally just call another method within the instance of PerfmonClient to do so, but the threading concept is making me double check my approach.

Here are some ways I'm considering taking that collected data and sending it to the server:

Create a new ThreadDelegate for the agent.upload method, load it and run it (Main thread, or spawned thread)

Change the internal object Dictionary<string,myObject> myUploadObject to public and static, and use a threadDelegate/Main thread to do the upload.

?? Not sure what happens if the initial agent.TestLoop exits, or errors out?  Do I loose all the data within the agent object?  How do I access internal data it when thread.IsActive == false?

Thank you for answering these questions... or pointing me in the right direction.  I'm not sure if I'm re-inventing the wheel here and may need to learn something new.

答:
I would have a central uploader thread that provides a method AddPerformanceData to add performance data that the collection threads can call. This method uses a lock and stores the data internally. The uploader thread then sends that data in order using the lock for access as well.

This has the advantage that you don't need any locks on the collection threads since no-one else is accessing their data - you basically serialize the upload through the uploader thread.

Body:
I have N threads that are each saving data to a private Dictionary<string,myObject> myUploadObject variable with instance-object scope.

Once there is sufficient data in that dictionary, or after 2 minutes pass, I'll upload that collection to the server.

I've never encountered this multi-threaded situation and not sure how to approach this. Here is how I'm launching my initial code:

        PerfmonClient agent = new PerfmonClient(Machine, Start, Stop, Interval, MaxIterations);
        Thread newThread = null;
        Console.WriteLine("Creating new thread: " + agent.ToThreadName());
        ThreadStart threadDelegate = new ThreadStart(agent.TestLoop);
        newThread = new Thread(threadDelegate);
        agent.AssociatedThread = newThread;
        AgentDictionary.Add(agent.ToThreadName(), agent);
        newThread.Start();

Now I'm trying to get data out of within the agent object and send it to the server.  I would normally just call another method within the instance of PerfmonClient to do so, but the threading concept is making me double check my approach.

Here are some ways I'm considering taking that collected data and sending it to the server:

Create a new ThreadDelegate for the agent.upload method, load it and run it (Main thread, or spawned thread)

Change the internal object Dictionary<string,myObject> myUploadObject to public and static, and use a threadDelegate/Main thread to do the upload.

?? Not sure what happens if the initial agent.TestLoop exits, or errors out?  Do I loose all the data within the agent object?  How do I access internal data it when thread.IsActive == false?

Thank you for answering these questions... or pointing me in the right direction.  I'm not sure if I'm re-inventing the wheel here and may need to learn something new.


来源: stackexchange

问:
OSGI Bundle bean delcaration issue
I'm new to OSGI blueprint definition, I'm trying to accomplish the following :

Bundle 1 : Contains Bean1 (Which has a Bean2 injection) all declared in blueprint1

Bundle 2 : In it's blueprint2, I would like to use Bean1 (without declaring Bean2)

Result :
Bundle 2 is failing on : missing dependency to Bean2, this makes sense because Bundle 2 doesn't add Bean2, but I don't want to make it visible in this bundle, It has some complex configs included in Blueprint1 (And I don't want to recopy the whole thing in Blueprint2)
I was hoping to create it in Bundle1 and use it in Bundle2

Question :
Is there any way to get this kind of access from Bundle 2 (bean1 is supposed to be like a service used by other bundles) ? If no, is there a different way to do ?

Thank you for your help.

As requested, below my blueprints :

Blueprints 1 :

`

```<code><?xml version="1.0"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" ... >
   <bean id="bean1" class="Bean1" />
   <bean id="bean2" class="Bean2" />
</blueprint>
</code>```

`

Blueprints 2 :

`

```<code><?xml version="1.0"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" ... >
   <bean id="bean1" class="Bean1" />
</blueprint>
</code>```

`

Bean 1 :

```<code>public class Bean1 {

  @BeanInject("bean2")
  Bean2 bean2;

  ....

}
</code>```

Blueprint 2 is failing

答:
Below my solution :

Bean declaration in the blueprint will always take the local bundle context, this one should identify all the dependencies used in this bean, so there is no way to call bean1 in blueprint2 without declaring Bean2 as well.

The solution is to use a service, declare bean1 as a service in Blueprint1 and use it as a reference in Blueprint2, no need to define any dependency then.

Detailed solution described here : Service OSGI

ContentLicense: CC BY-SA 3.0

Title: OSGI Bundle bean delcaration issue

Body:
I'm new to OSGI blueprint definition, I'm trying to accomplish the following :

Bundle 1 : Contains Bean1 (Which has a Bean2 injection) all declared in blueprint1

Bundle 2 : In it's blueprint2, I would like to use Bean1 (without declaring Bean2)

Result :
Bundle 2 is failing on : missing dependency to Bean2, this makes sense because Bundle 2 doesn't add Bean2, but I don't want to make it visible in this bundle, It has some complex configs included in Blueprint1 (And I don't want to recopy the whole thing in Blueprint2)
I was hoping to create it in Bundle1 and use it in Bundle2

Question :
Is there any way to get this kind of access from Bundle 2 (bean1 is supposed to be like a service used by other bundles) ? If no, is there a different way to do ?

Thank you for your help.

As requested, below my blueprints :

Blueprints 1 :

`

<?xml version="1.0"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" ... >
   <bean id="bean1" class="Bean1" />
   <bean id="bean2" class="Bean2" />
</blueprint>

`

Blueprints 2 :

`

<?xml version="1.0"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" ... >
   <bean id="bean1" class="Bean1" />
</blueprint>

`

Bean 1 :

public class Bean1 {

  @BeanInject("bean2")
  Bean2 bean2;

  ....

}

Blueprint 2 is failing


问:
Can't drag and drop item from storyboard to viewcontroller in xcode
I started working with xcode a few days ago, and today I tried to connect a textview from the main storyboard to the viewcontroller, but I figured out that its not working.

I am able to ctrl+click to drag the item, but unable to place it in both viewcontroller.h and .m. I double checked that its viewcontroller and not UIViewcontroller, so this is not the case.

I'm using a Yosemite 10.10 mac.

Any kind of help would be appreciated.

答:
Note that dragging to any point in your code doesn't necessarily work.  If you've been unable to drag to create the connection in one spot of your code, try dragging to another spot.  For me, I was trying to drag to add a connection in the middle of a function which didn't work.  Dragging to the beginning line of a function or in between functions did work.

Note: I'm on Xcode 9.1


问:
O(N) Time complexity for simple Python function
I just took a Codility demo test. The question and my answer can be seen here, but I'll paste my answer here as well. My response:

```<code>def solution(A):
    # write your code in Python 2.7

    retresult = 1; # the smallest integer we can return, if it is not in the array

    A.sort()
    for i in A:
        if i > 0:
            if i==retresult:   retresult += 1 # increment the result since the current result exists in the array
            elif i>retresult:   break # we can go out of the loop since we found a bigger number than our current positive integer result

    return retresult
</code>```

My question is around time complexity, which I hope to better understand by your response. The question asks for expected worst-case time complexity is O(N).

Does my function have O(N) time complexity? Does the fact that I sort the array increase the complexity, and if so how?

Codility reports (for my answer)

```<code>Detected time complexity:
O(N) or O(N * log(N))
</code>```

So, what is the complexity for my function? And if it is O(N*log(N)), what can I do to decrease the complexity to O(N) as the problem states?

Thanks very much!

p.s. my background reading on time complexity comes from this great post.

EDIT

Following the reply below, and the answers described here for this problem, I would like to expand on this with my take on the solutions:

basicSolution has an expensive time complexity and so is not the right answer for this Codility test:

```<code>def basicSolution(A):
    # 0(N*log(N) time complexity

    retresult = 1; # the smallest integer we can return, if it is not in the array

    A.sort()
    for i in A:
        if i > 0:
            if i==retresult:   retresult += 1 #increment the result since the current result exists in the array
            elif i>retresult:   break # we can go out of the loop since we found a bigger number than our current positive integer result
        else:
            continue; # negative numbers and 0 don't need any work

    return retresult
</code>```

hashSolution is my take on what is described in the above article, in the "use hashing" paragraph. As I am new to Python, please let me know if you have any improvements to this code (it does work though against my test cases), and what time complexity this has?

```<code>def hashSolution(A):
    # 0(N) time complexity, I think? but requires 0(N) extra space (requirement states to use 0(N) space

    table = {}

    for i in A:
        if i > 0:
            table[i] = True # collision/duplicate will just overwrite

    for i in range(1,100000+1): # the problem says that the array has a maximum of 100,000 integers
        if not(table.get(i)): return i

    return 1 # default
</code>```

Finally, the actual 0(N) solution (O(n) time and O(1) extra space solution) I am having trouble understanding. I understand that negative/0 values are pushed at the back of the array, and then we have an array of just positive values. But I do not understand the findMissingPositive function - could anyone please describe this with Python code/comments? With an example perhaps? I've been trying to work through it in Python and just cannot figure it out :(

答:
It does not, because you sort A.

The Python list.sort() function uses Timsort (named after Tim Peters), and has a worst-case time complexity of O(NlogN).

Rather than sort your input, you'll have to iterate over it and determine if any integers are missing by some other means. I'd use a set of a range() object:

```<code>def solution(A):
    expected = set(range(1, len(A) + 1))
    for i in A:
        expected.discard(i)
    if not expected:
        # all consecutive digits for len(A) were present, so next is missing
        return len(A) + 1
    return min(expected)
</code>```

This is O(N); we create a set of len(A) (O(N) time), then we loop over A, removing elements from expected (again O(N) time, removing elements from a set is O(1)), then test for expected being empty (O(1) time), and finally get the smallest element in expected (at most O(N) time).

So we make at most 3 O(N) time steps in the above function, making it a O(N) solution.

This also fits the storage requirement; all use is a set of size N. Sets have a small overhead, but always smaller than N.

The hash solution you found is based on the same principle, except that it uses a dictionary instead of a set. Note that the dictionary values are never actually used, they are either set to True or absent. I'd rewrite that as:

```<code>def hashSolution(A):
    seen = {i for i in A if i > 0}
    if not seen:
        # there were no positive values, so 1 is the first missing.
        return 1
    for i in range(1, 10**5 + 1):
        if i not in seen:
            return i
    # we can never get here because the inputs are limited to integers up to
    # 10k. So either `seen` has a limited number of positive values below
    # 10.000 or none at all.
</code>```

The above avoids looping all the way to 10.000 if there were no positive integers in A.

The difference between mine and theirs is that mine starts with the set of expected numbers, while they start with the set of positive values from A, inverting the storage and test.

Body:
I just took a Codility demo test. The question and my answer can be seen here, but I'll paste my answer here as well. My response:

def solution(A):
    # write your code in Python 2.7

    retresult = 1; # the smallest integer we can return, if it is not in the array

    A.sort()
    for i in A:
        if i > 0:
            if i==retresult:   retresult += 1 # increment the result since the current result exists in the array
            elif i>retresult:   break # we can go out of the loop since we found a bigger number than our current positive integer result

    return retresult

My question is around time complexity, which I hope to better understand by your response. The question asks for expected worst-case time complexity is O(N).

Does my function have O(N) time complexity? Does the fact that I sort the array increase the complexity, and if so how?

Codility reports (for my answer)

Detected time complexity:
O(N) or O(N * log(N))

So, what is the complexity for my function? And if it is O(N*log(N)), what can I do to decrease the complexity to O(N) as the problem states?

Thanks very much!

p.s. my background reading on time complexity comes from this great post.

EDIT

Following the reply below, and the answers described here for this problem, I would like to expand on this with my take on the solutions:

basicSolution has an expensive time complexity and so is not the right answer for this Codility test:

def basicSolution(A):
    # 0(N*log(N) time complexity

    retresult = 1; # the smallest integer we can return, if it is not in the array

    A.sort()
    for i in A:
        if i > 0:
            if i==retresult:   retresult += 1 #increment the result since the current result exists in the array
            elif i>retresult:   break # we can go out of the loop since we found a bigger number than our current positive integer result
        else:
            continue; # negative numbers and 0 don't need any work

    return retresult

hashSolution is my take on what is described in the above article, in the "use hashing" paragraph. As I am new to Python, please let me know if you have any improvements to this code (it does work though against my test cases), and what time complexity this has?

def hashSolution(A):
    # 0(N) time complexity, I think? but requires 0(N) extra space (requirement states to use 0(N) space

    table = {}

    for i in A:
        if i > 0:
            table[i] = True # collision/duplicate will just overwrite

    for i in range(1,100000+1): # the problem says that the array has a maximum of 100,000 integers
        if not(table.get(i)): return i

    return 1 # default

Finally, the actual 0(N) solution (O(n) time and O(1) extra space solution) I am having trouble understanding. I understand that negative/0 values are pushed at the back of the array, and then we have an array of just positive values. But I do not understand the findMissingPositive function - could anyone please describe this with Python code/comments? With an example perhaps? I've been trying to work through it in Python and just cannot figure it out :(

Body:
It does not, because you sort A.

The Python list.sort() function uses Timsort (named after Tim Peters), and has a worst-case time complexity of O(NlogN).

Rather than sort your input, you'll have to iterate over it and determine if any integers are missing by some other means. I'd use a set of a range() object:

def solution(A):
    expected = set(range(1, len(A) + 1))
    for i in A:
        expected.discard(i)
    if not expected:
        # all consecutive digits for len(A) were present, so next is missing
        return len(A) + 1
    return min(expected)

This is O(N); we create a set of len(A) (O(N) time), then we loop over A, removing elements from expected (again O(N) time, removing elements from a set is O(1)), then test for expected being empty (O(1) time), and finally get the smallest element in expected (at most O(N) time).

So we make at most 3 O(N) time steps in the above function, making it a O(N) solution.

This also fits the storage requirement; all use is a set of size N. Sets have a small overhead, but always smaller than N.

The hash solution you found is based on the same principle, except that it uses a dictionary instead of a set. Note that the dictionary values are never actually used, they are either set to True or absent. I'd rewrite that as:

def hashSolution(A):
    seen = {i for i in A if i > 0}
    if not seen:
        # there were no positive values, so 1 is the first missing.
        return 1
    for i in range(1, 10**5 + 1):
        if i not in seen:
            return i
    # we can never get here because the inputs are limited to integers up to
    # 10k. So either `seen` has a limited number of positive values below
    # 10.000 or none at all.

The above avoids looping all the way to 10.000 if there were no positive integers in A.

The difference between mine and theirs is that mine starts with the set of expected numbers, while they start with the set of positive values from A, inverting the storage and test.


问:
Get dataset value from input tag upon click and display as HTML
I would like to get the value from the data-price dataset in the radio button after the user has clicked a different option and display it below in the label tag.  I am doing something wrong.  Any help would be very much appreciated.

Here is my code:

(function (){
    var radios_price = document.getElementById('lbl-011');
    console.log(radios_price.dataset.price);
    for(var i = 0; i < radios_price.length; i++){
        radios_price[i].onclick = function(){
            document.getElementById('priceLabel').innerText = this.value;
        }
    }
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="lbl-011" class="click_radio checkbox123" data-name="One Gel Pen with One Blue Light" name="product_quantity" data-val="2264" data-price="29" data-qty="1" value="1" type="radio">

<input id="lbl-011" class="click_radio" data-name="Two Gel Pens and One Blue Light" name="product_quantity" data-val="2263" data-price="39" data-qty="2" value="2" type="radio" checked="checked">

<input id="lbl-011" class="click_radio" data-name="Four Gel Pens and One Blue Light with Bonus Mouth Tray" name="product_quantity" data-val="2259" data-qty="4" data-price="49" value="4" type="radio">

<p>Price (data-price):<label id="priceLabel"> $39</label></code>```

答:
This should give you the desired output. Like others said, the ID has to be unique. Only the class can be the same.</p>

```<code>(function() {
  let radios = document.querySelectorAll('.click_radio');

  radios.forEach((radio) => {
    radio.addEventListener('change', () => {

      // This gives you access to all the data attributes you've declared
      //
      let radioData = radio.dataset;

      document.getElementById('priceLabel').innerText = `$${ radioData.price }`
    })
  })
})()
</code>```

Body:
I would like to get the value from the data-price dataset in the radio button after the user has clicked a different option and display it below in the label tag.  I am doing something wrong.  Any help would be very much appreciated.

Here is my code:

(function (){
    var radios_price = document.getElementById('lbl-011');
    console.log(radios_price.dataset.price);
    for(var i = 0; i < radios_price.length; i++){
        radios_price[i].onclick = function(){
            document.getElementById('priceLabel').innerText = this.value;
        }
    }
})();

<input id="lbl-011" class="click_radio checkbox123" data-name="One Gel Pen with One Blue Light" name="product_quantity" data-val="2264" data-price="29" data-qty="1" value="1" type="radio">

<input id="lbl-011" class="click_radio" data-name="Two Gel Pens and One Blue Light" name="product_quantity" data-val="2263" data-price="39" data-qty="2" value="2" type="radio" checked="checked">

<input id="lbl-011" class="click_radio" data-name="Four Gel Pens and One Blue Light with Bonus Mouth Tray" name="product_quantity" data-val="2259" data-qty="4" data-price="49" value="4" type="radio">

Price (data-price): $39

Body:
This should give you the desired output. Like others said, the ID has to be unique. Only the class can be the same.

(function() {
  let radios = document.querySelectorAll('.click_radio');

  radios.forEach((radio) => {
    radio.addEventListener('change', () => {

      // This gives you access to all the data attributes you've declared
      //
      let radioData = radio.dataset;

      document.getElementById('priceLabel').innerText = `$${ radioData.price }`
    })
  })
})()


问:
Reactjs: Disable button to avoid double submission, then enable button once request is complete (response received)
I'm creating a reactjs form that submits a form (with field data and a file).

When the Submit button is clicked, its triggers the onClick event that invokes some handleFormSubmission method.

This handleFormSubmission method first disables the button, then creates an XMLHttpRequest that sends the form data away. It might take some moment to the response to come back, and until then the button remains disable.

But once the response is theree, be it successful (code 200) or fail (code 500), I want the Submit button to be re-enabled so user can do another submission.

For the disabling, I simply set the state isFormSubmitted to true, and bind it to the button's disabled property. How could I then re-enable it?

```<code>handleFormSubmission() {
    this.setState({
      isFormSubmitted: true
    });

    // stuff...
    let xhr = new XMLHttpRequest();
    xhr.open('POST', '/some-uri, true);
    this.setOnLoad(xhr);
    xhr.send(formData);
}

setOnLoad(xhr) {
    xhr.onload = function(){
      if (xhr.status == 200){
         // request succeeded...
      } else if (xhr.status == 500){
        // request failed
      } else {
       // anything else..
      }
    };
  }
</code>```

答:
You can check the state isFormSubmitted and disable the submit logic:

```<code>  handleFormSubmission() {
    if (this.state.isFormSubmitted) return;
    this.setState({
      isFormSubmitted: true
    });

    // stuff...
    let xhr = new XMLHttpRequest();
    xhr.open('POST', '/some-uri, true);
      this.setOnLoad(xhr); xhr.send(formData);
    }

    setOnLoad(xhr) {
      xhr.onload = function() {
        if (xhr.status == 200) {
          // request succeeded...
        } else if (xhr.status == 500) {
          // request failed
        } else {
          // anything else..
        }
        this.setState({
          isFormSubmitted: false
        });
      };
    }
</code>```

Body:
I'm creating a reactjs form that submits a form (with field data and a file).

When the Submit button is clicked, its triggers the onClick event that invokes some handleFormSubmission method.

This handleFormSubmission method first disables the button, then creates an XMLHttpRequest that sends the form data away. It might take some moment to the response to come back, and until then the button remains disable.

But once the response is theree, be it successful (code 200) or fail (code 500), I want the Submit button to be re-enabled so user can do another submission.

For the disabling, I simply set the state isFormSubmitted to true, and bind it to the button's disabled property. How could I then re-enable it?

handleFormSubmission() {
    this.setState({
      isFormSubmitted: true
    });

    // stuff...
    let xhr = new XMLHttpRequest();
    xhr.open('POST', '/some-uri, true);
    this.setOnLoad(xhr);
    xhr.send(formData);
}

setOnLoad(xhr) {
    xhr.onload = function(){
      if (xhr.status == 200){
         // request succeeded...
      } else if (xhr.status == 500){
        // request failed
      } else {
       // anything else..
      }
    };
  }

Body:
You can check the state isFormSubmitted and disable the submit logic:

  handleFormSubmission() {
    if (this.state.isFormSubmitted) return;
    this.setState({
      isFormSubmitted: true
    });

    // stuff...
    let xhr = new XMLHttpRequest();
    xhr.open('POST', '/some-uri, true);
      this.setOnLoad(xhr); xhr.send(formData);
    }

    setOnLoad(xhr) {
      xhr.onload = function() {
        if (xhr.status == 200) {
          // request succeeded...
        } else if (xhr.status == 500) {
          // request failed
        } else {
          // anything else..
        }
        this.setState({
          isFormSubmitted: false
        });
      };
    }


问:
Kotlin AlarmManager and BroadcastReceiver not working
I'm trying to set an alarm with AlarmManager, but my BroadcastReceiver never gets called.  Here is my snippet.

```<code>    val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            //Never gets hit
        }
    }
    context.registerReceiver(receiver, IntentFilter(LOCAL_NOTIFICATION))

    val intent = Intent()
    intent.action = LOCAL_NOTIFICATION

    val alarmManager = context.getSystemService(ALARM_SERVICE) as? AlarmManager
    val pendingIntent = PendingIntent.getService(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)

    val calendar = Calendar.getInstance()

    calendar.add(Calendar.SECOND, 10)

    alarmManager?.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)
</code>```

I've tried registering a broadcast receiver in AndroidManifest.xml but nothing seems to be working.

答:
I just noticed that I was calling getService() on PendingIntent instead of getBroadcast()

After changing that, it works perfectly!

Body:
I'm trying to set an alarm with AlarmManager, but my BroadcastReceiver never gets called.  Here is my snippet.

    val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            //Never gets hit
        }
    }
    context.registerReceiver(receiver, IntentFilter(LOCAL_NOTIFICATION))

    val intent = Intent()
    intent.action = LOCAL_NOTIFICATION

    val alarmManager = context.getSystemService(ALARM_SERVICE) as? AlarmManager
    val pendingIntent = PendingIntent.getService(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT)

    val calendar = Calendar.getInstance()

    calendar.add(Calendar.SECOND, 10)

    alarmManager?.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)

I've tried registering a broadcast receiver in AndroidManifest.xml but nothing seems to be working.


问:
render page on phantomjs with cron in node
I need to rennder page to img. I`m using phantomjs, childProcess and cron. If you know another way - write it please. In my way i do next, but it works only one first time. Help me please.

This is cron code:

var Cron = require('cron').CronJob;
var i = 0;

var job = new Cron({
  cronTime: "*/10 * * * * *",
  onTick: function() {
    console.log("iteration is ", i);
    var render = require('../tests/initphantom');
    i++;
  }
});

job.start();```
</div>
</div>
</p>

<p>phantomjs code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var webPage = require('webpage');
var page = webPage.create();

page.viewportSize = {
  width: 1920,
  height: 5000
};
page.open("http://localhost:3000/", function start(status) {
  console.log("status", status);
  page.render('test1.jpeg', {
    format: 'jpeg',
    quality: '100'
  });
  phantom.exit();
});</code>```

and intiate code:

var path = require('path');
var childProcess = require('child_process');
var phantomjs = require('phantomjs');
var binPath = phantomjs.path;

var childArgs = [
  path.join(__dirname, '/phantomTest.js')
]

module.exports.rendr = childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
  if (err) {
    console.log("err in childProcess", err)
  }
});```

答:
Thanks for watching! Answer is here:
phantomjs code - the same, but that i`ve got in cron code and it works:

var Cron = require('cron').CronJob;
var i = 0;
var path = require('path');
var childProcess = require('child_process');
var phantomjs = require('phantomjs');
var binPath = phantomjs.path;

var childArgs = [
  path.join(__dirname, '/phantomTest.js')
]

var job = new Cron({
  cronTime: "*/10 * * * * *",
  onTick: function() {
    console.log("iteration is ", i);
    childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
      console.log("stderr", stderr);
      console.info("stdout", stdout);
      if (err) {
        console.log("err in childProcess", err)
      }
    });
    i++;
  }
});

job.start();```

Body:
I need to rennder page to img. I`m using phantomjs, childProcess and cron. If you know another way - write it please. In my way i do next, but it works only one first time. Help me please.

This is cron code:

var Cron = require('cron').CronJob;
var i = 0;

var job = new Cron({
  cronTime: "*/10 * * * * *",
  onTick: function() {
    console.log("iteration is ", i);
    var render = require('../tests/initphantom');
    i++;
  }
});

job.start();

phantomjs code:

var webPage = require('webpage');
var page = webPage.create();

page.viewportSize = {
  width: 1920,
  height: 5000
};
page.open("http://localhost:3000/", function start(status) {
  console.log("status", status);
  page.render('test1.jpeg', {
    format: 'jpeg',
    quality: '100'
  });
  phantom.exit();
});

and intiate code:

var path = require('path');
var childProcess = require('child_process');
var phantomjs = require('phantomjs');
var binPath = phantomjs.path;

var childArgs = [
  path.join(__dirname, '/phantomTest.js')
]

module.exports.rendr = childProcess.execFile(binPath, childArgs, function(err, stdout, stderr) {
  if (err) {
    console.log("err in childProcess", err)
  }
});


问:
iOS11 UITableview reloadRowsAtIndexPaths glitch
Can anyone help me understand or solve this UITableView glitch in iOS11. I have managed to reproduce my issue in a fairly simple test case.

https://github.com/trapper-/iOS11-tableview-glitch

When reloading cells near the bottom of a tableview the reloaded cell will start to scroll weirdly and other cells start to move and hop around.

It gets much worse when reloading multiple cells, but I didn't want to complicate this simple example.

Edit: This issue only occurs in iOS11, works fine in iOS10 & iOS12. So
you need to download the iOS11 simulator to test this in Xcode 10

答:
This should help:</p>

```<code>[UIView performWithoutAnimation:^{
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This should help:

[UIView performWithoutAnimation:^{
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}];


问:
Update Firebase local data with observeSingleEvent
so I have a function to retrieve the user information from a given user id:

```<code>func getUserDataFrom(_ userID: String, completion: @escaping (_ userData: DBUser) -> Void) {

    ref.child(usersTable).child(userID).observeSingleEvent(of: .value) { (snapshot) in

        if let userDic = snapshot.value as? NSDictionary {

            let userData = DBUser(with: userDic)

            completion(userData)

        }

    }

}
</code>```

The problem is that this returns the local data instead of reading from Firebase. I'd like to retrieve the data from the server (as long as there's internet connection) and only read from disk if it's not available.

I know that the easiest way to accomplish this would be using a listener, but I'm making a Today Extension and they use way too much memory increasing the chances of a crash.

I've also researched about keepSynced feature but since the database reference to the users table will have a lot of children I don't know if this will affect the memory of my extension.

Long story short: I'd like to read data from Firebase once, and only read from disk if there isn't internet connection with the minimum memory usage possible.

Thank you in advance.

答:
I retrieve some explanation, I think it might help you in your case :

ObserveSingleEventType with keepSycned will not work if the Firebase
  connection cannot be established on time. This is especially true
  during appLaunch or in the appDelegate where there is a delay in the
  Firebase connection and the cached result is given instead. It will
  also not work at times if persistence is enabled and
  observeSingleEvent might give the cached data first. In situations
  like these, a continuous ObserveEventType is preferred and should be
  used if you absolutely need fresh data.

I think you don't have the choice to use a continuous listener. But to avoid performance issues why you don't remove yourself your listeners when you don't it anymore.

Body:
so I have a function to retrieve the user information from a given user id:

func getUserDataFrom(_ userID: String, completion: @escaping (_ userData: DBUser) -> Void) {

    ref.child(usersTable).child(userID).observeSingleEvent(of: .value) { (snapshot) in

        if let userDic = snapshot.value as? NSDictionary {

            let userData = DBUser(with: userDic)

            completion(userData)

        }

    }

}

The problem is that this returns the local data instead of reading from Firebase. I'd like to retrieve the data from the server (as long as there's internet connection) and only read from disk if it's not available.

I know that the easiest way to accomplish this would be using a listener, but I'm making a Today Extension and they use way too much memory increasing the chances of a crash.

I've also researched about keepSynced feature but since the database reference to the users table will have a lot of children I don't know if this will affect the memory of my extension.

Long story short: I'd like to read data from Firebase once, and only read from disk if there isn't internet connection with the minimum memory usage possible.

Thank you in advance.


问:
Is there a selection changed event for the listview control?
Is there an equivalent event to LBN_SELCHANGE but for a listview?

答:
Use LVN_ODSTATECHANGED for the event.

The event parameter is a pointer to a struct of type NMLVODSTATECHANGED.  Use the uNewState and uOldState bit-fields to determine which of these are selection changes (because there are other changes as well).  You're looking for the LVIS_SELECTED flag.

OwnerDisplayName: OJW

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jason Cohen


问:
Split into two variables?
Say I have the following: "44-xkIolspO"

I want to return 2 variables:

```<code>$one = "44";
$two = "xkIolspO";
</code>```

What would be the best way to do this?

答:
Try this:

    list($one, $two) = split("-", "44-xkIolspO", 2);

```<code>list($one, $two) = explode("-", "44-xkIolspO", 2);
</code>```

Title: Split into two variables?

Body:
Say I have the following: "44-xkIolspO"

I want to return 2 variables:

$one = "44";
$two = "xkIolspO";

What would be the best way to do this?

Body:
Try this:

    list($one, $two) = split("-", "44-xkIolspO", 2);

list($one, $two) = explode("-", "44-xkIolspO", 2);


问:
Working with epoch time in PowerShell using UniversalTime
This is probably a super simple question, but I'm a bit frustrated now because I can't find exactly what I'm looking for on the internet.

I am trying to convert a PowerShell DateTime to Epoch time using universal time.

I can do either, but can't seem to find a working command to do both.

Here is what I know I can do:

```<code>PS C:\WINDOWS\system32> (Get-Date).ToUniversalTime()
Wednesday, November 15, 2017 5:07:35 PM
</code>```

And:

```<code>PS C:\WINDOWS\system32> Get-Date -UFormat %s
1510747694.20287
</code>```

But, how do I combine them so that I get seconds since epoch in UTC? Everything I try just gives me errors about unexpected token "UFormat" or String does not have method "ToUniversalTime."

Thanks!

答:
If you look at Get-Help Get-Date the first parameter is a -Date option.  We can use that to our advantage by wrapping our Get-Date in another Get-Date like so:

```<code>$epochseconds = Get-Date (Get-Date).ToUniversalTime() -UFormat %s
return $epochseconds
</code>```

Body:
This is probably a super simple question, but I'm a bit frustrated now because I can't find exactly what I'm looking for on the internet.

I am trying to convert a PowerShell DateTime to Epoch time using universal time.

I can do either, but can't seem to find a working command to do both.

Here is what I know I can do:

PS C:\WINDOWS\system32> (Get-Date).ToUniversalTime()
Wednesday, November 15, 2017 5:07:35 PM

And:

PS C:\WINDOWS\system32> Get-Date -UFormat %s
1510747694.20287

But, how do I combine them so that I get seconds since epoch in UTC? Everything I try just gives me errors about unexpected token "UFormat" or String does not have method "ToUniversalTime."

Thanks!

Body:
If you look at Get-Help Get-Date the first parameter is a -Date option.  We can use that to our advantage by wrapping our Get-Date in another Get-Date like so:

$epochseconds = Get-Date (Get-Date).ToUniversalTime() -UFormat %s
return $epochseconds


问:
Unable to find the solution for this error : Django: django.db.utils.IntegrityError: NOT NULL constraint failed: book_comment.related_post_id
In short:

   I have created a Post model and Comment model and created a comment form, I am serving a single url which will show all posts, related comment and a comment form to enter new comments. With a submission page is reloaded with new comments. But when I submit the comment I get the error:

django.db.utils.IntegrityError: NOT NULL constraint failed: book_comment.related_post_id

This is one answer that looked promising but I am unable to do something.
I think it is not getting parent post id.

Long Version:

This is my model File:

```<code>def user_image_path(instance, filename):
    return f"profile/user_{random.randint(1,1000)}_{filename}"

class Post(models.Model):

    post_title = models.CharField(max_length=250)
    post_creator = models.CharField(max_length=150)
    creator_pic = models.ImageField(upload_to=user_image_path)
    post_body = models.TextField()
    post_created = models.DateTimeField(auto_now_add=True)
    post_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.post_title} **{self.post_creator}**"

class Comment(models.Model):
    related_post = models.ForeignKey(Post, related_name="comments")
    comment_creator = models.CharField(max_length=150)
    comment_body = models.CharField(max_length=1024)
    comment_created = models.DateTimeField(auto_now_add=True)
    comment_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.comment_creator}"
</code>```

This is my form:

```<code>from django import forms
from .models import Post, Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['comment_creator', 'comment_body']
</code>```

This is views:

```<code>from django.shortcuts import render, HttpResponseRedirect,reverse
from .models import Comment, Post
from .forms import CommentForm
# Create your views here.

def servePage(request):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            form.save()
            HttpResponseRedirect(reverse('serve'))
    else:
        form = CommentForm()
    posts = Post.objects.all()

    return render(request, 'book/showpost.html', {'posts': posts, 'form': form})
</code>```

This is my html template:

```<code>{% extends 'book/base.html' %}

{% block content %}
    <h1>Welcome to book of life</h1>
    <h2>New posts</h2>
    <ul>
        {% for post in posts %}
            <li>{{ post.post_title }} by <small>{{ post.post_creator }}</small></li>
            <p>{{ post.post_created|timesince }}</p>
            <p>Content: <span>{{ post.post_body }}</span></p>
{#            <br>#}
            <h3>Comments:</h3>
            {% for comment in post.comments.all %}
                <p>{{ comment.comment_creator }} => {{ comment.comment_body }}</p>
            {% endfor %}
            <form method="post">
                {% csrf_token %}
                {{ form.as_p }}
                <input type="submit" name="comment">
            </form>
            <br><br>
        {% endfor %}
    </ul>
{% endblock %}
</code>```

Sorry for any mistakes. Thanks in advance.

答:
I believe this error has occurred because you have tried to create a new record in the comment model that leaves the related_post field blank, when it shouldn't be. If you are happy for this field to be left blank, you can change the field to be the following in models.py :

```<code>related_post = models.ForeignKey(Post, related_name="comments", null=True)
</code>```

Alternatively, you may not want this to be blank. If you add related_post to the fields in the form, a drop down box will be created with all the posts and you can select one of these to comment on.

You may also be able to automatically detect what post you are commenting on, but I'm unsure how this is done.

Body:
In short:

   I have created a Post model and Comment model and created a comment form, I am serving a single url which will show all posts, related comment and a comment form to enter new comments. With a submission page is reloaded with new comments. But when I submit the comment I get the error:

django.db.utils.IntegrityError: NOT NULL constraint failed: book_comment.related_post_id

This is one answer that looked promising but I am unable to do something.
I think it is not getting parent post id.

Long Version:

This is my model File:

def user_image_path(instance, filename):
    return f"profile/user_{random.randint(1,1000)}_{filename}"

class Post(models.Model):

    post_title = models.CharField(max_length=250)
    post_creator = models.CharField(max_length=150)
    creator_pic = models.ImageField(upload_to=user_image_path)
    post_body = models.TextField()
    post_created = models.DateTimeField(auto_now_add=True)
    post_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.post_title} **{self.post_creator}**"

class Comment(models.Model):
    related_post = models.ForeignKey(Post, related_name="comments")
    comment_creator = models.CharField(max_length=150)
    comment_body = models.CharField(max_length=1024)
    comment_created = models.DateTimeField(auto_now_add=True)
    comment_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.comment_creator}"

This is my form:

from django import forms
from .models import Post, Comment

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['comment_creator', 'comment_body']

This is views:

from django.shortcuts import render, HttpResponseRedirect,reverse
from .models import Comment, Post
from .forms import CommentForm
# Create your views here.

def servePage(request):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            form.save()
            HttpResponseRedirect(reverse('serve'))
    else:
        form = CommentForm()
    posts = Post.objects.all()

    return render(request, 'book/showpost.html', {'posts': posts, 'form': form})

This is my html template:

{% extends 'book/base.html' %}

{% block content %}

Welcome to book of life

New posts

        {% for post in posts %}

{{ post.post_title }} by {{ post.post_creator }}

{{ post.post_created|timesince }}

Content: {{ post.post_body }}

{#
#}

Comments:

            {% for comment in post.comments.all %}

{{ comment.comment_creator }} => {{ comment.comment_body }}

            {% endfor %}
            <form method="post">
                {% csrf_token %}
                {{ form.as_p }}
                <input type="submit" name="comment">
            </form>

        {% endfor %}

{% endblock %}

Sorry for any mistakes. Thanks in advance.

Body:
I believe this error has occurred because you have tried to create a new record in the comment model that leaves the related_post field blank, when it shouldn't be. If you are happy for this field to be left blank, you can change the field to be the following in models.py :

related_post = models.ForeignKey(Post, related_name="comments", null=True)

Alternatively, you may not want this to be blank. If you add related_post to the fields in the form, a drop down box will be created with all the posts and you can select one of these to comment on.

You may also be able to automatically detect what post you are commenting on, but I'm unsure how this is done.


问:
Compiling zip component for PHP 5.2.11 in MAMP PRO
Helo

I installed MAMP PRO on my Macbook Pro (10.6) some time ago. Now I would like to use zip functions in php. I found that I must add zip.so to my extension folder and edited php.ini.

On my computer I have two different versions of PHP one in MAMP folder and other in user/lib which was pre-installed on my system.  Now I wish to compile my zip library for MAMP version.

I got zip sources for my version of PHP then in terminal called function
/Applications/MAMP/bin/php5/bin/phpize so it uses mamp php version

./configure

make

then I moved compile zip.so to extensions/no-debug-non-zts-20060613.

When MAMP is launched it returns this error:

[11-Apr-2010 16:33:27] PHP Warning:  PHP Startup: zip: Unable to initialize module
Module compiled with module API=20090626, debug=0, thread-safety=0
PHP    compiled with module API=20060613, debug=0, thread-safety=0
These options need to match
 in Unknown on line 0

Can some body explain to me how to do this the right way.

答:
Did you tried phpenmod zip?

```<code>usage: phpenmod [ -v ALL|php_version ] \
                [ -s ALL|sapi_name ] module_name \
                [ module_name_2 ]
</code>```

You can list all your available modules with ls /etc/php/*/mods-available.

Body:
Did you tried phpenmod zip?

usage: phpenmod [ -v ALL|php_version ] \
                [ -s ALL|sapi_name ] module_name \
                [ module_name_2 ]

You can list all your available modules with ls /etc/php/*/mods-available.


问:
JS: Array has no method 'keys' (Cordova, Android)
I am initializing a new array from a mappable function:

```<code>let data = Array.from(Array(20).keys(), new_datum);
</code>```

It gets webpack'd (v 3.5.5) to:

```<code>var data = Array.from(Array(20).keys(), new_datum);
</code>```

For completeness, here's that function, though I doubt it's relevant:

```<code>function new_datum() {
  return {
    name: Math.floor((Date.now() - START_TIME) / 1000),
    Temperature: Math.random() * 100
  }
}
</code>```

This works fine in my Chrome browser on desktop. However, when using Cordova (v 7.1.0) and Android (26) to compile this to an SDK and run on my phone (kitkat 4.4.4, Chrome 56.0.2924.87), I get the following:

```<code>Uncaught TypeError: Object [object Array] has no method 'keys'
</code>```

My intuition is, "something something ECMA6", because the Array.keys() method is pretty new, but since I am still pretty green with JS, I am stumped.

Edit: Additionally, looking at the App's userAgent:

```<code>5.0 (Linux; Android 4.4.4; XT1080 Build/SU6-7.7) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36
</code>```

I see that Cordova is using Chrome 33 for some bizarre reason. That's likely the problem.

Addendum:

Since I confirmed the Cordova app is indeed using Chrome 33, this is likely the reason why Array methods do not work properly.

It looks like there are some limitations with respect to WebView and hence Cordova chrome version. There are workarounds, but I suspect the easiest approach is just tooling the app for Chrome 33.

答:
Cordova is not using any specific version of chrome and may not even be using chrome at all.

Let me explain : what cordova does is that it uses the Webview component to bundle your html into a native application.

For Android, depending on the device you're using, the engine of the webview component is different. It may be based on the old android browser, the device manufacturer's browser or for device using android newer than 4.4 chrome. And for most devices, the webview can't be updated.

So the app behaviour is different for each device : html5 support, css support, strict mode, js version, wether or not you need to configure Content-Security-Policy...

You may have surprises with cordova each time a user uses your app on a new device.

You have to use javascript / css /html supported by the oldest platform version you target (for that you can refer to canIuse) and at the same time conform with the newest requirements (like Content Security Policy that is mandatory starting android 4.4).

Starting with Android 5.0 the webview (based on chrome) is in an apk and is updatable, so cordova apps runing on android 5 devices will be able to use up to date html5 features.

If you want to be sure that your app will behave the same way on all devices (except for screen size), I think the best choice for the moment is to use Crosswalk.

Crosswalk is a webview based on latest versions of Chromium.

If you add the Crosswalk Cordova plugin to your app, cordova will use the crosswalk engine instead of the system webview so your app will use the same engine on all devices and you have no more surprise with a javascript line working on a device but not on an other.

The only drawback of using Crosswalk is that you embed the Chromium engine in your apk, wich makes it much bigger (+17Mb for the apk and +50Mb on the device once the app installed).

Edit: sad to hear about the EOL of official Crosswalk project. Version 2.3 works perfectly in the Cordova plugin, hope someone will update it in the future.

Body:
I am initializing a new array from a mappable function:

let data = Array.from(Array(20).keys(), new_datum);

It gets webpack'd (v 3.5.5) to:

var data = Array.from(Array(20).keys(), new_datum);

For completeness, here's that function, though I doubt it's relevant:

function new_datum() {
  return {
    name: Math.floor((Date.now() - START_TIME) / 1000),
    Temperature: Math.random() * 100
  }
}

This works fine in my Chrome browser on desktop. However, when using Cordova (v 7.1.0) and Android (26) to compile this to an SDK and run on my phone (kitkat 4.4.4, Chrome 56.0.2924.87), I get the following:

Uncaught TypeError: Object [object Array] has no method 'keys'

My intuition is, "something something ECMA6", because the Array.keys() method is pretty new, but since I am still pretty green with JS, I am stumped.

Edit: Additionally, looking at the App's userAgent:

5.0 (Linux; Android 4.4.4; XT1080 Build/SU6-7.7) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36

I see that Cordova is using Chrome 33 for some bizarre reason. That's likely the problem.

Addendum:

Since I confirmed the Cordova app is indeed using Chrome 33, this is likely the reason why Array methods do not work properly.

It looks like there are some limitations with respect to WebView and hence Cordova chrome version. There are workarounds, but I suspect the easiest approach is just tooling the app for Chrome 33.


问:
How to avoid duplicate file upload but keep the uploader unaware of it?
First of all, I apologize if the question is not clear, I'm explaining it below.

For every file uploaded, I'm renaming the file and recording the hash values (using sha1_files function, please suggest if there are some better or faster hashing techniques for the file in php) in a separate DB table and checking the hash of every new file to avoid duplicate files.

In this manner, the one uploading a duplicate file will get an error msg and the file won't be uploaded.

My question is, is there any techniques or algorithm by which I can prevent duplicate file upload but the duplicate file uploader will be unaware of it and will find the file in his/her account with a different name than the one already present. However, users won't be able to upload banned files by any means.

答: Just add some extra logic in your code possibly using an extra table or extra fields in the existing table (it is up to you, there is more than one way to do it) that saves the file to an alternate location should you discover it is a duplicate rather than sending an error. Not sure, though, if what you are doing is a good idea from the UI design point of view, as you are doing something different with the user input in a way that the user will notice without telling the user why.</p>


问:
Primitive data type variables in Java
Are variables of primitive data types in Java considered objects of the wrapper class? I am new to programming so please explain.

答:
No. Primitive data types (int, char, byte, double, etc.) are not objects, nor are they classes. The word 'primitive' lets you know that they are primal, more basic, than objects.

Primitive data types do not have member functions or class Constructors because they aren't classes themselves. You cannot call a function from a primitive data type. You couldn't do something like

```<code>double b = 5.5;
b.round();
</code>```

There are Wrapper class Objects for each of the primitive data types. Integer is the object class for int data types. Double for doubles. etc.

These Wrapper Objects can and do have member functions and can also be created by Class Constructors:

```<code>Integer a = new Integer(1);
</code>```

Also, as a sidebar, because new programmers often are confused by this: the String data type is not a primitive in Java. It is an Object, backed by an array of chars (a primitive data type). You can, however, declare a new String without using the new operator:

```<code>String s = "This is a string";
</code>```

Title: Primitive data type variables in Java

Body:
No. Primitive data types (int, char, byte, double, etc.) are not objects, nor are they classes. The word 'primitive' lets you know that they are primal, more basic, than objects.

Primitive data types do not have member functions or class Constructors because they aren't classes themselves. You cannot call a function from a primitive data type. You couldn't do something like

double b = 5.5;
b.round();

There are Wrapper class Objects for each of the primitive data types. Integer is the object class for int data types. Double for doubles. etc.

These Wrapper Objects can and do have member functions and can also be created by Class Constructors:

Integer a = new Integer(1);

Also, as a sidebar, because new programmers often are confused by this: the String data type is not a primitive in Java. It is an Object, backed by an array of chars (a primitive data type). You can, however, declare a new String without using the new operator:

String s = "This is a string";


问:
How do I make my java application open a console/terminal window?
Is there any way I can make an executable .jar that will open up the command line when double clicked?

I'm making a text-based adventure game. As of right now it is just a maze with rooms. Eventually it is going to be much bigger and more in depth but for now I just want to get the basic structure down. Anyways, to make this work I've been getting output and input from the System.out.printf command and the java.util.Scanner. It's all working beautifully so far but I've realized I'm going to run into a problem when I try to send this to other people that don't know how or just don't want to run the program from the command line.

答:
Use Launch4j and in Basic Tab give your exe name in Output file and then load a jar file in Jar Tab.

Go to Header Tab and select Console.

Then go to JRE tab and give the JRE version e.g 1.8.0

Then click the build wrapper button (kind of setting icon)

It will ask you to save a xaml file just put some random name and click save.

Finally your .exe is created and you can run now.


答:
PHP has a function called preg_split() splits a string using a regular expression. This should do what you want.

Or explode() might be easier.

```<code>    $str = "44-xkIolspO";
    $parts = explode("-", $str);
    $one = $parts[0];
    $two = $parts[1];
</code>```

Title: Split into two variables?

Body:
PHP has a function called preg_split() splits a string using a regular expression. This should do what you want.

Or explode() might be easier.

    $str = "44-xkIolspO";
    $parts = explode("-", $str);
    $one = $parts[0];
    $two = $parts[1];


问:
How to use Polymer lifecycle hooks
I have a component that contains video. My component is nested in a dom-if and can disappear. When this happens the video (and it sound) keep playing.

Is there a way in which my component can detect that is has  disappeared from the DOM? I have tried to use the 'detached' callback as described here: https://www.polymer-project.org/1.0/docs/devguide/registering-elements

```<code>Polymer({
  is: 'my-component-with-video',

  properties: {
     // some properties
  },

  detached: function() {
    console.log('Component detached');
    // more code to stop video
  },
</code>```

but when my element is removed by the dom-if nothing happens, I don't see the console.log message. What am I doing wrong?

答:
In your detached function you need to get the Video Element and call .pause() on it.

You will probably also need to call .pause() when your condition changes that would cause the dom-if to remove the player.

Title: How to use Polymer lifecycle hooks

Body:
I have a component that contains video. My component is nested in a dom-if and can disappear. When this happens the video (and it sound) keep playing.

Is there a way in which my component can detect that is has  disappeared from the DOM? I have tried to use the 'detached' callback as described here: https://www.polymer-project.org/1.0/docs/devguide/registering-elements

Polymer({
  is: 'my-component-with-video',

  properties: {
     // some properties
  },

  detached: function() {
    console.log('Component detached');
    // more code to stop video
  },

but when my element is removed by the dom-if nothing happens, I don't see the console.log message. What am I doing wrong?


问:
Segmentation fault using malloc/struct
I am trying to code an easy list in C, which is able to store numbers.

With number SIZE, an index will be calculated and the numbers have to be stored in a kind of linear list at the array index.

However, sometimes I get a "segmentation fault", like 2 of 10 tries the output is correct.

I've gone a long search, but I couldn't find the problem.

Please keep in mind that my "solution" isn't implemented fully, so currently it's only working when the calculated index has no pointer thats stored. (Couldn't continue to code because of the error.)

Here is my code:

```<code>#define SIZE 3
#define NULL 0

typedef struct node_s node_t;

struct node_s {
  node_t* next;
  int number;
};

static node_t nodeArray[SIZE];

int addNumber(int numb){
  int index = number % SIZE;
  if(nodeArray[index].next == NULL){
    node_t* node = (node_t*) malloc(sizeof(node_t));
    node->number = number;
    nodeArray[hash].next = node;
  }
}

void print(){
  for(int i = 0; i < SIZE; i++){
    node_t* ptr = nodeArray[i].next;
    while(ptr != NULL){
      printf("%d -> ", ptr->number);
      ptr = ptr->next;
    }
    printf("\n");
  }
}

#include "dictionary.h"
#include <stdio.h>

int main(){
  insert(1);
  insert(2);
  print();
  return 0;
}
</code>```

What causes the "segmentation fault" sometimes?
I appreciate any kind of help, thanks in advance!

答:
Just after malloc you do init one member.

```<code>node->number = number;
</code>```

But you do not init the other member, there is no

```<code>node->next = NULL;
</code>```

Also, in your loop condition inside print(), you check ptr against NULL, but that is in most of the looping the non-initialised ptr->next from previous loop.

```<code>ptr = ptr->next;
</code>```

I.e. you rely on it to be initialised to NULL.

That is probably causing the segfault.

Useful background, as pointed out by yano (thanks):

Malloc doesn't initialize memory to 0. In order to do that you can malloc followed by a memset or you can use calloc.

Title: Segmentation fault using malloc/struct

Body:
I am trying to code an easy list in C, which is able to store numbers.

With number SIZE, an index will be calculated and the numbers have to be stored in a kind of linear list at the array index.

However, sometimes I get a "segmentation fault", like 2 of 10 tries the output is correct.

I've gone a long search, but I couldn't find the problem.

Please keep in mind that my "solution" isn't implemented fully, so currently it's only working when the calculated index has no pointer thats stored. (Couldn't continue to code because of the error.)

Here is my code:

#define SIZE 3
#define NULL 0

typedef struct node_s node_t;

struct node_s {
  node_t* next;
  int number;
};

static node_t nodeArray[SIZE];

int addNumber(int numb){
  int index = number % SIZE;
  if(nodeArray[index].next == NULL){
    node_t* node = (node_t*) malloc(sizeof(node_t));
    node->number = number;
    nodeArray[hash].next = node;
  }
}

void print(){
  for(int i = 0; i < SIZE; i++){
    node_t* ptr = nodeArray[i].next;
    while(ptr != NULL){
      printf("%d -> ", ptr->number);
      ptr = ptr->next;
    }
    printf("\n");
  }
}

#include "dictionary.h"
#include <stdio.h>

int main(){
  insert(1);
  insert(2);
  print();
  return 0;
}

What causes the "segmentation fault" sometimes?
I appreciate any kind of help, thanks in advance!

Body:
Just after malloc you do init one member.

node->number = number;

But you do not init the other member, there is no

node->next = NULL;

Also, in your loop condition inside print(), you check ptr against NULL, but that is in most of the looping the non-initialised ptr->next from previous loop.

ptr = ptr->next;

I.e. you rely on it to be initialised to NULL.

That is probably causing the segfault.

Useful background, as pointed out by yano (thanks):

Malloc doesn't initialize memory to 0. In order to do that you can malloc followed by a memset or you can use calloc.


问:
How to compress 2GB to 300 mb using python library
I've one million of string data and writing into a file, I'm using Python gZip compression which comes around 2gb of size, I want to reduce into 250-300 MB?

Is there any way to compress more and bring it to 300 MB?

Any help would be much appreciated.

Thanks!

答:
Sometimes you can help gzip and other algorithms preprocessing the data before compression.

For instance, if you have an image, instead of compressing the raw pixel data, you can try to compress the differences between the current pixel and the previous one.

So, instead of just compressing your string data, try pre-processing it before using your knowledge about the data itself.

Do not just compute deltas between characters: try normalizing stuff to reduce variance (remove unneeded characters, whitespace between the last character and end of line, unneeded whitespace, etc).

If your string data is composed by fields (usually it is), another technique that works is compressing the columns instead of the rows. Columnar data tends to have less variance and gzip will exploit that easily.

Keep in mind going from 2GB compressed data to 300M compressed will be quite hard to achieve, and you might need to process the data after decompressing in order to be usable.


问:
Where is the EventListener stored?
HHi everybody.
Anybody know where are stored Event when we use addEventListener method ???
example :

```<code>window.addEventListener('mousedown', this.myvar.onClick );
</code>```

that's ok , but i try to find where it's stored ???
i try check in

```<code>windows.event
windows.Event()
console.dir(window.addEventListener)
window._debugWindow
window.dispatchEvent()
// ... many other try
</code>```

I found no way to check where currents data listener stored.

i need to have the list || register for debug
thank for help

SOLVED EDIT:

答: In Chrome's devtools, you can use getEventListeners(node) to view what is bound on an object.

Title: Where is the EventListener stored?

Body:
HHi everybody.
Anybody know where are stored Event when we use addEventListener method ???
example :

window.addEventListener('mousedown', this.myvar.onClick );

that's ok , but i try to find where it's stored ???
i try check in

windows.event
windows.Event()
console.dir(window.addEventListener)
window._debugWindow
window.dispatchEvent()
// ... many other try

I found no way to check where currents data listener stored.

i need to have the list || register for debug
thank for help

SOLVED EDIT:


问:
EDIT (judge harshly): My display() method won't display and I'm not sure why
I recently posted a question in regards to my display() method only displaying certain objects, and was able to correct that with some feedback I received earlier in regards to my toString() method. However, I had to change my idNum to an int, and now my displayMethod() won't display at all. I tried retracing my steps and am unsure what happened.

The object array that is supposed to hold an identification number, a sales amount, and the persons name. However, when I display the array, nothing is displaying. I've tried the for loop, enhanced for loop and tried just a system.out.print invoking the get() methods.

I don't know if it has something to do with my displayDatabase() method, the way I am using my Scanner variable (USER_INPUT) to set the data entered, or something to do with my constructors.

My constructor looks like this:

==================================================

```<code> public class Salesperson
   {
   private String salesName;
   private int salesID;
   private double annualSales;

   public Salesperson(String salesName, int salesIDNum, double yearlySales)
   {
       this.salesName = salesName;
       salesID = salesIDNum;
       annualSales = yearlySales;
   }

   public String getSalesName()
   {
       return salesName;
   }
   public void setSalesName(String salesName)
   {
       this.salesName = salesName;
   }
   public double getSalesID()
   {
       return salesID;
   }
   public void setSalesID(int salesIDNum)
   {
       salesID = salesIDNum;
   }
   public double getAnnualSales()
   {
       return annualSales;
   }
   public void setAnnualSales(double yearlySales)
   {
       annualSales = yearlySales;
   }
   @Override
   public String toString()
   {
       return String.format("%s-%-10s%-10.2f", salesName,
                salesID, annualSales);
    }
</code>```

       }

```<code>And my code for application looks like this:

    import java.util.Arrays;
    import java.util.Scanner;
     public class CreateSalesperson
     {
       private static final Scanner USER_INPUT = new Scanner(System.in);
       private static final int UPPER_SIZE_LIMIT = 20;
       private static final int LOWER_SIZE_LIMIT = 0;
       private static Salesperson[] salesStaffInDatabase = new
      Salesperson[20];
       private static int numOfSalesPpl = 0;
       private static boolean loop = true;
       public static void main(String[] args)
      {
       String selection;
       selection = programMenu();
       String response;

            while(loop)
              switch(selection)
              {
                  case "A":
                      if(numOfSalesPpl == UPPER_SIZE_LIMIT)
                      {
                        System.out.print("Database has reached capacity.");
                        System.out.print(" Please delete a record before ");
                        System.out.println("adding to the database.");
                      }
                      else
                      {
                        addRecord();
                      }
                      break;
                  case "a":
                      if(numOfSalesPpl == UPPER_SIZE_LIMIT)
                      {
                        System.out.print("Database has reached capacity.");
                        System.out.print(" Please delete a record before ");
                        System.out.println("adding to the database.");
                      }
                      else
                      {
                        addRecord();
                      }
                      break;
                    case "C":
                      if(numOfSalesPpl == LOWER_SIZE_LIMIT)
                      {
                        System.out.print("Database is empty. ");
                        System.out.print("Please add a record.");
                      }
                      else
                      {
                        changeRecord();
                      }
                      break;
                    case "c":
                      if(numOfSalesPpl == LOWER_SIZE_LIMIT)
                      {
                        System.out.print("Database is empty. ");
                        System.out.print("Please add a record.");
                      }
                      else
                      {
                        changeRecord();
                      }
                      break;
                    case "E":
                    System.out.print("You Are Leaving Database");
                    loop = false;
                    break;
                    case "e":
                    System.out.print("You Are Leaving Database");
                    loop = false;
                    break;
                }
                }

      public static void changeRecord()
        {
            String idNum;
            String salesName;
            double salesAmount;
            String response;

            System.out.print("Enter Sales ID: ");
            idNum = USER_INPUT.nextLine();
            if(isValidID(idNum))

            {
            int searchResult = Arrays.binarySearch(salesStaffInDatabase, idNum);
            System.out.println(salesStaffInDatabase[searchResult]);
            }
            else
            {
                System.out.println("Invalid Sales ID");
            }
        }
     public static boolean isValidID(String idNum)
     {
     boolean isValid= false;
     for(int val = 0;val < numOfSalesPpl && !isValid; ++val)
     {
         if(salesStaffInDatabase[val].equals(idNum))
                 {
                   isValid = true;
                 }
     }
     return isValid;
     }
     public static void addRecord()
     {
        int idNum;
        String salesName;
        double salesAmount;
        String idNo;
        String response;

       do
       {
        System.out.print("Please enter sales ID: ");
        idNum = USER_INPUT.nextInt();
        idNo = Integer.toString(idNum);
        if(idNo.length() != 8)

           System.out.println("Sales ID must be 8 digits long: ");

       }
       while(idNo.length() < 8 || idNo.length() > 8);

        System.out.print("Name: ");
        salesName = USER_INPUT.nextLine();
        USER_INPUT.nextLine();
        System.out.print("Sales Amount: ");
        salesAmount = Double.parseDouble(USER_INPUT.nextLine());
        salesStaffInDatabase[numOfSalesPpl] = new
     Salesperson(salesName,idNum,salesAmount);

        salesStaffInDatabase[numOfSalesPpl].setSalesName(salesName);
        salesStaffInDatabase[numOfSalesPpl].setSalesID(idNum);
        salesStaffInDatabase[numOfSalesPpl].setAnnualSales(salesAmount);

        System.out.print("Do you want to display database Y/N?: ");
        response = USER_INPUT.nextLine();
        while(response.equalsIgnoreCase("Y")||response.equalsIgnoreCase("yes"))
        {
          displayDatabase();
        }
    }

    public static void displayDatabase()
    {

        for(int val=0;val < numOfSalesPpl; val++)
        {
              System.out.println(salesStaffInDatabase[val]);
        }

    }
    public static String programMenu()
    {
    String selection;
     do
        {

         System.out.println("(A)dd a Record");
         System.out.println("(C)hange a Record");
         System.out.println("(E)xit Database");
         System.out.print("Enter selection: ");
         selection = USER_INPUT.nextLine();
        }
        while(!selection.equalsIgnoreCase("a") &&
    !selection.equalsIgnoreCase("c")
        && !selection.equalsIgnoreCase("e"));
        return selection;
    }
    }
</code>```

=================================================================

答:
In Java, whenever you want to display an object as string, you must override the toString() method.
The code that you posted, the Salesperson's toString() method returns only the salesID and anualSales. If you want to display another attribute, you must place it in the toString() method.

If you want to display the first name on the beginning of the output, you can do:

```<code>@Override public String toString() {
    return String.format("%s - %-10s%-10.2f", salesFirstName, salesID, annualSales);
}
</code>```

Body:
I recently posted a question in regards to my display() method only displaying certain objects, and was able to correct that with some feedback I received earlier in regards to my toString() method. However, I had to change my idNum to an int, and now my displayMethod() won't display at all. I tried retracing my steps and am unsure what happened.

The object array that is supposed to hold an identification number, a sales amount, and the persons name. However, when I display the array, nothing is displaying. I've tried the for loop, enhanced for loop and tried just a system.out.print invoking the get() methods.

I don't know if it has something to do with my displayDatabase() method, the way I am using my Scanner variable (USER_INPUT) to set the data entered, or something to do with my constructors.

My constructor looks like this:

==================================================

 public class Salesperson
   {
   private String salesName;
   private int salesID;
   private double annualSales;

   public Salesperson(String salesName, int salesIDNum, double yearlySales)
   {
       this.salesName = salesName;
       salesID = salesIDNum;
       annualSales = yearlySales;
   }

   public String getSalesName()
   {
       return salesName;
   }
   public void setSalesName(String salesName)
   {
       this.salesName = salesName;
   }
   public double getSalesID()
   {
       return salesID;
   }
   public void setSalesID(int salesIDNum)
   {
       salesID = salesIDNum;
   }
   public double getAnnualSales()
   {
       return annualSales;
   }
   public void setAnnualSales(double yearlySales)
   {
       annualSales = yearlySales;
   }
   @Override
   public String toString()
   {
       return String.format("%s-%-10s%-10.2f", salesName,
                salesID, annualSales);
    }

       }

And my code for application looks like this:

    import java.util.Arrays;
    import java.util.Scanner;
     public class CreateSalesperson
     {
       private static final Scanner USER_INPUT = new Scanner(System.in);
       private static final int UPPER_SIZE_LIMIT = 20;
       private static final int LOWER_SIZE_LIMIT = 0;
       private static Salesperson[] salesStaffInDatabase = new
      Salesperson[20];
       private static int numOfSalesPpl = 0;
       private static boolean loop = true;
       public static void main(String[] args)
      {
       String selection;
       selection = programMenu();
       String response;

            while(loop)
              switch(selection)
              {
                  case "A":
                      if(numOfSalesPpl == UPPER_SIZE_LIMIT)
                      {
                        System.out.print("Database has reached capacity.");
                        System.out.print(" Please delete a record before ");
                        System.out.println("adding to the database.");
                      }
                      else
                      {
                        addRecord();
                      }
                      break;
                  case "a":
                      if(numOfSalesPpl == UPPER_SIZE_LIMIT)
                      {
                        System.out.print("Database has reached capacity.");
                        System.out.print(" Please delete a record before ");
                        System.out.println("adding to the database.");
                      }
                      else
                      {
                        addRecord();
                      }
                      break;
                    case "C":
                      if(numOfSalesPpl == LOWER_SIZE_LIMIT)
                      {
                        System.out.print("Database is empty. ");
                        System.out.print("Please add a record.");
                      }
                      else
                      {
                        changeRecord();
                      }
                      break;
                    case "c":
                      if(numOfSalesPpl == LOWER_SIZE_LIMIT)
                      {
                        System.out.print("Database is empty. ");
                        System.out.print("Please add a record.");
                      }
                      else
                      {
                        changeRecord();
                      }
                      break;
                    case "E":
                    System.out.print("You Are Leaving Database");
                    loop = false;
                    break;
                    case "e":
                    System.out.print("You Are Leaving Database");
                    loop = false;
                    break;
                }
                }

      public static void changeRecord()
        {
            String idNum;
            String salesName;
            double salesAmount;
            String response;

            System.out.print("Enter Sales ID: ");
            idNum = USER_INPUT.nextLine();
            if(isValidID(idNum))

            {
            int searchResult = Arrays.binarySearch(salesStaffInDatabase, idNum);
            System.out.println(salesStaffInDatabase[searchResult]);
            }
            else
            {
                System.out.println("Invalid Sales ID");
            }
        }
     public static boolean isValidID(String idNum)
     {
     boolean isValid= false;
     for(int val = 0;val < numOfSalesPpl && !isValid; ++val)
     {
         if(salesStaffInDatabase[val].equals(idNum))
                 {
                   isValid = true;
                 }
     }
     return isValid;
     }
     public static void addRecord()
     {
        int idNum;
        String salesName;
        double salesAmount;
        String idNo;
        String response;

       do
       {
        System.out.print("Please enter sales ID: ");
        idNum = USER_INPUT.nextInt();
        idNo = Integer.toString(idNum);
        if(idNo.length() != 8)

           System.out.println("Sales ID must be 8 digits long: ");

       }
       while(idNo.length() < 8 || idNo.length() > 8);

        System.out.print("Name: ");
        salesName = USER_INPUT.nextLine();
        USER_INPUT.nextLine();
        System.out.print("Sales Amount: ");
        salesAmount = Double.parseDouble(USER_INPUT.nextLine());
        salesStaffInDatabase[numOfSalesPpl] = new
     Salesperson(salesName,idNum,salesAmount);

        salesStaffInDatabase[numOfSalesPpl].setSalesName(salesName);
        salesStaffInDatabase[numOfSalesPpl].setSalesID(idNum);
        salesStaffInDatabase[numOfSalesPpl].setAnnualSales(salesAmount);

        System.out.print("Do you want to display database Y/N?: ");
        response = USER_INPUT.nextLine();
        while(response.equalsIgnoreCase("Y")||response.equalsIgnoreCase("yes"))
        {
          displayDatabase();
        }
    }

    public static void displayDatabase()
    {

        for(int val=0;val < numOfSalesPpl; val++)
        {
              System.out.println(salesStaffInDatabase[val]);
        }

    }
    public static String programMenu()
    {
    String selection;
     do
        {

         System.out.println("(A)dd a Record");
         System.out.println("(C)hange a Record");
         System.out.println("(E)xit Database");
         System.out.print("Enter selection: ");
         selection = USER_INPUT.nextLine();
        }
        while(!selection.equalsIgnoreCase("a") &&
    !selection.equalsIgnoreCase("c")
        && !selection.equalsIgnoreCase("e"));
        return selection;
    }
    }

=================================================================

Body:
In Java, whenever you want to display an object as string, you must override the toString() method.
The code that you posted, the Salesperson's toString() method returns only the salesID and anualSales. If you want to display another attribute, you must place it in the toString() method.

If you want to display the first name on the beginning of the output, you can do:

@Override public String toString() {
    return String.format("%s - %-10s%-10.2f", salesFirstName, salesID, annualSales);
}


问:
Unity 3d Follow camera
Have this camera working perfect on my target object with one caveat. Can't seem to get the character to look up and down. Left and right move perfectly, up and down don't move at all. What am I doing wrong with the "Mouse Y" part?

```<code>    public GameObject target;
    public float rotateSpeed = 7;
    Vector3 offset;

    void Start() {
        offset = target.transform.position - transform.position;
    }

    void LateUpdate() {
        float horizontal = Input.GetAxis("Mouse X") * rotateSpeed * Time.deltaTime;
        float verticle = Input.GetAxis("Mouse Y") * rotateSpeed * Time.deltaTime;
        target.transform.Rotate(0, horizontal, 0);

        float desiredAngle = target.transform.eulerAngles.y;

        Quaternion rotation = Quaternion.Euler(0, desiredAngle, verticle);
        transform.position = target.transform.position - (rotation * offset);

        transform.LookAt(target.transform);
    }
</code>```

答: The last line of code (transform.Lookat) overrides the previous code ... basically says 'always look at the target no matter what else happens'.</p>

Title: Unity 3d Follow camera

Body:
Have this camera working perfect on my target object with one caveat. Can't seem to get the character to look up and down. Left and right move perfectly, up and down don't move at all. What am I doing wrong with the "Mouse Y" part?

    public GameObject target;
    public float rotateSpeed = 7;
    Vector3 offset;

    void Start() {
        offset = target.transform.position - transform.position;
    }

    void LateUpdate() {
        float horizontal = Input.GetAxis("Mouse X") * rotateSpeed * Time.deltaTime;
        float verticle = Input.GetAxis("Mouse Y") * rotateSpeed * Time.deltaTime;
        target.transform.Rotate(0, horizontal, 0);

        float desiredAngle = target.transform.eulerAngles.y;

        Quaternion rotation = Quaternion.Euler(0, desiredAngle, verticle);
        transform.position = target.transform.position - (rotation * offset);

        transform.LookAt(target.transform);
    }


问:
Warning: setState(...): Can only update a mounted or mounting component. With timer
```<code>Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Clock component.
</code>```

Why is this error keeping being displayed ?? When I log out from my app this warning starts to appear on the console. Could anybody explain why that happens ?

```<code>const Clock = React.createClass({

    getInitialState() {
        return {
            currentTime: moment.utc().format(formatter)
        };
    },

    componentDidMount: function() {
        const tickId = setInterval(this.tick, 1000);
        this.setState({tickId: tickId});
    },

    componentWillUnmount: function() {
        clearInterval(this.state.tickId);
    },

    tick: function() {
        this.setState({
            currentTime: moment.utc().format(formatter)
        });
    },

    render() {
        return <span>{this.state.currentTime}</span>;
    }
});
</code>```

答:
No need to store the tickId in state.

```<code>componentDidMount: function() {
    this.tickId = setInterval(this.tick, 1000);
},

componentWillUnmount: function() {
    clearInterval(this.tickId);
}
</code>```

Body:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Clock component.

Why is this error keeping being displayed ?? When I log out from my app this warning starts to appear on the console. Could anybody explain why that happens ?

const Clock = React.createClass({

    getInitialState() {
        return {
            currentTime: moment.utc().format(formatter)
        };
    },

    componentDidMount: function() {
        const tickId = setInterval(this.tick, 1000);
        this.setState({tickId: tickId});
    },

    componentWillUnmount: function() {
        clearInterval(this.state.tickId);
    },

    tick: function() {
        this.setState({
            currentTime: moment.utc().format(formatter)
        });
    },

    render() {
        return {this.state.currentTime};
    }
});

Body:
No need to store the tickId in state.

componentDidMount: function() {
    this.tickId = setInterval(this.tick, 1000);
},

componentWillUnmount: function() {
    clearInterval(this.tickId);
}


问:
Create schemaless collection in mongoDB via mongoose
I have the following mongoose schema records:

```<code>var mongoose = require('mongoose');

module.exports = mongoose.model('lM', {
    any     :   mongoose.Schema.Types.Mixed,
},'mlr');
</code>```

And in my code I am doing as such:

```<code>var lm      = require('../server/models/records');

new lm().save(lmr);
</code>```

Being that lmr is a JSON object.

This produces a mongodb database with the name I provided but the records inside that collection contain only:

```<code>_id: objectID
_v: 0
</code>```

The JSON objects is nowhere to be seen. How can I get the JSON object inside the any wrapper in the schema?

答:
```<code>var lm      = require('../server/models/records');

new lm({'any':lmr}).save();
</code>```

In save() method pass callback function[optional] if you want to track error if any.

```<code>new lm({'any':lmr}).save(function(err){
   if(err) {
      console.log(err)
   }else{
      console.log('saved')
   }
});
</code>```

To create the schemaless collection you will have to set strict:false which is by default true. strict option ensures values passed to your model constructor that were not specified in schema do not get saved to the db.

strict option docs

Body:
I have the following mongoose schema records:

var mongoose = require('mongoose');

module.exports = mongoose.model('lM', {
    any     :   mongoose.Schema.Types.Mixed,
},'mlr');

And in my code I am doing as such:

var lm      = require('../server/models/records');

new lm().save(lmr);

Being that lmr is a JSON object.

This produces a mongodb database with the name I provided but the records inside that collection contain only:

_id: objectID
_v: 0

The JSON objects is nowhere to be seen. How can I get the JSON object inside the any wrapper in the schema?

Body:
var lm      = require('../server/models/records');

new lm({'any':lmr}).save();

In save() method pass callback function[optional] if you want to track error if any.

new lm({'any':lmr}).save(function(err){
   if(err) {
      console.log(err)
   }else{
      console.log('saved')
   }
});

To create the schemaless collection you will have to set strict:false which is by default true. strict option ensures values passed to your model constructor that were not specified in schema do not get saved to the db.

strict option docs


问:
Facing challenges while using relative path and mapping test data from a json file to a request
I am facing few issues while using relative path and mapping test data from a JSON file. I am having JSON POST request and a test data file in JSON format.

This is the test data I am using.

```<code>    {
  "name": "Test Data",
  "description": "Information's mainly related with Users",
  "testData": [
    {
      "Scenario1": {
        "givenName": "Joseph",
        "familyName": "George",
        "addressType": "Current",
        "lineOne": "BNRA-222, Kowdiar lane",
        "cityName": "Trivandrum",
        "countryID": "India",
        "postcode": "695006"
      }
    },
    {
      "Scenario2": {
        "givenName": "Sreenath",
        "familyName": "Bhasi",
        "addressType": "Current",
        "lineOne": "HSE-123, Karyavatom",
        "cityName": "Trivandrum",
        "countryID": "India",
        "postcode": "695552"
      }
    }
  ]
}
</code>```

This is the feature file

```<code>    Feature: Test using the Data from a JSON file

    Background:
    * def baseJsonRequest = read('../requests/jsonrequest.json')
    * def baseData = read('../data/sampledata.json')
    * def endPointURL = endPointURI + path

   Scenario: A sample scenario to test the data parametrization

    Given url endPointURL
    And request baseJsonRequest
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.givenName = baseData.testData[*].Scenario1.givenName
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.familyName = baseData.testData[*].Scenario1.familyName
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.residenceAddress.addressType = baseData.testData[*].Scenario1.addressType
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.residenceAddress.lineOne = baseData.testData[*].Scenario1.lineOne
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.residenceAddress.cityName = baseData.testData[*].Scenario1.cityName
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.residenceAddress.countryID = baseData.testData[*].Scenario1.countryID
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.residenceAddress.postcode = baseData.testData[*].Scenario1.postcode
</code>```

My Questions are:

I am not able to give relative path on both sides. The relative path is returning me a json array. For eg I cannot use $..Scenario1.givenName, which makes me write longer paths.

To include this mapping on every scenario will be practically difficult. How can we implement a parameterized solution for that. What will better way? Can I invoke the data reading using a feature file and pass the informations to another feature. If that's possible then I need to parameterize . How to do that?

Or do I need to use a java class to read the JSON file?

答:
Yes, the moment you have a wildcard in JsonPath, it returns an array. Anyway, 2 points that should help here straight away:

you can move repeating nested paths into a table-set

you can refer to a nested chunk of JSON by assigning to a variable

So this should be the way to go:

```<code>* def first = get[0] baseData.testData[*].Scenario1
* set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson
  | path                         | value             |
  | familyName                   | first.familyName  |
  | residenceAddress.addressType | first.addressType |
</code>```

I would try to not use wildcards as far as possible, for e.g.

```<code>* def first = $baseData.testData[0].Scenario1
</code>```

Hope this helps !

Body:
I am facing few issues while using relative path and mapping test data from a JSON file. I am having JSON POST request and a test data file in JSON format.

This is the test data I am using.

    {
  "name": "Test Data",
  "description": "Information's mainly related with Users",
  "testData": [
    {
      "Scenario1": {
        "givenName": "Joseph",
        "familyName": "George",
        "addressType": "Current",
        "lineOne": "BNRA-222, Kowdiar lane",
        "cityName": "Trivandrum",
        "countryID": "India",
        "postcode": "695006"
      }
    },
    {
      "Scenario2": {
        "givenName": "Sreenath",
        "familyName": "Bhasi",
        "addressType": "Current",
        "lineOne": "HSE-123, Karyavatom",
        "cityName": "Trivandrum",
        "countryID": "India",
        "postcode": "695552"
      }
    }
  ]
}

This is the feature file

    Feature: Test using the Data from a JSON file

    Background:
    * def baseJsonRequest = read('../requests/jsonrequest.json')
    * def baseData = read('../data/sampledata.json')
    * def endPointURL = endPointURI + path

   Scenario: A sample scenario to test the data parametrization

    Given url endPointURL
    And request baseJsonRequest
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.givenName = baseData.testData[*].Scenario1.givenName
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.familyName = baseData.testData[*].Scenario1.familyName
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.residenceAddress.addressType = baseData.testData[*].Scenario1.addressType
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.residenceAddress.lineOne = baseData.testData[*].Scenario1.lineOne
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.residenceAddress.cityName = baseData.testData[*].Scenario1.cityName
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.residenceAddress.countryID = baseData.testData[*].Scenario1.countryID
    * set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson.residenceAddress.postcode = baseData.testData[*].Scenario1.postcode

My Questions are:

I am not able to give relative path on both sides. The relative path is returning me a json array. For eg I cannot use $..Scenario1.givenName, which makes me write longer paths.

To include this mapping on every scenario will be practically difficult. How can we implement a parameterized solution for that. What will better way? Can I invoke the data reading using a feature file and pass the informations to another feature. If that's possible then I need to parameterize . How to do that?

Or do I need to use a java class to read the JSON file?

Body:
Yes, the moment you have a wildcard in JsonPath, it returns an array. Anyway, 2 points that should help here straight away:

you can move repeating nested paths into a table-set

you can refer to a nested chunk of JSON by assigning to a variable

So this should be the way to go:

* def first = get[0] baseData.testData[*].Scenario1
* set baseJsonRequest.autoRequest.applicants.applicant.specifiedPerson
  | path                         | value             |
  | familyName                   | first.familyName  |
  | residenceAddress.addressType | first.addressType |

I would try to not use wildcards as far as possible, for e.g.

* def first = $baseData.testData[0].Scenario1

Hope this helps !


问:
how to use filter to update row in SQLite.swift library?
I am using SQLite.swift library.

I have defined a expression:

```<code>let id = Expression<Int64>("id")
</code>```

I have a variable:

```<code>let num: Int = 1
</code>```

Then, in update statement I do filtering:

```<code>let users = Table("User")
// compiler error: // Binary operator '==' cannot be applied to operands of type 'Expression<Int64>' and 'Int'
users.filter(id == num)
</code>```

I get compiler error showing in above comment. I understand what the error is saying, but how to get rid of it? According to SQLite.swift library document, the library should be smart enough to map Int with Expression Int64.

答: You will get rid of this error by using the Int64 type (or Int) for both the id expression and the num variable.

Body:
I am using SQLite.swift library.

I have defined a expression:

let id = Expression<Int64>("id")

I have a variable:

let num: Int = 1

Then, in update statement I do filtering:

let users = Table("User")
// compiler error: // Binary operator '==' cannot be applied to operands of type 'Expression<Int64>' and 'Int'
users.filter(id == num)

I get compiler error showing in above comment. I understand what the error is saying, but how to get rid of it? According to SQLite.swift library document, the library should be smart enough to map Int with Expression Int64.