问:
My solution to check if the Check Box is checked not working?
I am trying to find if the Check Box is checked or  not. I am sure I am writing the write code but it's not working. Following is my code:

```<code>@Html.CheckBoxFor(m => m.Country, new { id = "country" })
</code>```

And my JavaScript Code:

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

  if ($("#country").is(":checked"))
  {
     alert("Working");
  }

});
</code>```

答:
perhaps try jquery on load instead of on document ready:

```<code>$(document).on({
  load: function () {
       if ($("#country").is(":checked")){
          alert("Working");
       }
  }
});
</code>```

Body:
I am trying to find if the Check Box is checked or  not. I am sure I am writing the write code but it's not working. Following is my code:

@Html.CheckBoxFor(m => m.Country, new { id = "country" })

And my JavaScript Code:

$(document).ready(function () {

  if ($("#country").is(":checked"))
  {
     alert("Working");
  }

});

Body:
perhaps try jquery on load instead of on document ready:

$(document).on({
  load: function () {
       if ($("#country").is(":checked")){
          alert("Working");
       }
  }
});


来源: stackexchange

问:
Replace a line in a text file if it matches a pattern
I'm trying to loop a specific file and see if any line contains a certain word or text and I want to replace the whole line. I am not sure how I am suppose to do it.

Right now this what I have:

```<code>@echo off
setlocal enabledelayedexpansion

FOR /F "usebackq delims=" %%G IN ("C:\folder\myfile.properties") DO (
  Set Line="transaction.sic.lettreEnvironnementBackend"
   IF %%G == %Line% (
      replace that line with new text
   )
)

pause
endlocal
</code>```

答:
Also easy in PowerShell.</p>

```<code>Get-Content .\OutputFile.txt |
    % { if ($_ -eq 'Warning message') { 'NEW WARNING' } else { $_ } }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to loop a specific file and see if any line contains a certain word or text and I want to replace the whole line. I am not sure how I am suppose to do it.

Right now this what I have:

@echo off
setlocal enabledelayedexpansion

FOR /F "usebackq delims=" %%G IN ("C:\folder\myfile.properties") DO (
  Set Line="transaction.sic.lettreEnvironnementBackend"
   IF %%G == %Line% (
      replace that line with new text
   )
)

pause
endlocal

Body:
Also easy in PowerShell.

Get-Content .\OutputFile.txt |
    % { if ($_ -eq 'Warning message') { 'NEW WARNING' } else { $_ } }


问:
How to make a child process exit abnormally after receiving SIGSEGV?
I wrote a program to intentionally let the child process to trigger SIGSEGV. However, I want the child process to terminate abnormally. Right now I use exit() in the signal handler. But exit() call will always generate a normal termination. Which function should I use to achieve that? Another question is how can I let the parent process know that the child process terminates because of SIGSEGV?</p>

```<code>extern char  etext, edata, end;
void handler() {
  pid_t pid;
  pid = getpid();

  char buf[100];
  snprintf(buf, 100, "child %d terminated by signal 11", (int)pid);
  psignal(SIGSEGV, buf);
  exit(-1);
}

int main(int argc, char **argv) {
  if (signal(SIGSEGV, handler) == SIG_ERR) {
    perror("signal error");
  }

  printf("First address beyond:\n");
  printf("    program text segment(etext)      %10p\n", &etext);
  printf("    initialized data segment(edata)  %10p\n", &edata);
  printf("    uninitialized data segment (end) %10p\n", &end);

  if (fork() == 0) {
    printf("from Child before\n");
    etext = 'a';
    printf("from Child after\n");
  } else {
    pid_t pid;
    int status;
    if ((pid == waitpid(-1, &status, 0)) >= 0) {
      printf("Handler reaped child %d\n", (int)pid);
    }
    printf("child WIFEXITED = %d, WEXITSTATUS = %d\n", WIFEXITED(status), WEXITSTATUS(status));
    if (WEXITSTATUS(status) == -3) {
      printf("Capture the exit code\n");
    }
  }
</code>```

答:
To cause the child exit by a signal, unregister a handler, unblock the signal, and raise it.

```<code>// unregister SIGSEGV handler
signal(SIGSEGV, SIG_DFL);

// unblock SIGSEGV
sigset_t mask;
sigemptyset (&mask);
sigaddset (&mask, SIGSEGV);
if (sigprocmask(SIG_UNBLOCK, &mask, &mask) < 0)
    perror ("Could not unblock");

// raise SIGSEGV
raise (SIGSEGV);
</code>```

You need to unblock if you are in a handler for that signal, for example. It is recommended to use sigaction instead of plain C standard signal, this is however not shown here.

To check in the parent process whether a child was terminated by a signal:

```<code>if (WIFSIGNALED(status)) {
    printf("child killed by signal %d\n", WTERMSIG(status));
</code>```

Body:
I wrote a program to intentionally let the child process to trigger SIGSEGV. However, I want the child process to terminate abnormally. Right now I use exit() in the signal handler. But exit() call will always generate a normal termination. Which function should I use to achieve that? Another question is how can I let the parent process know that the child process terminates because of SIGSEGV?

extern char  etext, edata, end;
void handler() {
  pid_t pid;
  pid = getpid();

  char buf[100];
  snprintf(buf, 100, "child %d terminated by signal 11", (int)pid);
  psignal(SIGSEGV, buf);
  exit(-1);
}

int main(int argc, char **argv) {
  if (signal(SIGSEGV, handler) == SIG_ERR) {
    perror("signal error");
  }

  printf("First address beyond:\n");
  printf("    program text segment(etext)      %10p\n", &etext);
  printf("    initialized data segment(edata)  %10p\n", &edata);
  printf("    uninitialized data segment (end) %10p\n", &end);

  if (fork() == 0) {
    printf("from Child before\n");
    etext = 'a';
    printf("from Child after\n");
  } else {
    pid_t pid;
    int status;
    if ((pid == waitpid(-1, &status, 0)) >= 0) {
      printf("Handler reaped child %d\n", (int)pid);
    }
    printf("child WIFEXITED = %d, WEXITSTATUS = %d\n", WIFEXITED(status), WEXITSTATUS(status));
    if (WEXITSTATUS(status) == -3) {
      printf("Capture the exit code\n");
    }
  }

Body:
To cause the child exit by a signal, unregister a handler, unblock the signal, and raise it.

// unregister SIGSEGV handler
signal(SIGSEGV, SIG_DFL);

// unblock SIGSEGV
sigset_t mask;
sigemptyset (&mask);
sigaddset (&mask, SIGSEGV);
if (sigprocmask(SIG_UNBLOCK, &mask, &mask) < 0)
    perror ("Could not unblock");

// raise SIGSEGV
raise (SIGSEGV);

You need to unblock if you are in a handler for that signal, for example. It is recommended to use sigaction instead of plain C standard signal, this is however not shown here.

To check in the parent process whether a child was terminated by a signal:

if (WIFSIGNALED(status)) {
    printf("child killed by signal %d\n", WTERMSIG(status));


问:
'Linker command failed with exit code 1' when using Google Analytics via CocoaPods
I'm trying to add Google Analytics to an iOS app written in Swift. I've followed the guide that adds the frameworks via CocoaPods and added a bridging header but I'm still getting:

```<code>Linker command failed with exit code 1
</code>```

My podfile does have use_frameworks! so I'm wondering if that has anything to do with it... there is no additional information on the Analytics site from what I can see.

EDIT:
I've noticed that after viewing the full error message the following is displayed:

```<code>ld: '/Users/simon/Programming/VenueNow/Pods/GoogleUtilities/Libraries/libGTM_NSData+zlib.a(GTMNSData+zlib.o)' does not contain bitcode.
You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. for architecture arm64
</code>```

And searching for that issue brings up that Google updated to support bit code but hadn't updated the cocoa pods framework at that time.

答: Make sure you open the .xcworkspace file not the project file from xCode Project menu when working with pods. That should solve the issue with linking.

Body:
I'm trying to add Google Analytics to an iOS app written in Swift. I've followed the guide that adds the frameworks via CocoaPods and added a bridging header but I'm still getting:

Linker command failed with exit code 1

My podfile does have use_frameworks! so I'm wondering if that has anything to do with it... there is no additional information on the Analytics site from what I can see.

EDIT:
I've noticed that after viewing the full error message the following is displayed:

ld: '/Users/simon/Programming/VenueNow/Pods/GoogleUtilities/Libraries/libGTM_NSData+zlib.a(GTMNSData+zlib.o)' does not contain bitcode.
You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. for architecture arm64

And searching for that issue brings up that Google updated to support bit code but hadn't updated the cocoa pods framework at that time.


问:
How to give jupyter cell standard input in python?
I am trying to run a program on a jupyter notebook that accepts user input, and I cannot figure out how to get it to read standard input. For example, if I run the code with shift-enter:

```<code>a = input()
print(a)
</code>```

the cell indicates it is running, but does not accept input from me. How do I get it to accept input?

答:
Use the raw_input() (for Python 2) or input() (for Python 3) methods.

Example code:

```<code>a = raw_input()
print(a)
</code>```

Example notebook:

Body:
I am trying to run a program on a jupyter notebook that accepts user input, and I cannot figure out how to get it to read standard input. For example, if I run the code with shift-enter:

a = input()
print(a)

the cell indicates it is running, but does not accept input from me. How do I get it to accept input?

Body:
Use the raw_input() (for Python 2) or input() (for Python 3) methods.

Example code:

a = raw_input()
print(a)

Example notebook:


问:
Is there an objective-c git library that would support push/pull against a remote repository?
Is there an objective-c git library that would support pushing to/pulling from a remote repository? I'm familiar with objective-git, but if I'm reading it correctly, it is for interaction with a local repository.

Ideally, the library would work on iOS and Mac OS X, and would be permissible for inclusion in app store apps.

答: Check out libgit2 -- it is a linkable c library that could probably work for you.</p>

ContentLicense: CC BY-SA 2.5


问:
CasperJS running out of memory
I'm running the following script with CasperJS and after about 1/3rd of the way through the array it starts running out of swap space and the machine becomes extremely slow.  What am i doing wrong here?

searchPages is an array of 54 numbers corresponding to a URL value for a search page.

```<code>casper.each(searchPages,function(casper,index){
    loadSearch(casper,index);
});

function loadSearch(casper,index){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 2;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var dateStart = month + "/" + day + "/" + year;
    month = currentTime.getMonth() + 3;
    var dateEnd = month + "/" + day + "/" + year;

    casper.thenOpen(url,function(){
        var myfile = "data-"+year + "-" + month + "-" + day+".html";
        this.evaluate(function(j) {
            document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
        },index);
        this.evaluate(function(start) {
            $("#leaveDate").val(start);
        },dateStart);
        this.evaluate(function(end) {
            $("#returnDate").val(end);
        },dateEnd);
        this.evaluate(function() {
            $("#OSB_btn").click();
        });

        this.waitForSelector('#destinationForPackage', function() {
            if (this.exists('#destinationForPackage')){
                var name = casper.evaluate(function() {
                    return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
                });
                if (name != "Going To"){
                    if (name == null){
                        console.log("it's null");
                    }else{
                        name = name.replace("/","_");
                        casper.capture('Captures/Searches/search_' + name + '.jpg');
                        console.log("Capturing search_" + name);
                    }
                }
            }else{
                console.log("Still doesn't exist...retry");
                loadSearch(casper,index);
            }

        },function(){
            console.log("Search page timed-out.");
        },20000);
    });
}
</code>```

And it adds about 3GB per loop.

答:
There might be a better solution to the original issue, but for a quick fix on running out of memory, try setTimeout to make the recursive call without winding up the stack...

```<code>setTimeout(() => loadSearch(casper,index), 0);
</code>```

(This idea assumes that the memory issue is the result of too much recursive depth over a long wait time).

Title: CasperJS running out of memory

Body:
I'm running the following script with CasperJS and after about 1/3rd of the way through the array it starts running out of swap space and the machine becomes extremely slow.  What am i doing wrong here?

searchPages is an array of 54 numbers corresponding to a URL value for a search page.

casper.each(searchPages,function(casper,index){
    loadSearch(casper,index);
});

function loadSearch(casper,index){
    var currentTime = new Date();
    var month = currentTime.getMonth() + 2;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    var dateStart = month + "/" + day + "/" + year;
    month = currentTime.getMonth() + 3;
    var dateEnd = month + "/" + day + "/" + year;

    casper.thenOpen(url,function(){
        var myfile = "data-"+year + "-" + month + "-" + day+".html";
        this.evaluate(function(j) {
            document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
        },index);
        this.evaluate(function(start) {
            $("#leaveDate").val(start);
        },dateStart);
        this.evaluate(function(end) {
            $("#returnDate").val(end);
        },dateEnd);
        this.evaluate(function() {
            $("#OSB_btn").click();
        });

        this.waitForSelector('#destinationForPackage', function() {
            if (this.exists('#destinationForPackage')){
                var name = casper.evaluate(function() {
                    return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
                });
                if (name != "Going To"){
                    if (name == null){
                        console.log("it's null");
                    }else{
                        name = name.replace("/","_");
                        casper.capture('Captures/Searches/search_' + name + '.jpg');
                        console.log("Capturing search_" + name);
                    }
                }
            }else{
                console.log("Still doesn't exist...retry");
                loadSearch(casper,index);
            }

        },function(){
            console.log("Search page timed-out.");
        },20000);
    });
}

And it adds about 3GB per loop.

Body:
There might be a better solution to the original issue, but for a quick fix on running out of memory, try setTimeout to make the recursive call without winding up the stack...

setTimeout(() => loadSearch(casper,index), 0);

(This idea assumes that the memory issue is the result of too much recursive depth over a long wait time).


问:
Which functions are included in executable file compiled by gcc with "-static" on? And which functions are not?
When a C program is compiled with GCC's -static option on, the final executable file would include tons of C's standard functions. For example, my whole program is like

```<code>int main(int argc, char *argv[]) {
    printf("Hello, world!\n");
    return 0;
}
</code>```

I checked the compiled executable file, and functions like, strcmp(), mktime(), realloc(), etc. are included in it, even though my program never calls them. However, some functions in stdlib.h are missing, like, rand(), system(), etc. My experiment environments are: Ubuntu 14.04 (with Linux kernel 3.13.0); GCC 4.8.2. I would like to know which C's functions would be included in the executable file when -static is turned on.

答:
Static linking means that ALL libraries that your program needs are linked and included into our executable at compiling time. In other words, your program will be larger, but it will be very independent (portable) as the executable will contain all libraries that it needs to run.

This means that with -static you will have ALL functions defined in your included libraries. You didn't put the include declarations, but just printf() already uses a large amount of libraries.

In other words, we cannot tell you which libraries are included in your program when using static, because it will vary from program to program.

Body:
When a C program is compiled with GCC's -static option on, the final executable file would include tons of C's standard functions. For example, my whole program is like

int main(int argc, char *argv[]) {
    printf("Hello, world!\n");
    return 0;
}

I checked the compiled executable file, and functions like, strcmp(), mktime(), realloc(), etc. are included in it, even though my program never calls them. However, some functions in stdlib.h are missing, like, rand(), system(), etc. My experiment environments are: Ubuntu 14.04 (with Linux kernel 3.13.0); GCC 4.8.2. I would like to know which C's functions would be included in the executable file when -static is turned on.


问:
How to union DataFrames and add only missing rows?
I have a dataframe df1, which contains below data:

```<code>**customer_id**   **product**   **Val_id**    **rule_name**
     1               A            1               rule1
     2               B            X               rule1
</code>```

I have another dataframe df2, which contains below data:

```<code>**customer_id**   **product**   **Val_id**    **rule_name**
     1               A            1               rule2
     2               B            X               rule2
     3               C            y               rule2
</code>```

rule_name values in both dataframes is always fixed

I want a new unionized dataframe df3. It should have all customers from dataframe df1 and all other customers from dataframe df2, which are not present in df1. So final df3 should look like:

```<code>**customer_id**   **product**   **Val_id**        **rule_name**
         1               A            1               rule1
         2               B            X               rule1
         3               C            y               rule2
</code>```

Can anyone please help me out to achieve this outcome. Any help will be appreciated.

答:
Given the following datasets:

```<code>val df1 = Seq(
  (1, "A", "1", "rule1"),
  (2, "B", "X", "rule1")
).toDF("customer_id", "product", "Val_id", "rule_name")

val df2 = Seq(
  (1, "A", "1", "rule2"),
  (2, "B", "X", "rule2"),
  (3, "C", "y", "rule2")
).toDF("customer_id", "product", "Val_id", "rule_name")
</code>```

And the requirement:

It should have all customers from dataframe df1 and all other customers from dataframe df2, which are not present in df1.

My first solution could be as follows:

```<code>val missingCustomers = df2.
  join(df1, Seq("customer_id"), "leftanti").
  select($"customer_id", df2("product"), df2("Val_id"), df2("rule_name"))
val all = df1.union(missingCustomers)
scala> all.show
+-----------+-------+------+---------+
|customer_id|product|Val_id|rule_name|
+-----------+-------+------+---------+
|          1|      A|     1|    rule1|
|          2|      B|     X|    rule1|
|          3|      C|     y|    rule2|
+-----------+-------+------+---------+
</code>```

Another (and perhaps slower) solution could be as follows:

```<code>// find missing ids, i.e. ids in df2 that are not in df1
// BE EXTRA CAREFUL: "Downloading" all missing ids to the driver
val missingIds = df2.
  select("customer_id").
  except(df1.select("customer_id")).
  as[Int].
  collect

// filter ids in df2 that match missing ids
val missingRows = df2.filter($"customer_id" isin (missingIds: _*))

scala> df1.union(missingRows).show
+-----------+-------+------+---------+
|customer_id|product|Val_id|rule_name|
+-----------+-------+------+---------+
|          1|      A|     1|    rule1|
|          2|      B|     X|    rule1|
|          3|      C|     y|    rule2|
+-----------+-------+------+---------+
</code>```

Body:
I have a dataframe df1, which contains below data:

**customer_id**   **product**   **Val_id**    **rule_name**
     1               A            1               rule1
     2               B            X               rule1

I have another dataframe df2, which contains below data:

**customer_id**   **product**   **Val_id**    **rule_name**
     1               A            1               rule2
     2               B            X               rule2
     3               C            y               rule2

rule_name values in both dataframes is always fixed

I want a new unionized dataframe df3. It should have all customers from dataframe df1 and all other customers from dataframe df2, which are not present in df1. So final df3 should look like:

**customer_id**   **product**   **Val_id**        **rule_name**
         1               A            1               rule1
         2               B            X               rule1
         3               C            y               rule2

Can anyone please help me out to achieve this outcome. Any help will be appreciated.

Body:
Given the following datasets:

val df1 = Seq(
  (1, "A", "1", "rule1"),
  (2, "B", "X", "rule1")
).toDF("customer_id", "product", "Val_id", "rule_name")

val df2 = Seq(
  (1, "A", "1", "rule2"),
  (2, "B", "X", "rule2"),
  (3, "C", "y", "rule2")
).toDF("customer_id", "product", "Val_id", "rule_name")

And the requirement:

It should have all customers from dataframe df1 and all other customers from dataframe df2, which are not present in df1.

My first solution could be as follows:

val missingCustomers = df2.
  join(df1, Seq("customer_id"), "leftanti").
  select($"customer_id", df2("product"), df2("Val_id"), df2("rule_name"))
val all = df1.union(missingCustomers)
scala> all.show
+-----------+-------+------+---------+
|customer_id|product|Val_id|rule_name|
+-----------+-------+------+---------+
|          1|      A|     1|    rule1|
|          2|      B|     X|    rule1|
|          3|      C|     y|    rule2|
+-----------+-------+------+---------+

Another (and perhaps slower) solution could be as follows:

// find missing ids, i.e. ids in df2 that are not in df1
// BE EXTRA CAREFUL: "Downloading" all missing ids to the driver
val missingIds = df2.
  select("customer_id").
  except(df1.select("customer_id")).
  as[Int].
  collect

// filter ids in df2 that match missing ids
val missingRows = df2.filter($"customer_id" isin (missingIds: _*))

scala> df1.union(missingRows).show
+-----------+-------+------+---------+
|customer_id|product|Val_id|rule_name|
+-----------+-------+------+---------+
|          1|      A|     1|    rule1|
|          2|      B|     X|    rule1|
|          3|      C|     y|    rule2|
+-----------+-------+------+---------+


问:
Is it suitable to pass a click event to a submit handler?
I have a <form> that I want to submit by clicking an  because a library I use builds buttons using  tags rather than <button> or <input type='submit'>.

The form's onsubmit attribute is set by PHP via Laravel.

I have a script to handle the clicks on the , which works well for the page I'm building.  The submit handler for my page doesn't currently utilize the event.  But I want to make this generic.  Therein lies the question:

Is it ok to send the "click" event generated by an anchor to a form submit handler, or does it need a "form submit" event?

Here is my code:

```<code><form method="POST" action="somewhere" onsubmit="return form_sub()" id="myForm">...</form>

<a id='saveButton' href='#'>Save</a>

<script type='text/javascript'>
$(document).ready(function() {
    $('#saveButton').click(function (e) {
        e.preventDefault();
        var $f = $('#myForm');
        if ($f.prop('onsubmit')) {
            if ($f.prop('onsubmit')(e)) { // <-- there, that event, passed to a handler that might expect a different "type" of event?
                $f.submit();
            }
        } else {
            $f.submit();
        }
    });
});
</script>
</code>```

I'm also willing to entertain ideas that I've missed something and there's an easier way do this - some way to submit the form which includes/doesn't include a call to the submit handler based on whether or not the handler exists, which may also extend to handlers installed via .addEventListener.  I realize that $(form).submit() calls event handlers installed by $(form).submit(handler) but that is not the case for this question, and I want this code to cover handlers installed both ways.

答:
try this</p>

```<code>$('#saveButton').click(function (e) {
    e.preventDefault();
    $("#myForm").submit()
});
</code>```

Body:
I have a <form> that I want to submit by clicking an  because a library I use builds buttons using  tags rather than <button> or <input type='submit'>.

The form's onsubmit attribute is set by PHP via Laravel.

I have a script to handle the clicks on the , which works well for the page I'm building.  The submit handler for my page doesn't currently utilize the event.  But I want to make this generic.  Therein lies the question:

Is it ok to send the "click" event generated by an anchor to a form submit handler, or does it need a "form submit" event?

Here is my code:

<form method="POST" action="somewhere" onsubmit="return form_sub()" id="myForm">...</form>

Save

I'm also willing to entertain ideas that I've missed something and there's an easier way do this - some way to submit the form which includes/doesn't include a call to the submit handler based on whether or not the handler exists, which may also extend to handlers installed via .addEventListener.  I realize that $(form).submit() calls event handlers installed by $(form).submit(handler) but that is not the case for this question, and I want this code to cover handlers installed both ways.

Body:
try this

$('#saveButton').click(function (e) {
    e.preventDefault();
    $("#myForm").submit()
});


问:
Efficient way of Writing algorithm
I was wondering when some one asks you to solve an algorithmic problem, is it a good way to actually start off with Hastable, Hashset or HashMap. Normally i have heard people saying you shouldn't come up with Hashes as your first answer.

So how should we go about in algorithms: In-place should be given importance or make sure time complexity is best

I'm not trying to generalise, but still some suggestions would be helpful.

Thanks

答: I think it is really situational.  If random access is a priority and you need fast access and little constraint on memory utilization and no sequential access, then Hashtable, (et al), is the choice.  </p>

Title: Efficient way of Writing algorithm


问:
Simple advice - Create a database
I'm here to ask a really simple advice to find the right system to accomplish my goal. I would like to create a simple online survey system and store the received information in spreadsheet based on some code. (So for example if Y answered X store this data in the Z spreadsheet). I'm a pretty solid C++ programmer, but I don't know how to manage a database like this. Could you help me giving me some advice? (What language to study, what online service to use...). I really don't know where to start.
Thank you very much!
Francesco.</p>

答:
is quite simple, you need to have a relationship type called N-N.
A row of table X can have multiple rows in table Y. This will save you from table Z.

A very common example of this is the like of facebook. X are the users, Y are the posts and Z saves that X liked to Y

I personally recommend a database (DBMOS) called MySql which is the most common version of the SQL standard

In the case of Facebook like the correct structure to save this data is:

http://sqlfiddle.com/#!9/60910/5

Title: Simple advice - Create a database


问:
Save Event in Google Calendar
Hi this question is related to this but this one saves the event as .ics format. I'm thinking of something like when a link is click it will open the google and save it automatically just like the screen below . So its something like the image below after I click a link it will redirect me to the google calendar page

答:
Try out this:

```<code><?php
$url = 'https://www.google.com/calendar/render?action=TEMPLATE&text={{ text }}&dates={{ start }}/{{ end }}&details={{ details }}&location={{ location }}&sf=true&output=xml';

$event = [
    'text' => 'Your Event Name',
    'start' => date('Ymd\THis\Z', strtotime('today')),
    'end' => date('Ymd\THis\Z', strtotime('tomorrow')),
    'details' => 'Click here for more details: http://example.com',
    'location' => 'Waldorf Astoria, 301 Park Ave , New York, NY 10022'
];

foreach ($event as $key => $value) {
    $url = str_replace("{{ $key }}", urlencode($value), $url);
}

echo $url;
</code>```

When you navigate to the generated URL, the page should look like on the screenshot.

Title: Save Event in Google Calendar

Body:
Try out this:

<?php
$url = 'https://www.google.com/calendar/render?action=TEMPLATE&text={{ text }}&dates={{ start }}/{{ end }}&details={{ details }}&location={{ location }}&sf=true&output=xml';

$event = [
    'text' => 'Your Event Name',
    'start' => date('Ymd\THis\Z', strtotime('today')),
    'end' => date('Ymd\THis\Z', strtotime('tomorrow')),
    'details' => 'Click here for more details: http://example.com',
    'location' => 'Waldorf Astoria, 301 Park Ave , New York, NY 10022'
];

foreach ($event as $key => $value) {
    $url = str_replace("{{ $key }}", urlencode($value), $url);
}

echo $url;

When you navigate to the generated URL, the page should look like on the screenshot.


问:
Debug python dump file in windbg
one of my python.exe (v3.5.2) process hang in remote Windows Server.
I cannot attach it from remote site so I create a full memory dump and download it back to analyze.

however, windbg doesn't have the tool like py-bt in gdb.
what I can do is downloading cpython symbol files and loading into windbg.

the question is:
how can I print the python script call stack just like "py-bt" do?

the call stack is as follow, looks like hang on HTTPS connection

```<code>0:000> k
ChildEBP RetAddr
0050dd24 74592242 ntdll!ZwWaitForSingleObject+0xc
0050dd6c 7459bdee mswsock!SockWaitForSingleObject+0x143
0050ddf8 777561e0 mswsock!WSPRecv+0x391
0050de48 614d8e76 ws2_32!recv+0x103
0050de68 614138bb _ssl!sock_read+0x26 [c:\build\cpython\externals\openssl-1.0.2h\crypto\bio\bss_sock.c @ 141]
0050de90 614bc229 _ssl!BIO_read+0x5b [c:\build\cpython\externals\openssl-1.0.2h\crypto\bio\bio_lib.c @ 210]
0050debc 614bc36e _ssl!ssl3_read_n+0x1c9 [c:\build\cpython\externals\openssl-1.0.2h\ssl\s3_pkt.c @ 255]
0050df78 614bd136 _ssl!ssl3_get_record+0x9e [c:\build\cpython\externals\openssl-1.0.2h\ssl\s3_pkt.c @ 339]
0050dfb8 614c0bb5 _ssl!ssl3_read_bytes+0x1a6 [c:\build\cpython\externals\openssl-1.0.2h\ssl\s3_pkt.c @ 1228]
0050dfdc 614c0c13 _ssl!ssl3_read_internal+0x45 [c:\build\cpython\externals\openssl-1.0.2h\ssl\s3_lib.c @ 4459]
0050dfec 61402880 _ssl!ssl3_read+0x13 [c:\build\cpython\externals\openssl-1.0.2h\ssl\s3_lib.c @ 4483]
0050e034 613ff8f7 _ssl!_ssl__SSLSocket_read_impl+0x1f0 [c:\build\cpython\modules\_ssl.c @ 1944]
0050e080 61b12ae3 _ssl!_ssl__SSLSocket_read+0x67 [c:\build\cpython\modules\clinic\_ssl.c.h @ 267]
0050e09c 61b7409f python35!PyCFunction_Call+0x113 [c:\build\cpython\objects\methodobject.c @ 109]
0050e0d0 61b712a5 python35!call_function+0x2ff [c:\build\cpython\python\ceval.c @ 4705]
0050e148 61b7301f python35!PyEval_EvalFrameEx+0x20a5 [c:\build\cpython\python\ceval.c @ 3239]
0050e194 61b74259 python35!_PyEval_EvalCodeWithName+0x75f [c:\build\cpython\python\ceval.c @ 4018]
0050e1dc 61b740f3 python35!fast_function+0x109 [c:\build\cpython\python\ceval.c @ 4813]
0050e210 61b712a5 python35!call_function+0x353 [c:\build\cpython\python\ceval.c @ 4730]
0050e288 61b7301f python35!PyEval_EvalFrameEx+0x20a5 [c:\build\cpython\python\ceval.c @ 3239]
</code>```

答:
I was surprised that nothing like CPython's gdbinit existed for WinDbg so I decided to write a debugger extension. I've uploaded the code to the PyExt repository on GitHub.

To install it:

Grab the latest zip from the releases page

Unzip pyext.dll into WinDbg's winext directory. (Make sure to use the x86 or x64 version that corresponds to the build of WinDbg you're using.)

Open a dump file in WinDbg and load the extension with: .load pyext

Add the Python symbol server to the symbol path with: .sympath+ srv*c:\symbols*http://pythonsymbols.sdcline.com/symbols/

Use !pystack to see the Python backtrace at the time the dump was captured.

Example:

```<code>0:000> .load pyext
0:000> .sympath+ srv*c:\symbols*http://pythonsymbols.sdcline.com/symbols/
Symbol search path is: srv*c:\symbols*http://msdl.microsoft.com/download/symbols;srv*c:\symbols*http://pythonsymbols.sdcline.com/symbols/

************* Symbol Path validation summary **************
Response  Time (ms)     Location
Deferred                srv*c:\symbols*http://msdl.microsoft.com/download/symbols
Deferred                srv*c:\symbols*http://pythonsymbols.sdcline.com/symbols/

0:000> ~*e!pystack
Thread 0:
    File "C:\python33\lib\threading.py", line 284, in wait
        [Globals]
    File "C:\python33\lib\threading.py", line 1028, in join
        [Globals]
    File "scripts\win32debug.py", line 153, in _launch_and_wait
        [Globals]
    File "scripts\win32debug.py", line 180, in dump_process
        [Globals]
    File "object_types.py", line 33, in <module>
        [Locals] [Globals]
</code>```

If you run into any problems or would find a new feature to be helpful, feel free to open an GitHub issue and let me know.

Title: Debug python dump file in windbg

Body:
one of my python.exe (v3.5.2) process hang in remote Windows Server.
I cannot attach it from remote site so I create a full memory dump and download it back to analyze.

however, windbg doesn't have the tool like py-bt in gdb.
what I can do is downloading cpython symbol files and loading into windbg.

the question is:
how can I print the python script call stack just like "py-bt" do?

the call stack is as follow, looks like hang on HTTPS connection

0:000> k
ChildEBP RetAddr
0050dd24 74592242 ntdll!ZwWaitForSingleObject+0xc
0050dd6c 7459bdee mswsock!SockWaitForSingleObject+0x143
0050ddf8 777561e0 mswsock!WSPRecv+0x391
0050de48 614d8e76 ws2_32!recv+0x103
0050de68 614138bb _ssl!sock_read+0x26 [c:\build\cpython\externals\openssl-1.0.2h\crypto\bio\bss_sock.c @ 141]
0050de90 614bc229 _ssl!BIO_read+0x5b [c:\build\cpython\externals\openssl-1.0.2h\crypto\bio\bio_lib.c @ 210]
0050debc 614bc36e _ssl!ssl3_read_n+0x1c9 [c:\build\cpython\externals\openssl-1.0.2h\ssl\s3_pkt.c @ 255]
0050df78 614bd136 _ssl!ssl3_get_record+0x9e [c:\build\cpython\externals\openssl-1.0.2h\ssl\s3_pkt.c @ 339]
0050dfb8 614c0bb5 _ssl!ssl3_read_bytes+0x1a6 [c:\build\cpython\externals\openssl-1.0.2h\ssl\s3_pkt.c @ 1228]
0050dfdc 614c0c13 _ssl!ssl3_read_internal+0x45 [c:\build\cpython\externals\openssl-1.0.2h\ssl\s3_lib.c @ 4459]
0050dfec 61402880 _ssl!ssl3_read+0x13 [c:\build\cpython\externals\openssl-1.0.2h\ssl\s3_lib.c @ 4483]
0050e034 613ff8f7 _ssl!_ssl__SSLSocket_read_impl+0x1f0 [c:\build\cpython\modules\_ssl.c @ 1944]
0050e080 61b12ae3 _ssl!_ssl__SSLSocket_read+0x67 [c:\build\cpython\modules\clinic\_ssl.c.h @ 267]
0050e09c 61b7409f python35!PyCFunction_Call+0x113 [c:\build\cpython\objects\methodobject.c @ 109]
0050e0d0 61b712a5 python35!call_function+0x2ff [c:\build\cpython\python\ceval.c @ 4705]
0050e148 61b7301f python35!PyEval_EvalFrameEx+0x20a5 [c:\build\cpython\python\ceval.c @ 3239]
0050e194 61b74259 python35!_PyEval_EvalCodeWithName+0x75f [c:\build\cpython\python\ceval.c @ 4018]
0050e1dc 61b740f3 python35!fast_function+0x109 [c:\build\cpython\python\ceval.c @ 4813]
0050e210 61b712a5 python35!call_function+0x353 [c:\build\cpython\python\ceval.c @ 4730]
0050e288 61b7301f python35!PyEval_EvalFrameEx+0x20a5 [c:\build\cpython\python\ceval.c @ 3239]

Body:
I was surprised that nothing like CPython's gdbinit existed for WinDbg so I decided to write a debugger extension. I've uploaded the code to the PyExt repository on GitHub.

To install it:

Grab the latest zip from the releases page

Unzip pyext.dll into WinDbg's winext directory. (Make sure to use the x86 or x64 version that corresponds to the build of WinDbg you're using.)

Open a dump file in WinDbg and load the extension with: .load pyext

Add the Python symbol server to the symbol path with: .sympath+ srv*c:\symbols*http://pythonsymbols.sdcline.com/symbols/

Use !pystack to see the Python backtrace at the time the dump was captured.

Example:

0:000> .load pyext
0:000> .sympath+ srv*c:\symbols*http://pythonsymbols.sdcline.com/symbols/
Symbol search path is: srv*c:\symbols*http://msdl.microsoft.com/download/symbols;srv*c:\symbols*http://pythonsymbols.sdcline.com/symbols/

************* Symbol Path validation summary **************
Response  Time (ms)     Location
Deferred                srv*c:\symbols*http://msdl.microsoft.com/download/symbols
Deferred                srv*c:\symbols*http://pythonsymbols.sdcline.com/symbols/

0:000> ~*e!pystack
Thread 0:
    File "C:\python33\lib\threading.py", line 284, in wait
        [Globals]
    File "C:\python33\lib\threading.py", line 1028, in join
        [Globals]
    File "scripts\win32debug.py", line 153, in _launch_and_wait
        [Globals]
    File "scripts\win32debug.py", line 180, in dump_process
        [Globals]
    File "object_types.py", line 33, in <module>
        [Locals] [Globals]

If you run into any problems or would find a new feature to be helpful, feel free to open an GitHub issue and let me know.


问:
Overwriting SQLite Database on iOS
I have a database.sqlite file, I used NSlog to know where is the file located, hopefully I got the location

and the question is, I want to overwrite that database with a button, so when ever the user click the button, it overwrites the database, but instead of overwriting, it saves the database to the following path

/Users/MYUsername/Library/Developer/CoreSimulator/Devices/4453818A-0617-479B-B98C-3FC544A24D00/data/Containers/Bundle/Application/F15404E8-AB5B-40D6-A4D5-ED42F8F7A682/Documents/Database.sqlite

which is not what I want, I want to save the database to here

/Users/MYUsername/Library/Developer/CoreSimulator/Devices/4453818A-0617-479B-B98C-3FC544A24D00/data/Containers/Data/Application/BD3E2250-DF45-480F-AB06-F8E97D3B0B37/Documents

I tried the following code:

```<code>- (IBAction)updateDatabase:(id)sender {

    NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"file URL"]];

    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];

    NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Database.sqlite"];

    [dbFile writeToFile:filePath atomically:YES];
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:filePath]) {
        NSLog(@"File Not exsists : %@",filePath);
    } else {
        NSLog(@"File exsits : %@",filePath);
    }
}
</code>```

答:
I think you'll want to use:

```<code>[[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask] firstObject] path]
</code>```

instead of

```<code>[[[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]
</code>```

See Apple's documentation:

https://developer.apple.com/reference/foundation/nsfilemanager/1407726-urlsfordirectory?language=objc

(edited)

Like so:

```<code>- (IBAction)updateDatabase:(id)sender {

    NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"file URL"]];

    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask] firstObject] path]];

    NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Database.sqlite"];

    [dbFile writeToFile:filePath atomically:YES];
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:filePath]) {
        NSLog(@"File Not exsists : %@",filePath);
    } else {
        NSLog(@"File exsits : %@",filePath);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Overwriting SQLite Database on iOS

Body:
I have a database.sqlite file, I used NSlog to know where is the file located, hopefully I got the location

and the question is, I want to overwrite that database with a button, so when ever the user click the button, it overwrites the database, but instead of overwriting, it saves the database to the following path

/Users/MYUsername/Library/Developer/CoreSimulator/Devices/4453818A-0617-479B-B98C-3FC544A24D00/data/Containers/Bundle/Application/F15404E8-AB5B-40D6-A4D5-ED42F8F7A682/Documents/Database.sqlite

which is not what I want, I want to save the database to here

/Users/MYUsername/Library/Developer/CoreSimulator/Devices/4453818A-0617-479B-B98C-3FC544A24D00/data/Containers/Data/Application/BD3E2250-DF45-480F-AB06-F8E97D3B0B37/Documents

I tried the following code:

- (IBAction)updateDatabase:(id)sender {

    NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"file URL"]];

    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];

    NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Database.sqlite"];

    [dbFile writeToFile:filePath atomically:YES];
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:filePath]) {
        NSLog(@"File Not exsists : %@",filePath);
    } else {
        NSLog(@"File exsits : %@",filePath);
    }
}

Body:
I think you'll want to use:

[[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask] firstObject] path]

instead of

[[[[NSBundle mainBundle] executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]

See Apple's documentation:

https://developer.apple.com/reference/foundation/nsfilemanager/1407726-urlsfordirectory?language=objc

(edited)

Like so:

- (IBAction)updateDatabase:(id)sender {

    NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"file URL"]];

    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask] firstObject] path]];

    NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Database.sqlite"];

    [dbFile writeToFile:filePath atomically:YES];
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:filePath]) {
        NSLog(@"File Not exsists : %@",filePath);
    } else {
        NSLog(@"File exsits : %@",filePath);
    }
}


问:
Best way to convert ArrayList of Character to String
I want to convert ArrayList of Character to String. I read similar thread like Best way to convert an ArrayList to a string but I want simpler way.

I tried this

```<code>List<Character> chars = new ArrayList<Character>();
...
Character[] charArray = (Character[]) chars.toArray();
String output = new String(charArray); // error
</code>```

But it didn't work because the new String() constructor takes only char[] as parameter. I couldn't convert chars or charArray to char[] type easily.

Aren't there any simple way? Or, do I have to iterate to make a String?

答:
A simple way is to append each character to a string:

```<code>String myString = "";
for (Character c : charList) {
    myString += c;
}
</code>```

This iterates through the list to append each character.

Result:

Output of charList is: [a, b, c].
Output of myString is: abc.

Body:
I want to convert ArrayList of Character to String. I read similar thread like Best way to convert an ArrayList to a string but I want simpler way.

I tried this

List<Character> chars = new ArrayList<Character>();
...
Character[] charArray = (Character[]) chars.toArray();
String output = new String(charArray); // error

But it didn't work because the new String() constructor takes only char[] as parameter. I couldn't convert chars or charArray to char[] type easily.

Aren't there any simple way? Or, do I have to iterate to make a String?

Body:
A simple way is to append each character to a string:

String myString = "";
for (Character c : charList) {
    myString += c;
}

This iterates through the list to append each character.

Result:

Output of charList is: [a, b, c].
Output of myString is: abc.


答:
The best you can hope for is a generalized answer for your generalized question.

It depends.

The reason there are many different algorithms is because there is not always 1 algorithm that is the best.    And many algorithms aim to solve different problems from each other.  Some algorithms it makes no sense to even talk about hash tables.

If someone asks me to solve an algorithmic problem though, I will probably try to use something that is built in to the language I'm using before designing my own algorithm.  The reason is because I value my time.   If I find later that the code is not efficient enough, then I can look for a better way to do it.

Title: Efficient way of Writing algorithm

Body:
I was wondering when some one asks you to solve an algorithmic problem, is it a good way to actually start off with Hastable, Hashset or HashMap. Normally i have heard people saying you shouldn't come up with Hashes as your first answer.

So how should we go about in algorithms: In-place should be given importance or make sure time complexity is best

I'm not trying to generalise, but still some suggestions would be helpful.

Thanks


问:
How to make an element transparent so its background is 2 layers behind?
I have an animated background (background), a div on it with a background-color (A), and another div in it (B). I want B to be transparent so through it we see the animated background, but B is in A, which already have a background-color.

Any ideas to achieve this?

答:
So it sounds like you have three layers: Background, Div A and Div B. Div A + B need to be transparent to be able to see the animated background. Have you tried using the CSS property "opacity"?

```<code>div {
    opacity: .3; /* Anything betweet 0 - 1 */
    filter: alpha(opacity=30); /* For IE8 and earlier */
}
</code>```

Check this out for more information about opacity https://www.w3schools.com/css/css_image_transparency.asp

Body:
So it sounds like you have three layers: Background, Div A and Div B. Div A + B need to be transparent to be able to see the animated background. Have you tried using the CSS property "opacity"?

div {
    opacity: .3; /* Anything betweet 0 - 1 */
    filter: alpha(opacity=30); /* For IE8 and earlier */
}

Check this out for more information about opacity https://www.w3schools.com/css/css_image_transparency.asp


问:
Detecting if user is playing music from another app
My game has an in-game soundtrack and I would like to pause the music if the user is playing music of their own from a media app on Android or iOS.

Is there a way to do this that is efficient enough to run in an update() function?

Thanks in advance!

答:
You have to implements the callback onAudioFocusChange() that your app will receive when some other app acquires or abandons audio focus.

```<code>AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
                         // Use the music stream.
                         AudioManager.STREAM_MUSIC,
                         // Request permanent focus.
                         AudioManager.AUDIOFOCUS_GAIN);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    // Start playback
}
</code>```

And the callback itself:

```<code>AudioManager.OnAudioFocusChangeListener afChangeListener = new AudioManager.OnAudioFocusChangeListener() {

public void onAudioFocusChange(int focusChange) {
  if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
    // Permanent loss of audio focus
    // Pause playback immediately
  } else if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT) {
    // Pause playback
  } else if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
    // Lower the volume, keep playing
  } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
    // Your app has been granted audio focus again
    // Raise volume to normal, restart playback if necessary
  }
}
</code>```

Take a look on this official guide: Handling Changes in Audio Output

Body:
You have to implements the callback onAudioFocusChange() that your app will receive when some other app acquires or abandons audio focus.

AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(afChangeListener,
                         // Use the music stream.
                         AudioManager.STREAM_MUSIC,
                         // Request permanent focus.
                         AudioManager.AUDIOFOCUS_GAIN);

if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    // Start playback
}

And the callback itself:

AudioManager.OnAudioFocusChangeListener afChangeListener = new AudioManager.OnAudioFocusChangeListener() {

public void onAudioFocusChange(int focusChange) {
  if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
    // Permanent loss of audio focus
    // Pause playback immediately
  } else if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT) {
    // Pause playback
  } else if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
    // Lower the volume, keep playing
  } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
    // Your app has been granted audio focus again
    // Raise volume to normal, restart playback if necessary
  }
}

Take a look on this official guide: Handling Changes in Audio Output


问:
Retrieving div "value" to javascript
So, im trying to code a simple sliding puzzle and got really stuck.
I've got a 3x3 sqare with diffrent "values"

Now, im trying to move the number to the blank space and vice versa.

So my question is how can i, in the easiest possible manner, change my 'test' text to the value of the clicked div ?

All answers and tips are truely appreciated

-Karlsen

EDIT :

Added full code, its a bit more understanding now i think :

          var counter = 0;
     var lastClickedDiv;

     function show(tag, alt1, alt2, alt3, alt4) {
       if (alt1 && document.getElementById(alt1).innerHTML == '') {
         document.getElementById(alt1).innerHTML = 'test';
         tag.innerHTML = '';
       }

       if (alt2 && document.getElementById(alt2).innerHTML == '') {
         document.getElementById(alt2).innerHTML = 'test1';
         tag.innerHTML = '';
       }

       if (alt3 && document.getElementById(alt3).innerHTML == '') {
         document.getElementById(alt3).innerHTML = 'test2';
         tag.innerHTML = '';
       }

       if (alt4 && document.getElementById(alt4).innerHTML == '') {
         document.getElementById(alt4).innerHTML = 'test3';
         tag.innerHTML = '';
       }
     }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>  div.container {
   display: flex;
   height: 28vh;
  }
   div.number {
    color: black;
    background-color: rgb(140,0,0);
    margin: 10px;
    border: 10px solid black;
    display: flex;
    flex: 1;
    font-size: 500%;
    text-align: center;
    flex-direction: column;
    justify-content: center;
   }</code>```

<!DOCTYPE html>

 Sliding Puzzle

8

5

4

6

7

2

1

3

```

答:
First you have error in the javascript at line 4,

```<code>document.getElementById(alt1).innerHTML. = 'test';
</code>```

there cannot be "." after innerHTML.

May be that is the problem and you not able to run your JS

Title: Retrieving div "value" to javascript

Body:
So, im trying to code a simple sliding puzzle and got really stuck.
I've got a 3x3 sqare with diffrent "values"

Now, im trying to move the number to the blank space and vice versa.

So my question is how can i, in the easiest possible manner, change my 'test' text to the value of the clicked div ?

All answers and tips are truely appreciated

-Karlsen

EDIT :

Added full code, its a bit more understanding now i think :

          var counter = 0;
     var lastClickedDiv;

     function show(tag, alt1, alt2, alt3, alt4) {
       if (alt1 && document.getElementById(alt1).innerHTML == '') {
         document.getElementById(alt1).innerHTML = 'test';
         tag.innerHTML = '';
       }

       if (alt2 && document.getElementById(alt2).innerHTML == '') {
         document.getElementById(alt2).innerHTML = 'test1';
         tag.innerHTML = '';
       }

       if (alt3 && document.getElementById(alt3).innerHTML == '') {
         document.getElementById(alt3).innerHTML = 'test2';
         tag.innerHTML = '';
       }

       if (alt4 && document.getElementById(alt4).innerHTML == '') {
         document.getElementById(alt4).innerHTML = 'test3';
         tag.innerHTML = '';
       }
     }

  div.container {
   display: flex;
   height: 28vh;
  }
   div.number {
    color: black;
    background-color: rgb(140,0,0);
    margin: 10px;
    border: 10px solid black;
    display: flex;
    flex: 1;
    font-size: 500%;
    text-align: center;
    flex-direction: column;
    justify-content: center;
   }

<!DOCTYPE html>

 Sliding Puzzle

8

5

4

6

7

2

1

3

Body:
First you have error in the javascript at line 4,

document.getElementById(alt1).innerHTML. = 'test';

there cannot be "." after innerHTML.

May be that is the problem and you not able to run your JS


Title: add first entry into next line and shift data after comma & underscore from previous line to the next line

Body:
Data after underscore and comma will go to next line and data from beginning to pipe add before them.

sample data:

1.2.4.0/24|24151_24409_24406
37.99.128.0/19|47794_47795,48695
37.142.128.0/17|21450,65555

expected result should be:

1.2.4.0/24|24151
1.2.4.0/24|24409
1.2.4.0/24|24406
37.99.128.0/19|47794
37.99.128.0/19|47795
37.99.128.0/19|48695
37.142.128.0/17|21450
37.142.128.0/17|65555

Is there a way to do it?

Body:
With awk:

awk -F '[|,_]' '{for (i=2; i<=NF; i++) print $1 "|" $i}' file

Output:

1.2.4.0/24|24151
1.2.4.0/24|24409
1.2.4.0/24|24406
37.99.128.0/19|47794
37.99.128.0/19|47795
37.99.128.0/19|48695
37.142.128.0/17|21450
37.142.128.0/17|65555

The variable NF is set to the total number of fields in the input record.


问:
Unit test: running programmatically a code that runs only at a real application instance
I am developing a plugin for PhpStorm, and in some point, it try to getContainingClass() from visited method. This method should return null when the class name is absent.

Just to make easier to explain, my visitPhpMethod() is like that:

```<code>final PhpClass methodClass = method.getContainingClass();

if (methodClass == null) {
    return null;
}
</code>```

My problem is justly to make the code-coverage of return null programmatically (from unit test) to proof that it is not a dead code. From a real instance of PhpStorm running my plugin I can reach this code when I just remove the class name like that:

Original code, that not access the return null:

```<code>class ThisIsMyClass { function x(){} }
</code>```

Modified code without the class name, that access return null:

```<code>class               { function x(){} }
</code>```

But when I run the modified code from unit test, it give that:

```<code>class<error descr="Expected: class name"> </error>{ function x(){} }
</code>```

And with that, my visitPhpMethod() is not triggered (while in real PhpStorm application it does). In this way, is impossible to coverage this part of code (but I like to do).

My best attempt: instead I relying on testHighlight() for that, I inputted with the functional code (that have the class name), then programatically I removed the class name (then the "expected class name" error don't happen anymore). Finally I run the visitPhpMethod() programmatically.

Unfortunatelly, the getContainingClass() instead of return null (that is what I expect to do), it just returns a PhpClass instance that don't have a name (and it should not works to me).

The code from this attempt could be seen here.

I tried to post the same problem on Intellij Community too, but without luck.

答:
Okay, I found my issue.

On reality, the problem is not on getContaingClass(). It really doesn't returns null when called from visitPhpMethod(). I found my problem on another method that try to getNameIdentifier() from the containing class, in this case, it is really absent and I just try to return it from a @NotNull method.

Body:
I am developing a plugin for PhpStorm, and in some point, it try to getContainingClass() from visited method. This method should return null when the class name is absent.

Just to make easier to explain, my visitPhpMethod() is like that:

final PhpClass methodClass = method.getContainingClass();

if (methodClass == null) {
    return null;
}

My problem is justly to make the code-coverage of return null programmatically (from unit test) to proof that it is not a dead code. From a real instance of PhpStorm running my plugin I can reach this code when I just remove the class name like that:

Original code, that not access the return null:

class ThisIsMyClass { function x(){} }

Modified code without the class name, that access return null:

class               { function x(){} }

But when I run the modified code from unit test, it give that:

class<error descr="Expected: class name"> </error>{ function x(){} }

And with that, my visitPhpMethod() is not triggered (while in real PhpStorm application it does). In this way, is impossible to coverage this part of code (but I like to do).

My best attempt: instead I relying on testHighlight() for that, I inputted with the functional code (that have the class name), then programatically I removed the class name (then the "expected class name" error don't happen anymore). Finally I run the visitPhpMethod() programmatically.

Unfortunatelly, the getContainingClass() instead of return null (that is what I expect to do), it just returns a PhpClass instance that don't have a name (and it should not works to me).

The code from this attempt could be seen here.

I tried to post the same problem on Intellij Community too, but without luck.


问:
Display decimal point with NSString stringWithFormat in Objective C
I'm a complete novice to objective C/iPad development, but I am trying to build a simple four function calculator on the iPad.

My current biggest difficulty is simply displaying a . when the decimal button is pressed. Here is what happens when a button (like two) is pressed.

```<code>-(IBAction)inTwo:(id)sender {
    display = display*10+2;
    [resultfield setText:[NSString stringWithFormat:@"%f",display]];
}
</code>```

Trying to just do

```<code>display = display*10+.
</code>```

Is obviously not working. Any way to append a period to the end of display?

Thanks

答:
If you just want to display it you can do this:

```<code>[resultField setText:[NSString stringWithFormat:@"%f%@", display, @"."]];
</code>```

Then, in your other methods, have them check to see if there is a decimal point before adding:

```<code>-(IBAction)inTwo:(id)sender {
    if([resultField.text rangeOfString:@"."] == NSNotFound) {
        display = display*10+2;
        [resultfield setText:[NSString stringWithFormat:@"%f",display]];
    }
    else {
        display += 2/10 * (resultField.length - [resultField.text rangeOfString:@"."] +1)
        [resultfield setText:[NSString stringWithFormat:@"%f",display]];
    }
}
</code>```

What you are doing here is first checking to see if there is a decimal point to see if you should be adding the digit to the ones place, or to the right of the decimal. If there is a decimal point, we add the digit divided by ten times the difference between the location of the decimal and the length of the whole string.

Body:
I'm a complete novice to objective C/iPad development, but I am trying to build a simple four function calculator on the iPad.

My current biggest difficulty is simply displaying a . when the decimal button is pressed. Here is what happens when a button (like two) is pressed.

-(IBAction)inTwo:(id)sender {
    display = display*10+2;
    [resultfield setText:[NSString stringWithFormat:@"%f",display]];
}

Trying to just do

display = display*10+.

Is obviously not working. Any way to append a period to the end of display?

Thanks

Body:
If you just want to display it you can do this:

[resultField setText:[NSString stringWithFormat:@"%f%@", display, @"."]];

Then, in your other methods, have them check to see if there is a decimal point before adding:

-(IBAction)inTwo:(id)sender {
    if([resultField.text rangeOfString:@"."] == NSNotFound) {
        display = display*10+2;
        [resultfield setText:[NSString stringWithFormat:@"%f",display]];
    }
    else {
        display += 2/10 * (resultField.length - [resultField.text rangeOfString:@"."] +1)
        [resultfield setText:[NSString stringWithFormat:@"%f",display]];
    }
}

What you are doing here is first checking to see if there is a decimal point to see if you should be adding the digit to the ones place, or to the right of the decimal. If there is a decimal point, we add the digit divided by ten times the difference between the location of the decimal and the length of the whole string.


问:
How to enable button onClick functions and java script in wordpress post
I am trying to add the below codes to Wordpress, however, wordpress always gives me error 404 whenever I try to update. I'm new to coding. So would appreciate some help.

```<code><!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>

</head>
<body>

  Code 1: <input type="text" id="code1">
  <br>
  <p id="code1ans"></p>

  Code 2: <input type="text" id="code2">
  <br>
  <p id="code2ans"></p>

  Code 3: <input type="text" id="code3">
  <br>
  <p id="code3ans"></p>

  Code 4: <input type="text" id="code4">
  <br>
  <p id="code4ans"></p>

  <button onclick="myFunction()">Submit</button>

    <script>
      function myFunction() {
          var code1 = document.getElementById("code1").value;
          var code2 = document.getElementById("code2").value;
          var code3 = document.getElementById("code3").value;
          var code4 = document.getElementById("code4").value;
          document.getElementById("code1ans").innerHTML = code1;
          document.getElementById("code2ans").innerHTML = code2;
          document.getElementById("code3ans").innerHTML = code3;
         document.getElementById("code4ans").innerHTML = code4;
      }
    </script>

  </body>
</html>
</code>```

答:
Wordpress uses the template hierarchy, so I'm guessing you want this code to execute on a specific page or perhaps you want it to run on every page load?

Wordpress uses a system of hooks called filters and actions to run things at certain times. One of them is https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts which allows you to load scripts. Here you can also add code run the script only on specific pages. You should add your script here based on the documentation.

Your question doesn't appear to specify where you are putting your code.

Body:
I am trying to add the below codes to Wordpress, however, wordpress always gives me error 404 whenever I try to update. I'm new to coding. So would appreciate some help.

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title></title>

  Code 1: <input type="text" id="code1">

  Code 2: <input type="text" id="code2">

  Code 3: <input type="text" id="code3">

  Code 4: <input type="text" id="code4">

  <button onclick="myFunction()">Submit</button>


问:
Summation of an array of numbers in javascript
Here, I want to take inputs from users. Split and store them into array. Then show the summation of array numbers.

 summation experiment

```<code><!-- for taking inputs -->
<input id="seriesInput" type="text" placeholder="please use space">
<!-- for submitting inputs -->
<input id="submiting" onclick="seriesFunction()" value="Submit" type="button">
<!-- for placing results -->
<div> Summation is <span id="sum"></span> </div>
<script type="text/javascript">

function seriesFunction()
{
    value = document.getElementById("seriesInput").value;
    // splitting string in an array
    value_arr = value.split(" ");
    alert(value_arr);
    // calling reduce method for summation
    var sum = value_arr.reduce(get_sum,0);
    // assigning result
    document.getElementById("sum").innerHTML =sum;
alert(sum);

    function get_sum(total, currentVal) {
total += currentVal;
return total;
}
}
</script>
</code>```

答:
You need to modify the code to:

```<code>function get_sum(total, currentVal) {
                total += +currentVal;
                return total;
}
</code>```

Notice + in front of currentVal. That will convert string to number not just int. So the benefit is that if you input three values  like 1.1 1.2 1.3, you would get the sum as 6.6.
Earlier without this you were doing string concatenation instead of sum that you intended to do.

function seriesFunction() {
  value = document.getElementById("seriesInput").value;
  // splitting string in an array
  value_arr = value.split(" ");
  alert(value_arr);
  // calling reduce method for summation
  var sum = value_arr.reduce(get_sum, 0);
  // assigning result
  document.getElementById("sum").innerHTML = sum;
  alert(sum);

  function get_sum(total, currentVal) {
    total += +currentVal;
    return total;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="seriesInput" type="text" placeholder="please use space">
<!-- for submitting inputs -->
<input id="submiting" onclick="seriesFunction()" value="Submit" type="button">
<!-- for placing results -->
<div> Summation is <span id="sum"></span> </div></code>```

Body:
Here, I want to take inputs from users. Split and store them into array. Then show the summation of array numbers.

 summation experiment

<input id="seriesInput" type="text" placeholder="please use space">

<input id="submiting" onclick="seriesFunction()" value="Submit" type="button">

 Summation is

Body:
You need to modify the code to:

function get_sum(total, currentVal) {
                total += +currentVal;
                return total;
}

Notice + in front of currentVal. That will convert string to number not just int. So the benefit is that if you input three values  like 1.1 1.2 1.3, you would get the sum as 6.6.
Earlier without this you were doing string concatenation instead of sum that you intended to do.

function seriesFunction() {
  value = document.getElementById("seriesInput").value;
  // splitting string in an array
  value_arr = value.split(" ");
  alert(value_arr);
  // calling reduce method for summation
  var sum = value_arr.reduce(get_sum, 0);
  // assigning result
  document.getElementById("sum").innerHTML = sum;
  alert(sum);

  function get_sum(total, currentVal) {
    total += +currentVal;
    return total;
  }
}

<input id="seriesInput" type="text" placeholder="please use space">
<!-- for submitting inputs -->
<input id="submiting" onclick="seriesFunction()" value="Submit" type="button">
<!-- for placing results -->
<div> Summation is <span id="sum"></span> </div>


问:
How do I find the time complexity (Big O) of while loop?
Code 1

```<code>int i = 0;
int j = 0;
while(i < n){
     while(j < n){
        printf("{%d,%d}",arr[i],arr[j]);
        j++;
    }
    i++;
    j = 0;
    printf("\n");
}
</code>```

Code 2

```<code>int result = 0;
int i = 0;
while (i < n / 2){
    result += arr[i];
    i += 1;
    while (i >= n / 2 && i < n){
        result += arr[i];
        i += 1;
    }
}
printf("%d\n", result);
</code>```

I only know how to find time complexity with for loops, but I am uncertain about while loop.
It would be greatly appreciated if someone could help me find the total running time of each code.

答:
The first code sample is pretty much a classis for loop. Its complexity is O(n^2). This is because the inner loop has a complexity O(n) and it is run n times.

The second one is a bit more difficult, untill you see that is equivalent to a non nested loop (ignoring the complexity of the checks)

```<code>int result = 0;
int i = 0;
while (i < n){
    result += arr[i];
    i += 1;
}
printf("%d\n", result);
</code>```

meaning its complexity is O(n)

The best approach to calculating time complexity is trying to actually understand how the algorithm works and counting the operations. In the second example, the inner loop never runs untill the outer loop is at its last iteration. And since they even execute the same code, the whole thing can be reduced to one loop.

Another good example is this:

```<code>for(i=0;i<n;i++){
    for(j=i;j<n;i++){
        //do something
    }
}
</code>```

Let's count the operations: 1 + 2 + 3 + 4 + ... + n. This comes down to n*n/2 leading to O(n^2)

Body:
Code 1

int i = 0;
int j = 0;
while(i < n){
     while(j < n){
        printf("{%d,%d}",arr[i],arr[j]);
        j++;
    }
    i++;
    j = 0;
    printf("\n");
}

Code 2

int result = 0;
int i = 0;
while (i < n / 2){
    result += arr[i];
    i += 1;
    while (i >= n / 2 && i < n){
        result += arr[i];
        i += 1;
    }
}
printf("%d\n", result);

I only know how to find time complexity with for loops, but I am uncertain about while loop.
It would be greatly appreciated if someone could help me find the total running time of each code.

Body:
The first code sample is pretty much a classis for loop. Its complexity is O(n^2). This is because the inner loop has a complexity O(n) and it is run n times.

The second one is a bit more difficult, untill you see that is equivalent to a non nested loop (ignoring the complexity of the checks)

int result = 0;
int i = 0;
while (i < n){
    result += arr[i];
    i += 1;
}
printf("%d\n", result);

meaning its complexity is O(n)

The best approach to calculating time complexity is trying to actually understand how the algorithm works and counting the operations. In the second example, the inner loop never runs untill the outer loop is at its last iteration. And since they even execute the same code, the whole thing can be reduced to one loop.

Another good example is this:

for(i=0;i<n;i++){
    for(j=i;j<n;i++){
        //do something
    }
}

Let's count the operations: 1 + 2 + 3 + 4 + ... + n. This comes down to n*n/2 leading to O(n^2)


问:
XML file contents to text area and PHP: Remove character replacement
I have a xml file which I'm retrieving its data with this PHP function file_get_contents().

My intention is to provide an editor for this XML file, so the XML contents string are loaded in a textarea, then edited (if needed), and saved with file_put_contents()

The string that PHP returns contains replacement characters (the �). How can I remove this or find a better solution to this?

My xml file looks like this:

```<code><?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <RECORD>
  <FIELD ID="1" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  <FIELD ID="2" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  <FIELD ID="3" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  <FIELD ID="4" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
</code>```

and it's retrieved as this:

```<code><�?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <RECORD>
  <FIELD ID="1" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  <FIELD ID="2" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  <FIELD ID="3" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  <FIELD ID="4" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
</code>```

答:
I found a solution with this function (http://php.net/manual/pt_BR/function.iconv.php):

```<code>iconv("UTF-16", "UTF-8", $content);
</code>```

Where $content is the string with the data return from my XML file.
Since the encoding was UTF-16, just translated that to UTF-8, and now it works fine.

Thank you.

** IMPORTANT **

Just remember to convert it back to the original encoding, when saving its contents:

```<code>iconv('UTF-8', 'UTF-16', $content);
</code>```

Otherwise you'll end up reading chinese in your application, next time you load it! :)

Body:
I have a xml file which I'm retrieving its data with this PHP function file_get_contents().

My intention is to provide an editor for this XML file, so the XML contents string are loaded in a textarea, then edited (if needed), and saved with file_put_contents()

The string that PHP returns contains replacement characters (the �). How can I remove this or find a better solution to this?

My xml file looks like this:

<?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <RECORD>
  <FIELD ID="1" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  <FIELD ID="2" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  <FIELD ID="3" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  <FIELD ID="4" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>

and it's retrieved as this:

<�?xml version="1.0"?>
<BCPFORMAT xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <RECORD>
  <FIELD ID="1" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  <FIELD ID="2" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  <FIELD ID="3" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>
  <FIELD ID="4" xsi:type="CharTerm" TERMINATOR="," MAX_LENGTH="100" COLLATION="SQL_Latin1_General_CP1_CI_AS"/>

Body:
I found a solution with this function (http://php.net/manual/pt_BR/function.iconv.php):

iconv("UTF-16", "UTF-8", $content);

Where $content is the string with the data return from my XML file.
Since the encoding was UTF-16, just translated that to UTF-8, and now it works fine.

Thank you.

** IMPORTANT **

Just remember to convert it back to the original encoding, when saving its contents:

iconv('UTF-8', 'UTF-16', $content);

Otherwise you'll end up reading chinese in your application, next time you load it! :)


问:
Loading YouTube Number of People Watching Live into Span using jQuery Updating every 5 seconds
I want to take the information found here:

https://www.youtube.com/live_stats?v=uSajGtd5SnY

Which returns a number that is displayed on the page.

I want to take that and put it into a span with the id of "live-watching".

I want this to be automatically updated every 5 seconds.

Dont really know where to even begin because I'm new to jQuery. I've been looking but I can't seem to piece the things i want together.

Heres a code pen for the set up, where X should be updated every 5 seconds with the number of people watching live:

https://codepen.io/JDSWebService/pen/yXLjdK

```<code> <p>Number of People Watching <span id="live-watching">X</span></p>
</code>```

Is there an easier way to do this? I'm very unfamiliar with working with jQuery, and YouTube videos.

答:
You can start an ajax call, then update the number on success and repeat after 5 seconds ( with jquery) :

```<code>(function reload(){
$.ajax({
  url:"https://www.youtube.com/live_stats?v=uSajGtd5SnY",
  success:function(data){
     $("#live-watching").html(data);
     setTimeout(reload,5000);
  }
});
})();
</code>```

Note that ajax calls to another domain may be blocked. In this case, you need to use a youtube api instead...

Body:
I want to take the information found here:

https://www.youtube.com/live_stats?v=uSajGtd5SnY

Which returns a number that is displayed on the page.

I want to take that and put it into a span with the id of "live-watching".

I want this to be automatically updated every 5 seconds.

Dont really know where to even begin because I'm new to jQuery. I've been looking but I can't seem to piece the things i want together.

Heres a code pen for the set up, where X should be updated every 5 seconds with the number of people watching live:

https://codepen.io/JDSWebService/pen/yXLjdK

Number of People Watching X

Is there an easier way to do this? I'm very unfamiliar with working with jQuery, and YouTube videos.

Body:
You can start an ajax call, then update the number on success and repeat after 5 seconds ( with jquery) :

(function reload(){
$.ajax({
  url:"https://www.youtube.com/live_stats?v=uSajGtd5SnY",
  success:function(data){
     $("#live-watching").html(data);
     setTimeout(reload,5000);
  }
});
})();

Note that ajax calls to another domain may be blocked. In this case, you need to use a youtube api instead...


问:
Pyspark map from RDD of strings to RDD of list of doubles
I believe in the context of programming in spark / python that this is a reasonably basic operation. I have a text file that looks as such:

```<code>mydata.txt
12  34  2.3  15
23  11  1.5  9
33  18  4.5  99
</code>```

and then I use the following code to read in the textfile:

```<code>data = sc.textFile("mydata.txt")
</code>```

and this reads in the file as an RDD of strings. However I want to separate the values and convert them all into floats. So I change the line above to this:

```<code>data = sc.textFile("matrix1.txt").map(lambda line: line.split(' '))
</code>```

which successfully splits the data by spaces. However I am struggling to come up with the map function that then converts to floats. something along the lines of:

```<code>.map(lambda line: float(line))
</code>```

but this didn't work. Any help appreciated!
Thanks!

EDIT - please assume I do not know the number of columns of the data. so something along the lines of .map(lambda line: float(line[0]), float(line[1]), float(line[2]), float(line[3])) is not particularly helpful.

答:
Nevermind, got it.</p>

```<code>.map(lambda line: [float(x) for x in line])
</code>```

Body:
I believe in the context of programming in spark / python that this is a reasonably basic operation. I have a text file that looks as such:

mydata.txt
12  34  2.3  15
23  11  1.5  9
33  18  4.5  99

and then I use the following code to read in the textfile:

data = sc.textFile("mydata.txt")

and this reads in the file as an RDD of strings. However I want to separate the values and convert them all into floats. So I change the line above to this:

data = sc.textFile("matrix1.txt").map(lambda line: line.split(' '))

which successfully splits the data by spaces. However I am struggling to come up with the map function that then converts to floats. something along the lines of:

.map(lambda line: float(line))

but this didn't work. Any help appreciated!
Thanks!

EDIT - please assume I do not know the number of columns of the data. so something along the lines of .map(lambda line: float(line[0]), float(line[1]), float(line[2]), float(line[3])) is not particularly helpful.

Body:
Nevermind, got it.

.map(lambda line: [float(x) for x in line])


问:
Which functions are included in executable file compiled by gcc with "-static" on? And which functions are not?
When a C program is compiled with GCC's -static option on, the final executable file would include tons of C's standard functions. For example, my whole program is like

```<code>int main(int argc, char *argv[]) {
    printf("Hello, world!\n");
    return 0;
}
</code>```

I checked the compiled executable file, and functions like, strcmp(), mktime(), realloc(), etc. are included in it, even though my program never calls them. However, some functions in stdlib.h are missing, like, rand(), system(), etc. My experiment environments are: Ubuntu 14.04 (with Linux kernel 3.13.0); GCC 4.8.2. I would like to know which C's functions would be included in the executable file when -static is turned on.

答:
Static libs are archives of object files.
Linking them, only brings in those archive members that resolve undefined
symbol references, and this works recursively (e.g., you may call a(), which calls b(), which calls c()). If each archive member defined exactly one symbol (e.g., a.o only defines a(), etc.) , you'd get only those symbols that were needed (recursively). Practically, an archive member may also define other symbols (e.g., a.o may define a() and variable), so you'll get symbols that resolve undefined symbol references along with the symbols that shared the same object file with the needed symbol definition.

Body:
When a C program is compiled with GCC's -static option on, the final executable file would include tons of C's standard functions. For example, my whole program is like

int main(int argc, char *argv[]) {
    printf("Hello, world!\n");
    return 0;
}

I checked the compiled executable file, and functions like, strcmp(), mktime(), realloc(), etc. are included in it, even though my program never calls them. However, some functions in stdlib.h are missing, like, rand(), system(), etc. My experiment environments are: Ubuntu 14.04 (with Linux kernel 3.13.0); GCC 4.8.2. I would like to know which C's functions would be included in the executable file when -static is turned on.


问:
Exception comes while migrating my spring based maven project from JBoss EAP 6 to tomcat 8.0
```<code>Cannot resolve reference to bean 'transactionManager' while setting bean
property 'transactionManager'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'transactionManager' defined in ServletContext resource [/config/core-spring-config.xml]: Invocation of init method failed; nested
    java.lang.IllegalStateException: No JTA UserTransaction available - specify either 'userTransaction' or 'userTransactionName' or 'transactionManager' or 'transactionManagerName'
</code>```

What things I've done for set up?

I have created the jndi resource. Initially the dataSourceBean initialisation error was coming, I resolved it by creating that jndi resource. The application.properties has also been correctly mapped and it is loading the same props. Now the above error is coming.

Assumption:
 1. The same app.war is working fine on jboss instance on my system. My tomcat is also on the same system. Few other apps like microservices are running well on the same tomcat but my main app is not.
2. I tried to run a sql query from init method of one of the beans, so sql connection/jdbctemplate is also fine.
I think the root cause should be some default spring jar related/path expression related.

答: Tomcat is only a servlet container unlike Jboss that is a full fledged Java EE stack implementation and is a application server. so you may need changes when migrating from tomcat to Jboss if you have used Java EE features like JMS, JTA and So on. in this case you should determine Transaction manager in order to let Tomcat know what kind of transaction manager it should use. </p>

Body:
Cannot resolve reference to bean 'transactionManager' while setting bean
property 'transactionManager'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'transactionManager' defined in ServletContext resource [/config/core-spring-config.xml]: Invocation of init method failed; nested
    java.lang.IllegalStateException: No JTA UserTransaction available - specify either 'userTransaction' or 'userTransactionName' or 'transactionManager' or 'transactionManagerName'

What things I've done for set up?

I have created the jndi resource. Initially the dataSourceBean initialisation error was coming, I resolved it by creating that jndi resource. The application.properties has also been correctly mapped and it is loading the same props. Now the above error is coming.

Assumption:
 1. The same app.war is working fine on jboss instance on my system. My tomcat is also on the same system. Few other apps like microservices are running well on the same tomcat but my main app is not.
2. I tried to run a sql query from init method of one of the beans, so sql connection/jdbctemplate is also fine.
I think the root cause should be some default spring jar related/path expression related.


问:
Cucumber gives Sqlite3 error
I just started using Cucumber, but I am running into a weird error:

```<code>SQLite3::SQLException: no such table: venues: SELECT "venues".* FROM "venues" (ActiveRecord::StatementInvalid)
./app/controllers/venues_controller.rb:5:in `index'
<internal:prelude>:10:in `synchronize'
./features/step_definitions/web_steps.rb:18:in `/^(?:|I )am on (.+)$/'
features/most_popular_bands.feature:8:in `Given I am on the home page'
</code>```

This comes from the Given step, where I mention the home page, which has a list of items from the venues tables. I wonder why Cucumber cannot find that table.

Btw, I am not running it with autotest. I am using bundle exec cucumber.

答: It looks like you're executing your features on old version of the database. Try rake db:test:clone  to copy the scheme of your development database to the test database.

Title: Cucumber gives Sqlite3 error

Body:
I just started using Cucumber, but I am running into a weird error:

SQLite3::SQLException: no such table: venues: SELECT "venues".* FROM "venues" (ActiveRecord::StatementInvalid)
./app/controllers/venues_controller.rb:5:in `index'
<internal:prelude>:10:in `synchronize'
./features/step_definitions/web_steps.rb:18:in `/^(?:|I )am on (.+)$/'
features/most_popular_bands.feature:8:in `Given I am on the home page'

This comes from the Given step, where I mention the home page, which has a list of items from the venues tables. I wonder why Cucumber cannot find that table.

Btw, I am not running it with autotest. I am using bundle exec cucumber.


问:
Regular expression for a string literal in flex/lex
I'm experimenting to learn flex and would like to match string literals. My code currently looks like:

```<code>"\""([^\n\"\\]*(\\[.\n])*)*"\""        {/*matches string-literal*/;}
</code>```

I've been struggling with variations for an hour or so and can't get it working the way it should. I'm essentially hoping to match a string literal that can't contain a new-line (unless it's escaped) and supports escaped characters.

I am probably just writing a poor regular expression or one incompatible with flex. Please advise!

答:
An answer that arrives late but which can be useful for the next one who will need it: </p>

```<code>\"(([^\"]|\\\")*[^\\])?\"
</code>```

Body:
I'm experimenting to learn flex and would like to match string literals. My code currently looks like:

"\""([^\n\"\\]*(\\[.\n])*)*"\""        {/*matches string-literal*/;}

I've been struggling with variations for an hour or so and can't get it working the way it should. I'm essentially hoping to match a string literal that can't contain a new-line (unless it's escaped) and supports escaped characters.

I am probably just writing a poor regular expression or one incompatible with flex. Please advise!

Body:
An answer that arrives late but which can be useful for the next one who will need it:

\"(([^\"]|\\\")*[^\\])?\"


问:
Ruby - share logger instance among module/classes
Working on a little Ruby script that goes out to the web and crawls various services. I've got a module with several classes inside:

```<code>module Crawler
  class Runner
  class Options
  class Engine
end
</code>```

I want to share one logger among all those of those classes. Normally I'd just put this in a constant in the module and reference it like so:

```<code>Crawler::LOGGER.info("Hello, world")
</code>```

The problem is that I can't create my logger instance until I know where the output is going. You start the crawler via command line and at that point you can tell it you want to run in development (log output goes to STDOUT) or production (log output goes to a file, crawler.log):

```<code>crawler --environment=production
</code>```

I have a class Options that parses the options passed in through the command line. Only at that point do I know how to instantiate the logger with the correct output location.

So, my question is: how/where to I put my logger object so that all my classes have access to it?

I could pass my logger instance to each new() call for every class instance I create, but I know there has to be a better, Rubyish way to do it. I'm imagining some weird class variable on the module that shared with class << self or some other magic. :)

A little more detail: Runner starts everything by passing the command line options to the Options class and gets back an object with a couple of instance variables:

```<code>module Crawler
  class Runner
    def initialize(argv)
      @options = Options.new(argv)
      # feels like logger initialization should go here
      # @options.log_output => STDOUT or string (log file name)
      # @options.log_level => Logger::DEBUG or Logger::INFO
      @engine = Engine.new()
    end
    def run
      @engine.go
    end
  end
end

runner = Runner.new(ARGV)
runner.run
</code>```

I need the code in Engine to be able to access the logger object (along with a couple more classes that are initialized inside Engine). Help!

All of this could be avoided if you could just dynamically change the output location of an already-instantiated Logger (similar to how you change the log level). I'd instantiate it to STDOUT and then change over to a file if I'm in production.  I did see a suggestion somewhere about changing Ruby's $stdout global variable, which would redirect output somewhere other than STDOUT, but this seems pretty hacky.

Thanks!

答:
Inspired by this thread I created the easy_logging gem.

It combines all the features discussed such as:

Adds logging functionality anywhere with one, short,
self-descriptive command

Logger works in both class and instance methods

Logger is specific to class and contains class name

Installation:

```<code>gem install 'easy_logging
</code>```

Usage:

```<code>require 'easy_logging'

class YourClass
  include EasyLogging

  def do_something
    # ...
    logger.info 'something happened'
  end
end

class YourOtherClass
  include EasyLogging

  def self.do_something
    # ...
    logger.info 'something happened'
  end
end

YourClass.new.do_something
YourOtherClass.do_something
</code>```

Output

```<code>I, [2017-06-03T21:59:25.160686 #5900]  INFO -- YourClass: something happened
I, [2017-06-03T21:59:25.160686 #5900]  INFO -- YourOtherClass: something happened
</code>```

More details on GitHub.

Body:
Working on a little Ruby script that goes out to the web and crawls various services. I've got a module with several classes inside:

module Crawler
  class Runner
  class Options
  class Engine
end

I want to share one logger among all those of those classes. Normally I'd just put this in a constant in the module and reference it like so:

Crawler::LOGGER.info("Hello, world")

The problem is that I can't create my logger instance until I know where the output is going. You start the crawler via command line and at that point you can tell it you want to run in development (log output goes to STDOUT) or production (log output goes to a file, crawler.log):

crawler --environment=production

I have a class Options that parses the options passed in through the command line. Only at that point do I know how to instantiate the logger with the correct output location.

So, my question is: how/where to I put my logger object so that all my classes have access to it?

I could pass my logger instance to each new() call for every class instance I create, but I know there has to be a better, Rubyish way to do it. I'm imagining some weird class variable on the module that shared with class << self or some other magic. :)

A little more detail: Runner starts everything by passing the command line options to the Options class and gets back an object with a couple of instance variables:

module Crawler
  class Runner
    def initialize(argv)
      @options = Options.new(argv)
      # feels like logger initialization should go here
      # @options.log_output => STDOUT or string (log file name)
      # @options.log_level => Logger::DEBUG or Logger::INFO
      @engine = Engine.new()
    end
    def run
      @engine.go
    end
  end
end

runner = Runner.new(ARGV)
runner.run

I need the code in Engine to be able to access the logger object (along with a couple more classes that are initialized inside Engine). Help!

All of this could be avoided if you could just dynamically change the output location of an already-instantiated Logger (similar to how you change the log level). I'd instantiate it to STDOUT and then change over to a file if I'm in production.  I did see a suggestion somewhere about changing Ruby's $stdout global variable, which would redirect output somewhere other than STDOUT, but this seems pretty hacky.

Thanks!

Body:
Inspired by this thread I created the easy_logging gem.

It combines all the features discussed such as:

Adds logging functionality anywhere with one, short,
self-descriptive command

Logger works in both class and instance methods

Logger is specific to class and contains class name

Installation:

gem install 'easy_logging

Usage:

require 'easy_logging'

class YourClass
  include EasyLogging

  def do_something
    # ...
    logger.info 'something happened'
  end
end

class YourOtherClass
  include EasyLogging

  def self.do_something
    # ...
    logger.info 'something happened'
  end
end

YourClass.new.do_something
YourOtherClass.do_something

Output

I, [2017-06-03T21:59:25.160686 #5900]  INFO -- YourClass: something happened
I, [2017-06-03T21:59:25.160686 #5900]  INFO -- YourOtherClass: something happened

More details on GitHub.