问:
What is a most efficient way to implement Gantt Chart in Angular js application?
I am working on a Hotel Management application in which I am using Angular Gantt chart to manage rates of rooms. My hotel has large number of rooms and each room has different rate plans, so to manage all that in Angular Gantt chart is not possible. (loading large amount of data in a chart at once hangs the system.)

So, in order to manage that, I added lazy loading in it and loads only records for 10 days but it didn't solve my problem. So I again breaks the data and added a dropdown in Chart and displayed records only for one room. This time it worked fine as I loaded small amount of data in a chart but it is not what I am looking for.

So I want to know about the most efficient way to display maximum data in a chart or some other way to achieve the same.

Thanks in advance.

答:
Varun,

I would like to recommend our RadiantQ jQuery Gantt Package. It's natively built to support a large number of "tasks" in the timeline. You don't even have to bother lazy load, our UI is virtualized and so can handle large data.

If you could give us an idea on how your data looks like, we can even put together a Proof Of Concept.


来源: stackexchange

答:
I'm very helpful in optimizing svg files, drawn in vector editors,

 a utility made by Peter Collingridge - SVG Editor

The interface is intuitive, almost immediately you start working.

The results are good:

Reduces the size of files almost several times

Removes all the service information left after Inkscape

There is a choice of the number of decimal digits

ContentLicense: CC BY-SA 3.0

Title: Trim Decimal Places from Numbers in a Text Editor

Body:
I have a set of SVG definition exported from Inkspace and as anyone who has done this themselves will know the resulting definition often contains far more accuracy that is actually justified. For example for a 32 x32 icon definition shown below, Inkspace has generated 6 (or more!) decimal places of accuracy per pixel. Now I know that means it will scale but in my case I would rather save space in my app which requires input of hundreds of such icon definitions.

<svg width="32" height="32"><path d="M 14.576172 5.453125 L 13.78125 8.8222656 L 12.464844 9.3691406 L 9.5625 7.5898438 L 7.5898438 9.5351562 L 9.3691406 12.576172 L 8.8222656 13.78125 L 5.4785156 14.630859 L 5.4785156 17.369141 L 8.8496094 18.246094 L 9.3691406 19.507812 L 7.5625 22.464844 L 9.5351562 24.410156 L 12.548828 22.658203 L 13.808594 23.177734 L 14.603516 26.494141 L 17.396484 26.521484 L 18.191406 23.177734 L 19.505859 22.658203 L 22.410156 24.410156 L 24.355469 22.410156 L 22.658203 19.451172 L 23.150391 18.191406 L 26.492188 17.369141 L 26.492188 14.630859 L 23.123047 13.726562 L 22.630859 12.521484 L 24.410156 9.5351562 L 22.410156 7.5898438 L 19.451172 9.3417969 L 18.246094 8.8222656 L 17.396484 5.453125 L 14.576172 5.453125 z M 15.984375 12.082031 A 3.9078221 3.9078221 0 0 1 19.892578 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 19.896484 A 3.9078221 3.9078221 0 0 1 12.078125 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 12.082031 Z" fill="#f9f9f9" /></svg>

So my question is how can I trim the definitions using a text editor to say 2 decimal places.

I have found that by using TextWrangler with the following grep search and replace string

(\.[0-9][0-9])([0-9][0-9][0-9][0-9][0-9][0-9])
\1

that I can search for all 6 decimal places strings and replace them with 2 decimal places. Then I can change the search and replace to

(\.[0-9][0-9])([0-9][0-9][0-9][0-9][0-9])
\1

and then to

(\.[0-9][0-9])([0-9][0-9][0-9][0-9])
\1

and finally to

(\.[0-9][0-9])([0-9][0-9][0-9])
\1

and this works.

However if someone with slightly (or a lot) more brain pixels than me, could show me how to do all of the above with just one search and replace operation, I would be very happy.


问:
MongoDB cannot insert document because it exceeds 180 levels of nesting
I'm new to MongoDB and I would really appreciate your help.

I'm trying to do a map/reduce, using MongoDB's java driver 3.4.2.

I have a collection collectionA which has documents such as this one:

```<code>{
    "_id" : ObjectId("5a29a6757c5def07307a4b6f"),
    "someProperty1" : "454545",
    "someProperty2" : "1234",
    "myArray" : [
        "1",
        "2",
        "3",
    ]
}
</code>```

I would like to get all the combinations of myArray: [1,2] [1,3] [2,1] [2,3] [3,1] [3,2]

The longest myArray has 20 elements.

I've tried using the following:

```<code>db.collectionA.mapReduce(
    function () {
        var elem= this;
        this.myArray.forEach(function (parent) {
            elem.myArray.forEach(function (child) {
                if (parent !== child)
                    emit(parent, child);
                });
        });
    },

    function (key, values) {
        return {
            result: Array.from(new Set(values))
        };
    },
    {
        query: {
            $where: "this.myArray.length > 1"
        },
        out: "collectionB"
    });
</code>```

It worked fine when I tested it with a small amount of data. Problem is now I have 21.5 million documents in the source collection, and it's throwing this exception.

Exception in thread "pool-3-thread-5"
  com.mongodb.MongoCommandException: Command failed with error 15:
  'cannot insert document because it exceeds 180 levels of nesting' on
  server localhost:27017. The full response is { "ok" : 0.0, "errmsg" :
  "cannot insert document because it exceeds 180 levels of nesting",
  "code" : 15, "codeName" : "Overflow" }    at
  com.mongodb.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:115)
    at
  com.mongodb.connection.CommandProtocol.execute(CommandProtocol.java:114)
    at

What am I doing wrong? what would be the correct way to approach this?

Thanks in advance.

答:
Well, it turned out I had a misconception about the way the reduce function works. It had been working fine with small amounts of data by mere luck (or back luck, really). I changed the map function to emit emit(parent, {result:[child]});
And the reduce function to:

```<code>function (key, values) {
    resultSet = new Set();
    values.forEach(function (partialResult) {
        partialResult.result.forEach(function (elem) {
            resultSet.add(elem);
        });
    });
    return {
        result: Array.from(resultSet)
    };
}
</code>```

works like a charm.

Body:
I'm new to MongoDB and I would really appreciate your help.

I'm trying to do a map/reduce, using MongoDB's java driver 3.4.2.

I have a collection collectionA which has documents such as this one:

{
    "_id" : ObjectId("5a29a6757c5def07307a4b6f"),
    "someProperty1" : "454545",
    "someProperty2" : "1234",
    "myArray" : [
        "1",
        "2",
        "3",
    ]
}

I would like to get all the combinations of myArray: [1,2] [1,3] [2,1] [2,3] [3,1] [3,2]

The longest myArray has 20 elements.

I've tried using the following:

db.collectionA.mapReduce(
    function () {
        var elem= this;
        this.myArray.forEach(function (parent) {
            elem.myArray.forEach(function (child) {
                if (parent !== child)
                    emit(parent, child);
                });
        });
    },

    function (key, values) {
        return {
            result: Array.from(new Set(values))
        };
    },
    {
        query: {
            $where: "this.myArray.length > 1"
        },
        out: "collectionB"
    });

It worked fine when I tested it with a small amount of data. Problem is now I have 21.5 million documents in the source collection, and it's throwing this exception.

Exception in thread "pool-3-thread-5"
  com.mongodb.MongoCommandException: Command failed with error 15:
  'cannot insert document because it exceeds 180 levels of nesting' on
  server localhost:27017. The full response is { "ok" : 0.0, "errmsg" :
  "cannot insert document because it exceeds 180 levels of nesting",
  "code" : 15, "codeName" : "Overflow" }    at
  com.mongodb.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:115)
    at
  com.mongodb.connection.CommandProtocol.execute(CommandProtocol.java:114)
    at

What am I doing wrong? what would be the correct way to approach this?

Thanks in advance.

Body:
Well, it turned out I had a misconception about the way the reduce function works. It had been working fine with small amounts of data by mere luck (or back luck, really). I changed the map function to emit emit(parent, {result:[child]});
And the reduce function to:

function (key, values) {
    resultSet = new Set();
    values.forEach(function (partialResult) {
        partialResult.result.forEach(function (elem) {
            resultSet.add(elem);
        });
    });
    return {
        result: Array.from(resultSet)
    };
}

works like a charm.


问:
How can you mock a DOM window event?
In my ng4 app, I have a service that exposes an Observable over the window focus event. How would you go about testing this (I am using Jasmine, but that's not very important)?

constructor(@Inject('Window') private window: Window) {

    this.window.onfocus = () => {
        this.onFocusSubject.next();
    };
}

// how can I test that the onFocus Observable is triggered
// when window.onfocus is fired?
public onFocus(): Observable<any> {
    return this.onFocusSubject.asObservable();
}
```

My approach is to mock the window object and to trigger fire the onfocus event, but am unsure of how to trigger the event...

答:
Just mock the service using a BehaviorSubject and trigger a next call to ensure your listeners are invoked.

Like this:

const serviceStub = {
  windowEvent: new BehaviorSubject(null);
}

// in your test:

it('should trigger an event listener: ', () => {
  const service = componentInstance.injector.get(Service);
  service.windowEvent.next(new FocusEvent('focus'));
  // write your test logic here
})```

Title: How can you mock a DOM window event?

Body:
In my ng4 app, I have a service that exposes an Observable over the window focus event. How would you go about testing this (I am using Jasmine, but that's not very important)?

constructor(@Inject('Window') private window: Window) {

    this.window.onfocus = () => {
        this.onFocusSubject.next();
    };
}

// how can I test that the onFocus Observable is triggered
// when window.onfocus is fired?
public onFocus(): Observable<any> {
    return this.onFocusSubject.asObservable();
}

My approach is to mock the window object and to trigger fire the onfocus event, but am unsure of how to trigger the event...


问:
Navigating to Commonly/Recently Used Dirs, in Terminal (Unix/OS X)
Would it be possible to save certain locations that I've used recently/commonly (like /folder/folder/folder/) so that I don't have to manually navigate through each dir between my current and destination dir?

Sort of like alt-tab, but for paths.  I'm on OS X, but perhaps this can be done using basic Unix skills?

Thanks!

答: One way that works in most shells (but is slightly different for different shells) is the directory stack.  You can use pushd to push a directory, popd to pop the top directory from the stack, and dirs to move directories around and switch to directories in the middle of the stack.  I just checked, and the man page for pushd on Mac OS X is useless; use the man page for your shell (likely bash) and search for pushd, etc. there.

ContentLicense: CC BY-SA 2.5


问:
$_GET not picking up the variable
What am i doing wrong. The variable will not get picked up. I have tried to echo it out just to check but the echo was blank. What did i do wrong?

```<code>if($result->num_rows){
        while($row = $result->fetch_array(MYSQLI_ASSOC)){
            //Displays them
            echo '<h4> <a href="request.php?='.$row['account_id'].'">' . $row['fname'] . '&nbsp' . $row['lname'] . '</a> <h4/>' .'<br/>';
            }
</code>```

request.php below

```<code>$requestedId = $_GET['account_id'];
$userId = $_SESSION['user_id'];
</code>```

Thats the portions of the code i need help with. The account id is passed through the URL.

答:
In the while loop you need to put the name account_id in it, not just the value</p>

```<code>echo '<h4> <a href="request.php?account_id='.$row['account_id'].'">' .
     $row['fname'] . '&nbsp' . $row['lname'] . '</a> <h4/>' .'<br/>';
</code>```

Title: $_GET not picking up the variable

Body:
What am i doing wrong. The variable will not get picked up. I have tried to echo it out just to check but the echo was blank. What did i do wrong?

if($result->num_rows){
        while($row = $result->fetch_array(MYSQLI_ASSOC)){
            //Displays them
            echo '
 ' . $row['fname'] . '&nbsp' . $row['lname'] . '
' .'
';
            }

request.php below

$requestedId = $_GET['account_id'];
$userId = $_SESSION['user_id'];

Thats the portions of the code i need help with. The account id is passed through the URL.

Body:
In the while loop you need to put the name account_id in it, not just the value

echo '<h4> <a href="request.php?account_id='.$row['account_id'].'">' .
     $row['fname'] . '&nbsp' . $row['lname'] . '</a> <h4/>' .'<br/>';


问:
How to repeat a function on every Ajax request
So I have this transform code as an example but basically I have 3 buttons on my page that load different html files. When I click the first button the function in the .ajaxSend works properly. After I click the next button to load a different html file the .ajaxSend function doesn't work but the html file loads fine.

Am i missing something or is there a way to basically set the function so that it resets everytime I load an html file.

```<code>$('a').click(function(){
  var page = $(this).attr('href');
  $("#content").hide().load(page).fadeIn('500');

  return false;
});

$( document ).ajaxSend(function() {
  setInterval(function () {
       $('body').css('transform', 'rotate(360deg)');
   },300);
});
</code>```

答:
If I understand correctly, when you click the first button, it applies style='transform:rotate(360deg)' on the body.

When you click the second button, it's simply going to leave style='transform:rotate(360deg)' on body, so it's not going to rotate it again. What I would suggest is, in the ajaxSend function first removing the css from body before adding the css style.

I hope i was clear. Let me know if it works.

Body:
So I have this transform code as an example but basically I have 3 buttons on my page that load different html files. When I click the first button the function in the .ajaxSend works properly. After I click the next button to load a different html file the .ajaxSend function doesn't work but the html file loads fine.

Am i missing something or is there a way to basically set the function so that it resets everytime I load an html file.

$('a').click(function(){
  var page = $(this).attr('href');
  $("#content").hide().load(page).fadeIn('500');

  return false;
});

$( document ).ajaxSend(function() {
  setInterval(function () {
       $('body').css('transform', 'rotate(360deg)');
   },300);
});


问:
How to do if statement with jquery
I'm trying to do an if statement in jQuery, but it doesn't really work.

```<code>$("#button2").hide()
var score = 0;

//some code with button that is adding the score with score++ (working)

if(score >= 100) {
    $("#button2").show()
}
</code>```

The if statement is not properly working.

```<code>        $("#grandmabutton1").hide()
        $("#farmbutton1").hide()
        $("#minebutton1").hide()
        $("#factorybutton1").hide()

        $(function(){
            var score = 0;

            $("#p1").html("Your score is: " + score)

            $("#headbutton1").mousedown(function(){
                score++

                $("#p1").html("Your score is: " + score)
            })

            if(score >= 100) {
                $("#grandmabutton1").show()
            }

        })
</code>```

答:
You should write:

```<code>$("#headbutton1").mousedown(function(){
    score++
    if(score >= 100) {
        $("#grandmabutton1").show()
    }
    $("#p1").html("Your score is: " + score)
})
</code>```

What you want to do here is to evaluate the condition for each mousedown event. By including the if clause inside the function, you will be checking if the score is greater or equal than 100 each time the event is triggered, however, by putting it outside, it will be only executed once in runtime.

Also, according to MDN:

```<code>if (condition)
   statement1
[else
   statement2]
</code>```

If statements are a part of JavaScript built in syntax, not modified in any way by jQuery, fyi. What jQuery does is to extend JS functionality, but it does not change the syntax of the language. So there are no jQuery if clauses, there are JS if clauses, and yours is properly formatted.

To avoid these kind of beginner confusions, I recommend you to use a code editor that proof-checks your code to see if there are syntax errors, so when you debug you know that the problem is in the workflow design and not in the syntax.

Title: How to do if statement with jquery

Body:
I'm trying to do an if statement in jQuery, but it doesn't really work.

$("#button2").hide()
var score = 0;

//some code with button that is adding the score with score++ (working)

if(score >= 100) {
    $("#button2").show()
}

The if statement is not properly working.

        $("#grandmabutton1").hide()
        $("#farmbutton1").hide()
        $("#minebutton1").hide()
        $("#factorybutton1").hide()

        $(function(){
            var score = 0;

            $("#p1").html("Your score is: " + score)

            $("#headbutton1").mousedown(function(){
                score++

                $("#p1").html("Your score is: " + score)
            })

            if(score >= 100) {
                $("#grandmabutton1").show()
            }

        })

Body:
You should write:

$("#headbutton1").mousedown(function(){
    score++
    if(score >= 100) {
        $("#grandmabutton1").show()
    }
    $("#p1").html("Your score is: " + score)
})

What you want to do here is to evaluate the condition for each mousedown event. By including the if clause inside the function, you will be checking if the score is greater or equal than 100 each time the event is triggered, however, by putting it outside, it will be only executed once in runtime.

Also, according to MDN:

if (condition)
   statement1
[else
   statement2]

If statements are a part of JavaScript built in syntax, not modified in any way by jQuery, fyi. What jQuery does is to extend JS functionality, but it does not change the syntax of the language. So there are no jQuery if clauses, there are JS if clauses, and yours is properly formatted.

To avoid these kind of beginner confusions, I recommend you to use a code editor that proof-checks your code to see if there are syntax errors, so when you debug you know that the problem is in the workflow design and not in the syntax.


问:
RoR STI Single of each type for every parent model instance
Im trying to validate the count of models that inherit from Parent model and keep them unique.

So i have

```<code>User has_many :parents
Parent belongs_to :user
</code>```

Also I'm using single table inheritance for this , so:

```<code>rails g model Type1Parent --parent=Parent
</code>```

overall i have 3 types , so Type1Parent,Type2Parent,Type3Parent.

Every user must have only one of each type, so for example

```<code>type1parent = user.type1parents.new
type1parent.save #=> OK!
</code>```

but if i try do this again

```<code>type1parent = user.type1parents.new
type1parent.save #=> Error: User already has a type1parents
</code>```

but also be able to create a type2parent for the same user.

So , how can i validate the single existence of each type for every user?

答:
Add this scoped uniqueness validation to your Parent model:

validates :type, uniqueness: { scope: :user_id }

Also as suggested by @MrYoshiji add a unique index on type, user_id on the parents table

Body:
Im trying to validate the count of models that inherit from Parent model and keep them unique.

So i have

User has_many :parents
Parent belongs_to :user

Also I'm using single table inheritance for this , so:

rails g model Type1Parent --parent=Parent

overall i have 3 types , so Type1Parent,Type2Parent,Type3Parent.

Every user must have only one of each type, so for example

type1parent = user.type1parents.new
type1parent.save #=> OK!

but if i try do this again

type1parent = user.type1parents.new
type1parent.save #=> Error: User already has a type1parents

but also be able to create a type2parent for the same user.

So , how can i validate the single existence of each type for every user?


问:
How to display scroll bar onto a html table
I am writing a page where I need an html table to maintain a set size. I need the headers at the top of the table to stay there at all times but I also need the body of the table to scroll no matter how many rows are added to the table.

I want it to look like method 2 in this url: http://www.cssplay.co.uk/menu/tablescroll.html

I have tried doing this but no scrollbar appears:

tbody {
  height: 80em;
  overflow: scroll;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border=1 id="qandatbl" align="center">
  <tr>
    <th class="col1">Question No</th>
    <th class="col2">Option Type</th>
    <th class="col1">Duration</th>
  </tr>

  <tbody>
    <tr>
      <td class='qid'></td>
      <td class="options"></td>
      <td class="duration"></td>
    </tr>
  </tbody>
</table></code>```

答:
If you get to the point where all the mentioned solutions don't work (as it got for me), do this:

Create two tables. One for the header and another for the body

Give the two tables different parent containers/divs

Style the second table's div to allow vertical scroll of its contents.

Like this, in your HTML

```<code><div class="table-header-class">
    <table>
       <thead>
          <tr>
            <th>Ava</th>
            <th>Alexis</th>
            <th>Mcclure</th>
          </tr>
       </thead>
    </table>
</div>
<div class="table-content-class">
   <table>
       <tbody>
          <tr>
            <td>I am the boss</td>
            <td>No, da-da is not the boss!</td>
            <td>Alexis, I am the boss, right?</td>
          </tr>
       </tbody>
    </table>
</div>
</code>```

Then style the second table's parent to allow vertical scroll, in your CSS

```<code>    .table-content-class {
        overflow-y: scroll;    // use auto; or scroll; to allow vertical scrolling;
        overflow-x: hidden;    // disable horizontal scroll
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am writing a page where I need an html table to maintain a set size. I need the headers at the top of the table to stay there at all times but I also need the body of the table to scroll no matter how many rows are added to the table.

I want it to look like method 2 in this url: http://www.cssplay.co.uk/menu/tablescroll.html

I have tried doing this but no scrollbar appears:

tbody {
  height: 80em;
  overflow: scroll;
}

    Question No
    Option Type
    Duration

Body:
If you get to the point where all the mentioned solutions don't work (as it got for me), do this:

Create two tables. One for the header and another for the body

Give the two tables different parent containers/divs

Style the second table's div to allow vertical scroll of its contents.

Like this, in your HTML

<div class="table-header-class">
    <table>
       <thead>
          <tr>
            <th>Ava</th>
            <th>Alexis</th>
            <th>Mcclure</th>
          </tr>
       </thead>
    </table>
</div>
<div class="table-content-class">
   <table>
       <tbody>
          <tr>
            <td>I am the boss</td>
            <td>No, da-da is not the boss!</td>
            <td>Alexis, I am the boss, right?</td>
          </tr>
       </tbody>
    </table>
</div>

Then style the second table's parent to allow vertical scroll, in your CSS

    .table-content-class {
        overflow-y: scroll;    // use auto; or scroll; to allow vertical scrolling;
        overflow-x: hidden;    // disable horizontal scroll
    }


问:
The current AWS identity is not a role for sagemaker?
I am getting error when i call get_execution_role() from sagemaker in python.
I have attached the error for the same.

I have added the SagemakerFullAccess Policy to role and user both.

答:
thanks for trying out SageMaker!

The exception you are seeing already suggests the reason. The credentials you are using are not a role credentials but most likely a user.
The format of 'user' credentials will look like:

'arn:aws:iam::accid:user/name' as opposed to a role:
'arn:aws:iam::accid:role/name'

Hope this helps!


问:
Segmentation fault (core dumped) in parallel computing
I am trying to code an AMPI to sum a 1d array in parallel. However, I am getting a segmentation fault (core dumped). </p>

<p>I tried to fix my function so many times but I could not find where the error is or how to fix it. </p>

```<code>/* File: mpi_sum.c
* Compile as: mpicc -g -Wall -std=c99 -o mpi_sum mpi_sum.c -lm
* Run as:  mpirun -n 40  ./mpi_sum
* Description: An MPI solution to sum a 1D array. */

int main(int argc, char *argv[]) {
  int myID, numProcs;  // myID for the index to know when should the cpu start and stop calculate
                       //numPro numper of cpu you need to do the calculation
  double localSum;    // this for one operation on one cpu
  double parallelSum; // this for collecting the values of localsum
  int length = 10000000; // this for how many num
  double Fact = 1 ;
  int i; // this for for loop
  clock_t clockStart, clockEnd;   // timer
  srand(5); // Initialize MPI
  MPI_Init(NULL, NULL); //Initialize MPI
  MPI_Comm_size(MPI_COMM_WORLD, &numProcs); // Get size
  MPI_Comm_rank(MPI_COMM_WORLD, &myID); // Get rank
  localSum = 0.0;                               // the value for eash cpu is 0
  int A = (length / numProcs)*((long)myID);     // this is to make each cpu work on his area
  int B = (length / numProcs)*((long)myID + 1); // this is to make each cpu work on his area

  A ++;                                         // add 1 to go to next num
  B ++;

  clockStart = clock();                     // start the timer to see how much time it take
  for (i = A; i < B; i++)
  {
          Fact = (1 / myID - 1/numProcs) / (1 - 1/numProcs);
          localSum += Fact ;
  }

  MPI_Reduce(&localSum, &parallelSum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);

  clockEnd = clock();

  if (myID == 0)
  {
          printf("Time to sum %d floats with MPI in parallel %3.5f seconds\n", length, (clockEnd - clockStart) / (float)CLOCKS_PER_SEC);
          printf("The parallel sum: %f\n", parallelSum + 1);
  }

    MPI_Finalize();
  return 0;
}
</code>```

答:
When I ran your code, my numProcs came up as 1 and the program crashed with

```<code>*** Process received signal ***
Signal: Floating point exception (8)
Signal code: Integer divide-by-zero (1)
Failing at address: 0x400af9
[ 0] /lib/x86_64-linux-gnu/libpthread.so.0(+0x10330)[0x7f8bb13d2330]
[ 1] ./mpi_sum[0x400af9]
[ 2] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0x7f8bb101af45]
[ 3] ./mpi_sum[0x400919]
*** End of error message ***
Floating point exception (core dumped)
</code>```

on the line

```<code>Fact = (1 / myID - 1/numProcs) / (1 - 1/numProcs);
</code>```

because we had a zero in the denominator.

Since you are getting a different error, may I suggest putting in a bunch of:

```<code>printf("%d\n", __LINE__); fflush(stdout);
</code>```

statements to get an idea where it is crashing?

Body:
I am trying to code an AMPI to sum a 1d array in parallel. However, I am getting a segmentation fault (core dumped).

I tried to fix my function so many times but I could not find where the error is or how to fix it.

/* File: mpi_sum.c
* Compile as: mpicc -g -Wall -std=c99 -o mpi_sum mpi_sum.c -lm
* Run as:  mpirun -n 40  ./mpi_sum
* Description: An MPI solution to sum a 1D array. */

int main(int argc, char *argv[]) {
  int myID, numProcs;  // myID for the index to know when should the cpu start and stop calculate
                       //numPro numper of cpu you need to do the calculation
  double localSum;    // this for one operation on one cpu
  double parallelSum; // this for collecting the values of localsum
  int length = 10000000; // this for how many num
  double Fact = 1 ;
  int i; // this for for loop
  clock_t clockStart, clockEnd;   // timer
  srand(5); // Initialize MPI
  MPI_Init(NULL, NULL); //Initialize MPI
  MPI_Comm_size(MPI_COMM_WORLD, &numProcs); // Get size
  MPI_Comm_rank(MPI_COMM_WORLD, &myID); // Get rank
  localSum = 0.0;                               // the value for eash cpu is 0
  int A = (length / numProcs)*((long)myID);     // this is to make each cpu work on his area
  int B = (length / numProcs)*((long)myID + 1); // this is to make each cpu work on his area

  A ++;                                         // add 1 to go to next num
  B ++;

  clockStart = clock();                     // start the timer to see how much time it take
  for (i = A; i < B; i++)
  {
          Fact = (1 / myID - 1/numProcs) / (1 - 1/numProcs);
          localSum += Fact ;
  }

  MPI_Reduce(&localSum, &parallelSum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);

  clockEnd = clock();

  if (myID == 0)
  {
          printf("Time to sum %d floats with MPI in parallel %3.5f seconds\n", length, (clockEnd - clockStart) / (float)CLOCKS_PER_SEC);
          printf("The parallel sum: %f\n", parallelSum + 1);
  }

    MPI_Finalize();
  return 0;
}

Body:
When I ran your code, my numProcs came up as 1 and the program crashed with

*** Process received signal ***
Signal: Floating point exception (8)
Signal code: Integer divide-by-zero (1)
Failing at address: 0x400af9
[ 0] /lib/x86_64-linux-gnu/libpthread.so.0(+0x10330)[0x7f8bb13d2330]
[ 1] ./mpi_sum[0x400af9]
[ 2] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0x7f8bb101af45]
[ 3] ./mpi_sum[0x400919]
*** End of error message ***
Floating point exception (core dumped)

on the line

Fact = (1 / myID - 1/numProcs) / (1 - 1/numProcs);

because we had a zero in the denominator.

Since you are getting a different error, may I suggest putting in a bunch of:

printf("%d\n", __LINE__); fflush(stdout);

statements to get an idea where it is crashing?


问:
Error in grouped_df_impl(data, unname(vars), drop) :
This is the first time I try to write a function with 2 pipes inside so that when I give a name x and variable name y, the results will be aggregrated, joined to the data and removed. When I run my written function, the captioned error message kept on coming up and I have no idea what the problem is.

```<code>mrr <- function(x, y){
  x <- data %>%
   group_by(y) %>%
   summarize(n=n(),
         sum=sum(unit_sales))
data <- data %>%
  left_join(x, by="y") %>%
  mutate(str_c(x,y))=(sum-unit_sales)/(n-1) %>%
  select(-one_of(n, sum)) %>%
  rm(x)
}
</code>```

I found the related results when I gave the error message in the search box, but the answers were not related to my problem. Do let me know if you have any thoughts.

答: You're getting hung up with str_c on the left hand side of your second pipe's mutate. dplyr uses non-standard evaluation, you need to use some tooling to accomplish what you want, vis := and perhaps UQ. See  use dplyr mutate() in programming for a similar problem.</p>

Body:
This is the first time I try to write a function with 2 pipes inside so that when I give a name x and variable name y, the results will be aggregrated, joined to the data and removed. When I run my written function, the captioned error message kept on coming up and I have no idea what the problem is.

mrr <- function(x, y){
  x <- data %>%
   group_by(y) %>%
   summarize(n=n(),
         sum=sum(unit_sales))
data <- data %>%
  left_join(x, by="y") %>%
  mutate(str_c(x,y))=(sum-unit_sales)/(n-1) %>%
  select(-one_of(n, sum)) %>%
  rm(x)
}

I found the related results when I gave the error message in the search box, but the answers were not related to my problem. Do let me know if you have any thoughts.


问:
AOSP repo sync takes too long
I'm trying to learn Embedded Android from the book with the same name. And the author suggested working with AOSP gingerbread branch. So I followed to download the source:

```<code>$ repo init -u https://android.googlesource.com/platform/manifest.git
-b gingerbread

$ repo sync
</code>```

But it's taking too long. Also from the output, it seems to me like it's also downloading source code from other branches (I see android-5.....) which is not what I want. I'm wondering if that's the reason why it takes so long.

Has anybody had the same problem? Please give me a suggestion! Thanks!

答:
```<code>repo sync -c --no-tags --no-clone-bundle -j2
</code>```

Shortens my sync times greatly.

Title: AOSP repo sync takes too long

Body:
I'm trying to learn Embedded Android from the book with the same name. And the author suggested working with AOSP gingerbread branch. So I followed to download the source:

$ repo init -u https://android.googlesource.com/platform/manifest.git
-b gingerbread

$ repo sync

But it's taking too long. Also from the output, it seems to me like it's also downloading source code from other branches (I see android-5.....) which is not what I want. I'm wondering if that's the reason why it takes so long.

Has anybody had the same problem? Please give me a suggestion! Thanks!

Body:
repo sync -c --no-tags --no-clone-bundle -j2

Shortens my sync times greatly.


问:
Typescript: Accessing a parent property from child object in a constant
In this Typescript/Javascript code:

```<code>var v= {
  x: 1,
  y: {
    z: v.x,
  }
}

const c = {
  x: 1,
  y: {
    z: c.x,
  }
}
</code>```

v is ok because var is JavaScript and it doesn't complain, but when assigning z in c there is an error because of the use of z before its declaration.

My question: is there a way to get it?
(I know I could declare another x out of c and assign its value inside, but I mean something more direct)

答:
One possibility is to make z lazy:

var v = {
   x: 1,
   y: {
      z: () => v.x,
   }
}

const c = {
   x: 1,
   y: {
      z: () => c.x,
   }
}

console.log(v.y.z());
console.log(c.y.z());```

Body:
In this Typescript/Javascript code:

var v= {
  x: 1,
  y: {
    z: v.x,
  }
}

const c = {
  x: 1,
  y: {
    z: c.x,
  }
}

v is ok because var is JavaScript and it doesn't complain, but when assigning z in c there is an error because of the use of z before its declaration.

My question: is there a way to get it?
(I know I could declare another x out of c and assign its value inside, but I mean something more direct)


问:
How to store elements in javascript array?
I am trying to build a card game in which two players gets random cards and the one who gets the highest sum of cards wins.

I tried pushing the generated random number into array .The trouble here is the new number should add to array but instead its going off leaving array empty. Could someone please help me.

 var varCounter = 1;
    var refVar = setInterval(function() {

      if (varCounter <= 4) {

        var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
        var player1 = [];
        player1.push(randomnumber);

        for (var i = 0; i < player1.length; i++) {
          document.write("
");
          document.write("player1 " + i + "card");
          document.write("
");
          document.write(player1[i]);

        }
        varCounter++;
      } else if (varCounter >= 5 && varCounter <= 8) {
        var randomnumber2 = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
        var player2 = [];
        player2.push(randomnumber2);
        for (var i = 0; i < player2.length; i++) {
          document.write("
");
          document.write("player2 " + i + "card");
          document.write("
");
          document.write(player2[i]);
        }
        varCounter++;
      } else {
        clearInterval(refVar);
      }
    }, 100);```
</div>
</div>
</p>

<p>EXPECTED OUTPUT:</p>

```player1 1card
9
player1 2card
12
player1 3card
4
player1 4card
12
player2 1card
5
player2 2card
7
player2 3card
9
player2 4card
2
```

<p>CURRENT OUTPUT:</p>

```player1 0card
9
player1 0card
12
player1 0card
4
player1 0card
12
player2 0card
5
player2 0card
7
player2 0card
9
player2 0card
2
```

答:
Try this if you only wanted the desired output. I changed varCounter-related code so it works with the varCounter modulo % nicely and made it into runnable snippet.

var varCounter = 0;
var refVar = setInterval(function() {

  if (varCounter < 4) {
    var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
    var player1 = [];
    player1.push(randomnumber);

    for (var i = 0; i < player1.length; i++) {
      document.write("
");
      document.write("player1 " + (varCounter%4+1) + "card");
      document.write("
");
      document.write(player1[i]);

    }
    varCounter++;
  } else if (varCounter >= 4 && varCounter < 8) {
    var randomnumber2 = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
    var player2 = [];
    player2.push(randomnumber2);
    for (var i = 0; i < player2.length; i++) {
      document.write("
");
      document.write("player2 " + (varCounter%4+1) + "card");
      document.write("
");
      document.write(player2[i]);
    }
    varCounter++;
  } else {
    clearInterval(refVar);
  }
}, 100);```
</div>
</div>
</p>

<p>Or if you really want the result which you fill the array with card values, (EDITED: Removed the <code>for</code> loops, add in the <code>for</code> loops again to check the array content)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var varCounter = 0;

var player1 = [];
var player2 = [];

var refVar = setInterval(function() {

  if (varCounter < 4) {
    var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
    player1.push(randomnumber);

    document.write("<br>");
    document.write("player1 " + (varCounter%4+1) + "card");
    document.write("<br>");
    document.write(player1[varCounter%4] + " "); //Removed for loop

    varCounter++;
  } else if (varCounter >= 4 && varCounter < 8) {
    var randomnumber2 = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
    player2.push(randomnumber2);

    document.write("<br>");
    document.write("player2 " + (varCounter%4+1) + "card");
    document.write("<br>");
    document.write(player2[varCounter%4] + " "); //Removed for loop

    varCounter++;
  } else {
    clearInterval(refVar);
  }
}, 100);</code>```

EDIT:
OP's Final Answer:

var varCounter = 0;
var player1 = [];
var player2 = [];
var refVar = setInterval(function() {
  if (varCounter <= 3) {
    var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;

    player1.push(randomnumber);
    var i = varCounter % 4;
    for (i; i < player1.length; i++) {

      document.write("
");
      document.write("player1 " + (i + 1) + "card");
      document.write("
");
      document.write(player1[i]);

    }
    varCounter++;
  } else if (varCounter >= 4 && varCounter <= 7) {
    var randomnumber2 = Math.floor(Math.random() * (13 - 1 + 1)) + 1;

    player2.push(randomnumber2);
    var i = varCounter % 4;
    for (i; i < player2.length; i++) {

      document.write("
");
      document.write("player2 " + (i + 1) + "card");
      document.write("
");
      document.write(player2[i]);

    }
    varCounter++;
  } else {
    clearInterval(refVar);
  }
}, 100)```

Body:
I am trying to build a card game in which two players gets random cards and the one who gets the highest sum of cards wins.

I tried pushing the generated random number into array .The trouble here is the new number should add to array but instead its going off leaving array empty. Could someone please help me.

 var varCounter = 1;
    var refVar = setInterval(function() {

      if (varCounter <= 4) {

        var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
        var player1 = [];
        player1.push(randomnumber);

        for (var i = 0; i < player1.length; i++) {
          document.write("
");
          document.write("player1 " + i + "card");
          document.write("
");
          document.write(player1[i]);

        }
        varCounter++;
      } else if (varCounter >= 5 && varCounter <= 8) {
        var randomnumber2 = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
        var player2 = [];
        player2.push(randomnumber2);
        for (var i = 0; i < player2.length; i++) {
          document.write("
");
          document.write("player2 " + i + "card");
          document.write("
");
          document.write(player2[i]);
        }
        varCounter++;
      } else {
        clearInterval(refVar);
      }
    }, 100);

EXPECTED OUTPUT:

player1 1card
9
player1 2card
12
player1 3card
4
player1 4card
12
player2 1card
5
player2 2card
7
player2 3card
9
player2 4card
2

CURRENT OUTPUT:

player1 0card
9
player1 0card
12
player1 0card
4
player1 0card
12
player2 0card
5
player2 0card
7
player2 0card
9
player2 0card
2

Body:
Try this if you only wanted the desired output. I changed varCounter-related code so it works with the varCounter modulo % nicely and made it into runnable snippet.

var varCounter = 0;
var refVar = setInterval(function() {

  if (varCounter < 4) {
    var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
    var player1 = [];
    player1.push(randomnumber);

    for (var i = 0; i < player1.length; i++) {
      document.write("<br>");
      document.write("player1 " + (varCounter%4+1) + "card");
      document.write("<br>");
      document.write(player1[i]);

    }
    varCounter++;
  } else if (varCounter >= 4 && varCounter < 8) {
    var randomnumber2 = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
    var player2 = [];
    player2.push(randomnumber2);
    for (var i = 0; i < player2.length; i++) {
      document.write("<br>");
      document.write("player2 " + (varCounter%4+1) + "card");
      document.write("<br>");
      document.write(player2[i]);
    }
    varCounter++;
  } else {
    clearInterval(refVar);
  }
}, 100);

Or if you really want the result which you fill the array with card values, (EDITED: Removed the for loops, add in the for loops again to check the array content)

var varCounter = 0;

var player1 = [];
var player2 = [];

var refVar = setInterval(function() {

  if (varCounter < 4) {
    var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
    player1.push(randomnumber);

    document.write("<br>");
    document.write("player1 " + (varCounter%4+1) + "card");
    document.write("<br>");
    document.write(player1[varCounter%4] + " "); //Removed for loop

    varCounter++;
  } else if (varCounter >= 4 && varCounter < 8) {
    var randomnumber2 = Math.floor(Math.random() * (13 - 1 + 1)) + 1;
    player2.push(randomnumber2);

    document.write("<br>");
    document.write("player2 " + (varCounter%4+1) + "card");
    document.write("<br>");
    document.write(player2[varCounter%4] + " "); //Removed for loop

    varCounter++;
  } else {
    clearInterval(refVar);
  }
}, 100);

EDIT:
OP's Final Answer:

var varCounter = 0;
var player1 = [];
var player2 = [];
var refVar = setInterval(function() {
  if (varCounter <= 3) {
    var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;

    player1.push(randomnumber);
    var i = varCounter % 4;
    for (i; i < player1.length; i++) {

      document.write("<br>");
      document.write("player1 " + (i + 1) + "card");
      document.write("<br>");
      document.write(player1[i]);

    }
    varCounter++;
  } else if (varCounter >= 4 && varCounter <= 7) {
    var randomnumber2 = Math.floor(Math.random() * (13 - 1 + 1)) + 1;

    player2.push(randomnumber2);
    var i = varCounter % 4;
    for (i; i < player2.length; i++) {

      document.write("<br>");
      document.write("player2 " + (i + 1) + "card");
      document.write("<br>");
      document.write(player2[i]);

    }
    varCounter++;
  } else {
    clearInterval(refVar);
  }
}, 100)


问:
How to bind Dropdown widget to query filter?
I have a Calculated Model, MonthlyTotalsByResource, displayed in a table that I am trying to query with a filter. First, I am retrieving the initial data from a regular Data Model called Allocations. I only wish to retrieve records from Allocations where the "Approved" field =true.

I also want to allow the user to filter MonthlyTotalsByResource by the "ManagerName" field. I have created a Dropdown widget with the Options as the full list of managers, and the Value is a query on the Calculated Model datasource:

```<code>    @datasource.query.filters.ManagerName._equals
</code>```

Here is the beginning of my code for getting the data for the Calculated Model MonthlyTotalsByResource from the regular data model Allocations, and where I filter for only "true" values in the Approved field. I am unclear what I should make the ManagerName filter set to in order for it to be binded to my Dropdown widget, or if I should add another query on the Calculated Model itself, instead of here on the regular Data Model.

```<code>    function getMonthlyTotalsByResource_() {
        var allRecordsQuery = app.models.Allocations.newQuery();
        allRecordsQuery.filters.Approved._equals = true;
        allRecordsQuery.filters.Resource.Manager.ManagerName._equals = ;
</code>```

答:
First things first, you need to introduce ManagerName parameter in your calculated datasource:

Once you add the parameter, you'll be able to set its value on client and read on server.

// dropdown widget's 'value' property binding
@datasources.MonthlyTotalsByResource.query.parameters.ManagerName

// server side code to get parameter value
var query = app.models.Allocations.newQuery();
...
query.filters.Resource.Manager.ManagerName._equals = query.parameters.ManagerName;
...
```

Body:
I have a Calculated Model, MonthlyTotalsByResource, displayed in a table that I am trying to query with a filter. First, I am retrieving the initial data from a regular Data Model called Allocations. I only wish to retrieve records from Allocations where the "Approved" field =true.

I also want to allow the user to filter MonthlyTotalsByResource by the "ManagerName" field. I have created a Dropdown widget with the Options as the full list of managers, and the Value is a query on the Calculated Model datasource:

    @datasource.query.filters.ManagerName._equals

Here is the beginning of my code for getting the data for the Calculated Model MonthlyTotalsByResource from the regular data model Allocations, and where I filter for only "true" values in the Approved field. I am unclear what I should make the ManagerName filter set to in order for it to be binded to my Dropdown widget, or if I should add another query on the Calculated Model itself, instead of here on the regular Data Model.

    function getMonthlyTotalsByResource_() {
        var allRecordsQuery = app.models.Allocations.newQuery();
        allRecordsQuery.filters.Approved._equals = true;
        allRecordsQuery.filters.Resource.Manager.ManagerName._equals = ;


问:
Run a separate PowerShell script asynchronously while continuing the current script
PowerShell script #1 does the following:

```<code>Performs FTP ops ending with saving updated remote directory data in a local file
</code>```

The script runs quickly until the remote directory data must be obtained using FTP.  It would be desirable to remove the remote directory data retrieval into a different PowerShell script #2.

This SO post explains launching a script from within a script.  But it seems in this case the first script is suspended while the second script executes.

How can I code script #1 so that script #2 is launched and forgotten and script #1 continues and completes quickly leaving script #2 to finish in the background.

答:
You would have a single script with multiple functions. The script is a standard ps1 script. The use-case here is you are executing blocks of code that do effectively a single task and you get to decide which blocks to execute at which stage of the script execution:

```<code>Function Get-RemoteDirectory {

   <Insert shorter running operation here>

}

Function Pull-RemoteDirectory {

  Get-RemoteDirectory -Path <Path>

  <Insert longer running operation here>

}

Pull-RemoteDirectory -SourcePath <Path> -DestinationPath <Path>
</code>```

Here I am calling the first function within the second function. You can insert your script logic as you like here. Be careful about variable scopes. Once your script is ready just save the file and execute as any Powershell script.

NB. You can add param() blocks to your script and/or to your functions. Whatever suits your needs depending on script runtime requirements.

Body:
PowerShell script #1 does the following:

Performs FTP ops ending with saving updated remote directory data in a local file

The script runs quickly until the remote directory data must be obtained using FTP.  It would be desirable to remove the remote directory data retrieval into a different PowerShell script #2.

This SO post explains launching a script from within a script.  But it seems in this case the first script is suspended while the second script executes.

How can I code script #1 so that script #2 is launched and forgotten and script #1 continues and completes quickly leaving script #2 to finish in the background.

Body:
You would have a single script with multiple functions. The script is a standard ps1 script. The use-case here is you are executing blocks of code that do effectively a single task and you get to decide which blocks to execute at which stage of the script execution:

Function Get-RemoteDirectory {

   <Insert shorter running operation here>

}

Function Pull-RemoteDirectory {

  Get-RemoteDirectory -Path <Path>

  <Insert longer running operation here>

}

Pull-RemoteDirectory -SourcePath <Path> -DestinationPath <Path>

Here I am calling the first function within the second function. You can insert your script logic as you like here. Be careful about variable scopes. Once your script is ready just save the file and execute as any Powershell script.

NB. You can add param() blocks to your script and/or to your functions. Whatever suits your needs depending on script runtime requirements.


问:
Displaying header data on google
This is my site:

http://www.armonisencia.cl/site/

When you search "armonisencia" on Google, it displays the following (you can see it on the attached picture too):

"Fatal error: Uncaught Error: Call to undefined function ...
www.armonisencia.cl/site/
Traducir esta páginaFatal error: Uncaught Error: Call to undefined function elegant_description() in /home/armonisencia/public_html/site/wp-content/themes/DIVI/header.php:16 Stack trace: #0 /home/armonisencia/public_html/site/wp-includes/template.php(688): require_once() #1 ..."

Maybe is some bug in my WordPress or something, but i decided i didn't want to look for the solution and i prefered to do the more simple stuff, i just edited my theme's header.php file and left the head element like this:

<title>Armonisencia</title>
   <meta charset="UTF-8">
 <meta name="description" content="Naturaleza que funciona">
 <meta name="keywords" content="Productos, Armonisencia">

 <?php $template_directory_uri = get_template_directory_uri(); ?>

 <?php wp_head(); ?>
```
</div>
</div>
</p>

<p>I made this change yesterday and today Google is still showing me the same ulgy data. How can i fix it?</p>

<p>This is how  looked before my change</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
 <meta charset="<?php bloginfo( 'charset' ); ?>" />
 <?php elegant_description(); ?>
 <?php elegant_keywords(); ?>
 <?php elegant_canonical(); ?>

 <?php do_action( 'et_head_meta' ); ?>

 <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />

 <?php $template_directory_uri = get_template_directory_uri(); ?>
 <!--[if lt IE 9]>
 <script src="<?php echo esc_url( $template_directory_uri . '/js/html5.js"' ); ?>" type="text/javascript"></script>
 <![endif]-->

 <script type="text/javascript">
  document.documentElement.className = 'js';
 </script>

 <?php wp_head(); ?>
</head></code>```

答:
The excerpt shown by google tells you where the error is:

"Fatal error: Uncaught Error: Call to undefined function elegant_description() in /home/armonisencia/public_html/site/wp-content/themes/DIVI/header.php:16 Stack trace: #0 /home/armonisencia/public_html/site/wp-includes/template.php(688): require_once() #1 .."

It saying that you're trying to use a function (elegant_description()) in your header.php that doesn't exist.

Google crawls websites to scrape information however it doesn't happen instantly (in fact it can take up to 30 days). You can request google to crawl your site again via Google search console. Here is a support doc by Google that will get you going in the right direction: https://support.google.com/webmasters/answer/6065812?hl=en

Title: Displaying header data on google

Body:
This is my site:

http://www.armonisencia.cl/site/

When you search "armonisencia" on Google, it displays the following (you can see it on the attached picture too):

"Fatal error: Uncaught Error: Call to undefined function ...
www.armonisencia.cl/site/
Traducir esta páginaFatal error: Uncaught Error: Call to undefined function elegant_description() in /home/armonisencia/public_html/site/wp-content/themes/DIVI/header.php:16 Stack trace: #0 /home/armonisencia/public_html/site/wp-includes/template.php(688): require_once() #1 ..."

Maybe is some bug in my WordPress or something, but i decided i didn't want to look for the solution and i prefered to do the more simple stuff, i just edited my theme's header.php file and left the head element like this:

<title>Armonisencia</title>
   <meta charset="UTF-8">
 <meta name="description" content="Naturaleza que funciona">
 <meta name="keywords" content="Productos, Armonisencia">

 <?php $template_directory_uri = get_template_directory_uri(); ?>

 <?php wp_head(); ?>

I made this change yesterday and today Google is still showing me the same ulgy data. How can i fix it?

This is how  looked before my change

 <meta charset="<?php bloginfo( 'charset' ); ?>" />
 <?php elegant_description(); ?>
 <?php elegant_keywords(); ?>
 <?php elegant_canonical(); ?>

 <?php do_action( 'et_head_meta' ); ?>

 <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />

 <?php $template_directory_uri = get_template_directory_uri(); ?>

 <?php wp_head(); ?>


问:
Object Browser for .NET Core Development on Mac OS X
I'm using Visual Studio Code on Mac OS X to develop a series of .NET Core web APIs.

However, I'm missing the Object Browser from Visual Studio 2015 on Windows, and similarly missing .NET Reflector. Either of these utilities are essential for browsing .NET assemblies, to discover constructors, method signatures, class names, and other metadata

Question: What can I use on Mac OS X as a replacement for the Visual Studio Object Browser or .NET Reflector?

答:
In Visual Studio for Mac, the information you ware looking for is located here:

View -> Pads -> Help

There you can see details on Basic Class Library, such as System > Console Class > Methods. Where you'll find eg. ReadLine. Tapping on this will launch a MonoDoc that will give you lots on in depth information that you would find in the Object Browser Windows Visual Studio equivalent.


问:
cannot share a folder with docker container
I am running a python interactive docker container on Ubuntu 14.04 using docker 17.03.1. I want to share files between local host and docker container so that files I create in the container are visible in the local directory and vice-versa. However when I run the following command I see an empty working directory in the container with no files.</p>

```<code>docker run -e USER=$USER -e USERID=$UID -v /home/watts/python:/home/watts/python -w=/home/watts/python -p 8888:8888 --rm -it watts/python jupyter notebook --no-browser --notebook-dir=/home/watts/python --allow-root
</code>```

答:
I just run this command:

```<code>docker run -v `pwd`/home/watts/python:/home/watts/python -it kaggle/python /bin/bash
</code>```

And after that, I started creating a few files both host and container. All files are visible in both sides.

Hopefully this will help.

Body:
I am running a python interactive docker container on Ubuntu 14.04 using docker 17.03.1. I want to share files between local host and docker container so that files I create in the container are visible in the local directory and vice-versa. However when I run the following command I see an empty working directory in the container with no files.

docker run -e USER=$USER -e USERID=$UID -v /home/watts/python:/home/watts/python -w=/home/watts/python -p 8888:8888 --rm -it watts/python jupyter notebook --no-browser --notebook-dir=/home/watts/python --allow-root

Body:
I just run this command:

docker run -v `pwd`/home/watts/python:/home/watts/python -it kaggle/python /bin/bash

And after that, I started creating a few files both host and container. All files are visible in both sides.

Hopefully this will help.


问:
How to run ansible on a nspawn container via its shell commands?
I have several systemd-nspawn containers I would like to connect to via ansible and run a series of scripts on each of them.

The traditional way is to use an SSH connection, I do that for other environments. In this case, the Ansible playbook will be ran on containers running on the same host which do not have SSH installed.

Is it possible to configure the playbook so that it uses the shell command of the containers to run its modules?

If not I will either install SSH on them, or use salt which will source its calls from the containers out.

答:
You should take a look at the connection plugins and use it by setting ansible_connection var for each host that is a nspawn container in your inventory.

If you don't find one that fit your situation, you can develop one locally (inspired from the docker one e.g.) then reference it with the config defaults.connection_plugins


问:
JavaScript Inheritance, Resetting the prototype constructor?
Here's a basic example of instance inheritance:

```<code>function A() {
    this.props = {
        a: 'a',
        b: 'b'
    }
}
A.prototype = {
    fn: function() {
        console.log(this.props);
    }
}

function B() {
    A.call(this);
}

B.prototype = Object.assign(A.prototype, {
    write: function() {
        this.fn();
    }
});

console.log(B.prototype.constructor); // ƒ Object() { [native code] }
B.prototype.constructor = B;
console.log(B.prototype.constructor); // ƒ B() { A.call(this); }

var b = new B();
</code>```

And here's an example of the same functions without inheritance:

```<code>function A() {
    this.props = {
        a: 'a',
        b: 'b'
    }
}
A.prototype = {
    fn: function() {
        console.log(this.props);
    }
}

function B() {

}
B.prototype = {
    write: function() {
        console.log('good')
    }
}

/*
    I don't think anyone advocates setting the prototype constructor
    as the Function to which it belongs in this case.
*/
console.log(B.prototype.constructor); // ƒ Object() { [native code] }
B.prototype.constructor = B;
console.log(B.prototype.constructor); // ƒ B() {}

var b = new B();
</code>```

As you can see, in both cases, before the line:

```<code>B.prototype.constructor = B;
</code>```

The prototype constructor is the native Object constructor and afterward it is the Object/Function which the prototypes were declared on.

Is the line in question necessary for older browsers, was it necessary to combat some popular bad techniques, or am I not doing prototypal inheritance correctly?

答:
Thanks Ibrahim, for pointing out, that in both cases I was overriding B.prototype.

In light of this, it seems that:

1.

```<code>B.prototype = Object.assign(B.prototype, A.prototype, {
    write: function() {
        this.fn();
    }
});
</code>```

2.

```<code>B.prototype = Object.assign(B.prototype, {
    write: function() {
        console.log('good')
    }
});
</code>```

Should leave the original prototype constructor intact.

Body:
Here's a basic example of instance inheritance:

function A() {
    this.props = {
        a: 'a',
        b: 'b'
    }
}
A.prototype = {
    fn: function() {
        console.log(this.props);
    }
}

function B() {
    A.call(this);
}

B.prototype = Object.assign(A.prototype, {
    write: function() {
        this.fn();
    }
});

console.log(B.prototype.constructor); // ƒ Object() { [native code] }
B.prototype.constructor = B;
console.log(B.prototype.constructor); // ƒ B() { A.call(this); }

var b = new B();

And here's an example of the same functions without inheritance:

function A() {
    this.props = {
        a: 'a',
        b: 'b'
    }
}
A.prototype = {
    fn: function() {
        console.log(this.props);
    }
}

function B() {

}
B.prototype = {
    write: function() {
        console.log('good')
    }
}

/*
    I don't think anyone advocates setting the prototype constructor
    as the Function to which it belongs in this case.
*/
console.log(B.prototype.constructor); // ƒ Object() { [native code] }
B.prototype.constructor = B;
console.log(B.prototype.constructor); // ƒ B() {}

var b = new B();

As you can see, in both cases, before the line:

B.prototype.constructor = B;

The prototype constructor is the native Object constructor and afterward it is the Object/Function which the prototypes were declared on.

Is the line in question necessary for older browsers, was it necessary to combat some popular bad techniques, or am I not doing prototypal inheritance correctly?

Body:
Thanks Ibrahim, for pointing out, that in both cases I was overriding B.prototype.

In light of this, it seems that:

1.

B.prototype = Object.assign(B.prototype, A.prototype, {
    write: function() {
        this.fn();
    }
});

2.

B.prototype = Object.assign(B.prototype, {
    write: function() {
        console.log('good')
    }
});

Should leave the original prototype constructor intact.


问:
jQuery Tools: only one AJAX tab
I would like to use jQuery Tools Tabs, and have a set of regular inline content tabs, and one AJAX tab. But I only see samples of either inline content, OR ajax content. Can I mix them?</p>

答:
AFAIK, it is either all AJAX or none. However, you can easily AJAX a single pane yourself. All you need to do is add a click handler (preferably using .one() so that it removes itself after it is run for the first time) to the tab; this click handler can then load the pane's content with .load() or whatever other AJAX means you want.

For example, the HTML would be something like this:

```<code><ul class="tabs">
    <li><a href="#">Tab 1</a></li>
    <li><a href="#">Tab 2</a></li>
    <li id="ajax-tab"><a href="#">Tab 3</a></li>
</ul>
<div class="panes">
    <div>First tab content. Tab contents are called "panes"</div>
    <div>Second tab content</div>
    <div id="ajax-pane"></div>
</div>
</code>```

and the JavaScript would be something like this:

```<code>$("ul.tabs").tabs("div.panes > div");
$('#ajax-tab').one('click', function() {
    $('#ajax-pane').load('/some/path/that/returns/our/html');
});
</code>```

And here's a simple live example: http://jsfiddle.net/ambiguous/stxha/

Title: jQuery Tools: only one AJAX tab

Body:
AFAIK, it is either all AJAX or none. However, you can easily AJAX a single pane yourself. All you need to do is add a click handler (preferably using .one() so that it removes itself after it is run for the first time) to the tab; this click handler can then load the pane's content with .load() or whatever other AJAX means you want.

For example, the HTML would be something like this:

<ul class="tabs">
    <li><a href="#">Tab 1</a></li>
    <li><a href="#">Tab 2</a></li>
    <li id="ajax-tab"><a href="#">Tab 3</a></li>
</ul>
<div class="panes">
    <div>First tab content. Tab contents are called "panes"</div>
    <div>Second tab content</div>
    <div id="ajax-pane"></div>
</div>

and the JavaScript would be something like this:

$("ul.tabs").tabs("div.panes > div");
$('#ajax-tab').one('click', function() {
    $('#ajax-pane').load('/some/path/that/returns/our/html');
});

And here's a simple live example: http://jsfiddle.net/ambiguous/stxha/


问:
In Microsoft Access, what are the relationships between CodeData, CodeProject, and DAO..?
What are the differences between the following sets of Microsoft Access VBA collections..? Some of them seem to point to the same data & child objects, but through different conduits. I'm thinking the DAO objects are DBMS-specific, but Access.⃰ Code.⃰  and Access.⃰ Project.⃰  are not, and get connected through Access. There is ADODB, which is another beast entirely. Also, it seems some of the collections may not exist if there no child objects of that type.

Given the mentions of SQL features, there seem to be three scenarios to be concerned with, but it's difficult to grasp:

A standalone ACCDB file.

A split database with two or more ACCDB
files.

An Access frontend to an SQL server.

Object set #1:

Access.CodeData.AllTables

Access.CodeData.AllQueries

Access.CodeData.AllFunctions

Access.CodeData.AllDatabaseDiagrams

Access.CodeData.AllStoredProcedures

Access.CodeData.AllViews

Access.CodeProject.AllForms

Access.CodeProject.AllMacros

Access.CodeProject.AllModules

Access.CodeProject.AllReports

And of course CodeData vs. CurrentData and CodeProject vs. CurrentProject.

Object set #2:

Access.Application.CodeData.*

Access.Application.CodeProject.*

Object set #3:

Access.Application.CurrentDb.QueryDefs (DAO.QueryDefs)

Access.Application.CurrentDb.Relations (DAO.Relations)

Access.Application.CurrentDb.TableDefs (DAO.TableDefs)

答:
In Access, the CodeDB and CurrentDb functions return DAO.Database objects.

CodeDb is the database or add-in, within which the code is running (which might not be the same as the CurrentDb.

CurrentDb is the currently active database (not an add-in).

Access 2002/03 added ADODB, and so they added CurrentProject and CodeProject functions for returning the ADO equivalents of CurrentDb and CodeDb, but being ADO, they have very different methods and properties.


答:
This is what I finally came up with.

var varCounter = 0;
var player1 = [];
var player2 = [];
var refVar = setInterval(function() {
  if (varCounter <= 3) {
    var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;

    player1.push(randomnumber);
    var i = varCounter % 4;
    for (i; i < player1.length; i++) {

      document.write("
");
      document.write("player1 " + (i + 1) + "card");
      document.write("
");
      document.write(player1[i]);

    }
    varCounter++;
  } else if (varCounter >= 4 && varCounter <= 7) {
    var randomnumber2 = Math.floor(Math.random() * (13 - 1 + 1)) + 1;

    player2.push(randomnumber2);
    var i = varCounter % 4;
    for (i; i < player2.length; i++) {

      document.write("
");
      document.write("player2 " + (i + 1) + "card");
      document.write("
");
      document.write(player2[i]);

    }
    varCounter++;
  } else {
    clearInterval(refVar);
  }
}, 100)```

Title: How to store elements in javascript array?

Body:
This is what I finally came up with.

var varCounter = 0;
var player1 = [];
var player2 = [];
var refVar = setInterval(function() {
  if (varCounter <= 3) {
    var randomnumber = Math.floor(Math.random() * (13 - 1 + 1)) + 1;

    player1.push(randomnumber);
    var i = varCounter % 4;
    for (i; i < player1.length; i++) {

      document.write("<br>");
      document.write("player1 " + (i + 1) + "card");
      document.write("<br>");
      document.write(player1[i]);

    }
    varCounter++;
  } else if (varCounter >= 4 && varCounter <= 7) {
    var randomnumber2 = Math.floor(Math.random() * (13 - 1 + 1)) + 1;

    player2.push(randomnumber2);
    var i = varCounter % 4;
    for (i; i < player2.length; i++) {

      document.write("<br>");
      document.write("player2 " + (i + 1) + "card");
      document.write("<br>");
      document.write(player2[i]);

    }
    varCounter++;
  } else {
    clearInterval(refVar);
  }
}, 100)


问:
How to convert specific algorithm with streams
The task is to return String with sum of every letter. The input is also a String.

For example

```<code>input: dasamdw
output: s1d2a2m1w1
</code>```

I came out with a simple quick algorithm:

```<code>private String method(String input) {
    Map<String, Integer> integerMap = new HashMap<>();
    for( char c : input.toCharArray()) {
        String key = String.valueOf(c);
        if(integerMap.containsKey(key)) {
            integerMap.put(key, integerMap.get(key) + 1);
        } else {
            integerMap.put(key, 1);
        }
    }

    StringBuilder sb = new StringBuilder();
    for(Map.Entry<String, Integer> e : integerMap.entrySet()) {
        sb.append(e.getKey());
        sb.append(e.getValue());
    }
    return sb.toString();
}
</code>```

But I really would like to use streams for that, someting like:

```<code>private String method(String input) {
    Map<Character, Integer> collect =
        input.chars().
        mapToObj(i -> (char)i).collect(Collectors.groupingBy(Function.identity(), Collectors.counting() ));

    return collect.entrySet()
                    .stream()
                    .map(entry -> entry.getKey() + "" + entry.getValue())
                    .collect(Collectors.joining(""));
}
</code>```

But I can't figure out the right groupingBy part...

答:
```<code>String foo = "dasamdw";
Arrays.stream(foo.split(""))
          .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
          .entrySet().stream()
                     .map(entry -> entry.getKey() + entry.getValue())
                     .collect(Collectors.joining(""));
</code>```

This gives the result -> a2s1d2w1m1

You can add your sorting how you would need however you needed.

Body:
The task is to return String with sum of every letter. The input is also a String.

For example

input: dasamdw
output: s1d2a2m1w1

I came out with a simple quick algorithm:

private String method(String input) {
    Map<String, Integer> integerMap = new HashMap<>();
    for( char c : input.toCharArray()) {
        String key = String.valueOf(c);
        if(integerMap.containsKey(key)) {
            integerMap.put(key, integerMap.get(key) + 1);
        } else {
            integerMap.put(key, 1);
        }
    }

    StringBuilder sb = new StringBuilder();
    for(Map.Entry<String, Integer> e : integerMap.entrySet()) {
        sb.append(e.getKey());
        sb.append(e.getValue());
    }
    return sb.toString();
}

But I really would like to use streams for that, someting like:

private String method(String input) {
    Map<Character, Integer> collect =
        input.chars().
        mapToObj(i -> (char)i).collect(Collectors.groupingBy(Function.identity(), Collectors.counting() ));

    return collect.entrySet()
                    .stream()
                    .map(entry -> entry.getKey() + "" + entry.getValue())
                    .collect(Collectors.joining(""));
}

But I can't figure out the right groupingBy part...

Body:
String foo = "dasamdw";
Arrays.stream(foo.split(""))
          .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
          .entrySet().stream()
                     .map(entry -> entry.getKey() + entry.getValue())
                     .collect(Collectors.joining(""));

This gives the result -> a2s1d2w1m1

You can add your sorting how you would need however you needed.


问:
perl my variable $x masks earlier declaration in same statement
I am confused on this error, this program takes user input 1 2 3 2 and displays the input in a specific order.

```<code>#!/usr/bin/perl -w
use strict;
use warnings;

print "Enter a number :";

my $num = <STDIN>;
chomp($num);

my @final = split(' ',$num);
my @count;
foreach my $x (@final){

 $count[my $x]++;

}
foreach my $x (@count){

print my $x .$count[my $x];
}
</code>```

my output : I get this error
"my" variable $x masks earlier declaration in same statement at line 19

Expected output:

1 1

2 2

3 1

答:
You are using my a little bit too often.

my is used to declare a variable, for the current scope (usually a block {...}).

To use the variable, you don't need the my.

So, in your first loop, do:

```<code>$count[ $x ]++;
</code>```

In the second loop:

```<code>print "$x: $count[ $x ]\n";
</code>```

See perldoc -f my and Private-Variables-via-my

Body:
I am confused on this error, this program takes user input 1 2 3 2 and displays the input in a specific order.

#!/usr/bin/perl -w
use strict;
use warnings;

print "Enter a number :";

my $num = <STDIN>;
chomp($num);

my @final = split(' ',$num);
my @count;
foreach my $x (@final){

 $count[my $x]++;

}
foreach my $x (@count){

print my $x .$count[my $x];
}

my output : I get this error
"my" variable $x masks earlier declaration in same statement at line 19

Expected output:

1 1

2 2

3 1

Body:
You are using my a little bit too often.

my is used to declare a variable, for the current scope (usually a block {...}).

To use the variable, you don't need the my.

So, in your first loop, do:

$count[ $x ]++;

In the second loop:

print "$x: $count[ $x ]\n";

See perldoc -f my and Private-Variables-via-my


问:
Access Search Subform + Update Query Subform?
So I'm new to Access 365, and I'm working on a database for my church's cemetery. I have a "main" form that will house searches and the results of said searches (https://i.imgur.com/v6ZmDx2.png).

So I'd like to put a box on this form that when I press the "Run Query" button, updates with all records matching the criteria. I have the query working, and if I go into the individual search form and search, it works fine.

If I try dragging the query onto the main form, I get a SearchQuery subform, but when I go into form view, I have to fill out data before the form even loads. I need it to only update after I click the button, so that I can enter info, THEN search (https://i.imgur.com/6jJ416o.png & https://i.imgur.com/XPPpg6S.png). If I click cancel, it loads fine, but when I type in data to the search then press "Run Query", it still prompts me for the info (https://i.imgur.com/FKbZ6WK.png).

Thanks in advance!

答:
Your code is constructing criteria with control names as the data to search in, must use table field names. Remove the Result_ from each expression.

Coffin and Cremation radio buttons are within an OptionGroup control. This means you must test for the value of the OptionGroup, not the controls within the group. Clicking radio button sets value of the OptionGroup control. Following is revised code for the OptionGroup and checkboxes. Note removal of Result_ - fix the other conditional expressions as well. Might want to rename the OptionGroup control.

```<code>'Coffin/Cremation
If Not IsNull(Me.optGroup) Then strFilter = strFilter & "([Coffin/Cremation] = " & Me.optGroup & ") AND "

'Veteran
If Not IsNull(Me.Veteran) Then strFilter = strFilter & "([Veteran] = " & Me.Veteran & ") AND "

'Monument
If Not IsNull(Me.Monument) Then strFilter = strFilter & "([Monument] = " & Me.Monument & ") AND "
</code>```

Why is the Clear Search button using EmbeddedMacro? Code to clear search parameters:

```<code>Private Sub cmdReset_Click()
    'Purpose:   Clear all the search boxes in the Form Header, and show all records again.
    Dim ctl As Control

    'Clear all the controls in the Form Header section.
    For Each ctl In Me.Section(acHeader).Controls
        Select Case ctl.ControlType
        Case acTextBox, acComboBox, acCheckBox, acOptionGroup
            ctl.Value = Null
        End Select
    Next

    'Remove the form's filter.
    Me.FilterOn = False
End Sub
</code>```

Consider using comboboxes instead of textboxes to help users enter valid data. Can still allow any input and use LIKE/wildcard. RowSource SQL could be like:

SELECT DISTINCT [Last Name] FROM A ORDER BY [Last Name];

Advise not to use space nor punctuation/special characters (only exception is underscore) in naming convention.

Body:
Your code is constructing criteria with control names as the data to search in, must use table field names. Remove the Result_ from each expression.

Coffin and Cremation radio buttons are within an OptionGroup control. This means you must test for the value of the OptionGroup, not the controls within the group. Clicking radio button sets value of the OptionGroup control. Following is revised code for the OptionGroup and checkboxes. Note removal of Result_ - fix the other conditional expressions as well. Might want to rename the OptionGroup control.

'Coffin/Cremation
If Not IsNull(Me.optGroup) Then strFilter = strFilter & "([Coffin/Cremation] = " & Me.optGroup & ") AND "

'Veteran
If Not IsNull(Me.Veteran) Then strFilter = strFilter & "([Veteran] = " & Me.Veteran & ") AND "

'Monument
If Not IsNull(Me.Monument) Then strFilter = strFilter & "([Monument] = " & Me.Monument & ") AND "

Why is the Clear Search button using EmbeddedMacro? Code to clear search parameters:

Private Sub cmdReset_Click()
    'Purpose:   Clear all the search boxes in the Form Header, and show all records again.
    Dim ctl As Control

    'Clear all the controls in the Form Header section.
    For Each ctl In Me.Section(acHeader).Controls
        Select Case ctl.ControlType
        Case acTextBox, acComboBox, acCheckBox, acOptionGroup
            ctl.Value = Null
        End Select
    Next

    'Remove the form's filter.
    Me.FilterOn = False
End Sub

Consider using comboboxes instead of textboxes to help users enter valid data. Can still allow any input and use LIKE/wildcard. RowSource SQL could be like:

SELECT DISTINCT [Last Name] FROM A ORDER BY [Last Name];

Advise not to use space nor punctuation/special characters (only exception is underscore) in naming convention.


问:
Javascript listening for data changes & trigger reload
I have a server sent event in PHP that displays inventory information client side and updates in real time. That part works great. The challenge is that I want to trigger a reload when the inventory = 0. Note: I'm using jQuery Mobile 1.4.5

Here's my code:

```<code>var source = new EventSource('listener.php');
source.onmessage = function(msg) {
document.getElementById('inv').innerHTML = msg.data;
};

source.addEventListener('msg', onMessageHandler,false);

function onMessageHandler(msg) {
var inventory = msg.data;
};

// Trying to Fire Something like this //
//if (inventory = 0) {
//setTimeout(function() {
//location.reload(true)
//},5000);
</code>```

Thanks for any suggestions : )

答:
Thank you for the suggestions. Both helped tremendously. This is what worked for me in the event any others ever have a similar challenge:</p>

```<code>var source = new EventSource('listener.php');
source.onmessage = function(msg) {
  document.getElementById('inv').innerHTML = msg.data;
  console.log(msg.data);
  var x = msg.data;
  if (x == 0) {
    setTimeout(function() {
      window.location.reload(true);
      // Or any of the 1000's of other ways to reload
    }, 1000);
  }
};

source.addEventListener('msg', onMessageHandler,false);

function onMessageHandler(msg) {
  var inventory = msg.data;
};
</code>```

Body:
I have a server sent event in PHP that displays inventory information client side and updates in real time. That part works great. The challenge is that I want to trigger a reload when the inventory = 0. Note: I'm using jQuery Mobile 1.4.5

Here's my code:

var source = new EventSource('listener.php');
source.onmessage = function(msg) {
document.getElementById('inv').innerHTML = msg.data;
};

source.addEventListener('msg', onMessageHandler,false);

function onMessageHandler(msg) {
var inventory = msg.data;
};

// Trying to Fire Something like this //
//if (inventory = 0) {
//setTimeout(function() {
//location.reload(true)
//},5000);

Thanks for any suggestions : )

Body:
Thank you for the suggestions. Both helped tremendously. This is what worked for me in the event any others ever have a similar challenge:

var source = new EventSource('listener.php');
source.onmessage = function(msg) {
  document.getElementById('inv').innerHTML = msg.data;
  console.log(msg.data);
  var x = msg.data;
  if (x == 0) {
    setTimeout(function() {
      window.location.reload(true);
      // Or any of the 1000's of other ways to reload
    }, 1000);
  }
};

source.addEventListener('msg', onMessageHandler,false);

function onMessageHandler(msg) {
  var inventory = msg.data;
};


问:
CloudKit "subscription is duplicate of" error - get SubscriptionId
I'm trying to save a CKQuerySubscription to the public database - a CKError is returned with the following information:

```<code>[
    "ServerErrorDescription": subscription is duplicate of 'C82E82EF-F373-4D75-A465-65364D8FEB12',
    "CKErrorDescription": Error saving record subscription with id E30DB4D5-2617-4E0D-8CFE-A14538140029 to server: subscription is duplicate of 'C82E82EF-F373-4D75-A465-65364D8FEB12',
    "NSDebugDescription": CKInternalErrorDomain: 2032,
    "NSUnderlyingError": <CKError 0x1c064ec70: "Server Rejected Request" (2032); server message = "subscription is duplicate of 'C82E82EF-F373-4D75-A465-65364D8FEB12'"; uuid = A5290A31-650C-44FC-B1C1-7BCB181291F8; container ID = "iCloud.com.mycompany.myapp">,
    "NSLocalizedDescription": Error saving record subscription with id E30DB4D5-2617-4E0D-8CFE-A14538140029 to server: subscription is duplicate of 'C82E82EF-F373-4D75-A465-65364D8FEB12', "errorKey": ck1uc5yob,
    "RequestUUID": A5290A31-650C-44FC-B1C1-7BCB181291F8,
    "ContainerID": iCloud.com.mycompany.myapp
]
</code>```

The properties ancestorRecord, clientRecord and serverRecord on the CKError object are all nil.

How can I get the ID of the query that exists on the server from this error (ie C82E82EF-F373-4D75-A465-65364D8FEB12). Is there a property that I'm missing that would have it?

答:
There are a couple of options. I tend to use fetchAllSubscriptionsWithCompletion handler to pull all subscriptions and then parse the ones I'm interested in, like so:

```<code> [publicDatabase fetchAllSubscriptionsWithCompletionHandler:^(NSArray<CKSubscription *> * _Nullable subscriptions, NSError * _Nullable error)
 {
     for (CKQuerySubscription *sub in subscriptions)
     {
         NSString *predString = [NSString stringWithFormat:@"%@", sub.predicate];
     }
 }];
</code>```

But you can also use CKFetchSubscriptionsOperation to pull all subs, or specific subs based on the subscription ID. In this case, you'd create the operation, configure the subscription ID you're interested, add your post-processing code to the completion block, and then run then run the operation.

Body:
I'm trying to save a CKQuerySubscription to the public database - a CKError is returned with the following information:

[
    "ServerErrorDescription": subscription is duplicate of 'C82E82EF-F373-4D75-A465-65364D8FEB12',
    "CKErrorDescription": Error saving record subscription with id E30DB4D5-2617-4E0D-8CFE-A14538140029 to server: subscription is duplicate of 'C82E82EF-F373-4D75-A465-65364D8FEB12',
    "NSDebugDescription": CKInternalErrorDomain: 2032,
    "NSUnderlyingError": <CKError 0x1c064ec70: "Server Rejected Request" (2032); server message = "subscription is duplicate of 'C82E82EF-F373-4D75-A465-65364D8FEB12'"; uuid = A5290A31-650C-44FC-B1C1-7BCB181291F8; container ID = "iCloud.com.mycompany.myapp">,
    "NSLocalizedDescription": Error saving record subscription with id E30DB4D5-2617-4E0D-8CFE-A14538140029 to server: subscription is duplicate of 'C82E82EF-F373-4D75-A465-65364D8FEB12', "errorKey": ck1uc5yob,
    "RequestUUID": A5290A31-650C-44FC-B1C1-7BCB181291F8,
    "ContainerID": iCloud.com.mycompany.myapp
]

The properties ancestorRecord, clientRecord and serverRecord on the CKError object are all nil.

How can I get the ID of the query that exists on the server from this error (ie C82E82EF-F373-4D75-A465-65364D8FEB12). Is there a property that I'm missing that would have it?

Body:
There are a couple of options. I tend to use fetchAllSubscriptionsWithCompletion handler to pull all subscriptions and then parse the ones I'm interested in, like so:

 [publicDatabase fetchAllSubscriptionsWithCompletionHandler:^(NSArray<CKSubscription *> * _Nullable subscriptions, NSError * _Nullable error)
 {
     for (CKQuerySubscription *sub in subscriptions)
     {
         NSString *predString = [NSString stringWithFormat:@"%@", sub.predicate];
     }
 }];

But you can also use CKFetchSubscriptionsOperation to pull all subs, or specific subs based on the subscription ID. In this case, you'd create the operation, configure the subscription ID you're interested, add your post-processing code to the completion block, and then run then run the operation.


问:
copy and paste the text in xmgrace
I have a graph in xmgrace (say, a graph of 10 different concentrations and hence 10 lines of different color), and I have typed some text corresponding to define what does each line represent. But now I have another similar graph and want to copy the same text typed for the previous graph to the new one. </p>

<p>How to copy and paste the text typed in the xmgrace from one graph to another.   </p>

答:
One of the frustrating things about using xmgrace is that it is not immediately obvious how to copy and paste.

You can copy selected text with ctrl-insert and paste it using shift-insert. This will work, for example, when editing the data set legend labels or axis labels.

However, if you do this many times it will become tedious. If you have already created a graph with labels you can re-use them all by saving a parameters file (a kind of template file).
To do this, with your first plot file loaded click 'Plot' > 'Save parameters' then choose a filename and click 'OK'.

You can then load the parameters file into any later plot. The parameters file contains lots of Graph, Set and Axis properties too.

Alternatively, when you are creating your second graph, add the -param flag to your command on the terminal.

e.g. xmgrace -param /foo/bar/template.par data1.dat data2.dat

Title: copy and paste the text in xmgrace

Body:
I have a graph in xmgrace (say, a graph of 10 different concentrations and hence 10 lines of different color), and I have typed some text corresponding to define what does each line represent. But now I have another similar graph and want to copy the same text typed for the previous graph to the new one.

How to copy and paste the text typed in the xmgrace from one graph to another.


问:
What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?
I'm designing a table in SQL Server 2008 that will store a list of users and a Google Maps co-ordinate (longitude & latitude).

Will I need two fields, or can it be done with 1?

What's the best (or most common) data-type to use for storing this kind of data?

答:
NOTE: This is a recent answer based on recent SQL server, .NET stack updates

latitute and longitude from google Maps should be stored as Point(note capital P) data in SQL server under geography data type.

Assuming your current data is stored in a table Sample as varchar under columns lat and lon, below query will help you convert to geography

```<code>alter table Sample add latlong geography
go
update Sample set latlong= geography::Point(lat,lon,4326)
go
</code>```

PS: Next time when you do a select on this table with geography data, apart from Results and Messages tab, you will also get Spatial results tab like below for visualization

OwnerDisplayName: jonathanconway

LastEditorDisplayName: Cade Roux

Body:
NOTE: This is a recent answer based on recent SQL server, .NET stack updates

latitute and longitude from google Maps should be stored as Point(note capital P) data in SQL server under geography data type.

Assuming your current data is stored in a table Sample as varchar under columns lat and lon, below query will help you convert to geography

alter table Sample add latlong geography
go
update Sample set latlong= geography::Point(lat,lon,4326)
go

PS: Next time when you do a select on this table with geography data, apart from Results and Messages tab, you will also get Spatial results tab like below for visualization


问:
How to get the data from a Fragment which is inside a DialogFragment?
I have a DialogFragment that is using a FragmentPagerAdapter to display tabs. Each tab has a different Fragment that uses a RecyclerView. I can get what item is clicked passed to the Fragment, but how can I get the data from the Fragment to the DialogFragment in order to pass it to the calling Activity?

TabDialog extends DialogFragment:

```<code>public class TabDialog extends DialogFragment {

public interface OnCompleteListener{
    void onCompleteListener(String test);
}

private OnCompleteListener mListener;

TabLayout tabLayout;
ViewPager viewPager;
FragmentTabPositive tabPositive = new FragmentTabPositive();
FragmentTabNegative tabNegative = new FragmentTabNegative();
TabAdapter adapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    getDialog().setCanceledOnTouchOutside(true);
    View rootView = inflater.inflate(R.layout.dialog_layout, container, false);
    tabLayout = (TabLayout) rootView.findViewById(R.id.tabLayout1);
    viewPager = (ViewPager) rootView.findViewById(R.id.masterViewPager);
    adapter = new TabAdapter(getChildFragmentManager());
    adapter.addFragment("Positive", tabPositive);
    adapter.addFragment("Negative", tabNegative);
    viewPager.setAdapter(adapter);
    tabLayout.setupWithViewPager(viewPager);

    return rootView;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{
        this.mListener = (OnCompleteListener)context;
    } catch(ClassCastException e){
        throw new ClassCastException(context.toString() +
                " must Implement OnCompleteListener");
    }

}
</code>```

TabAdapter extends FragmentPagerAdapter

```<code>public class TabAdapter extends FragmentPagerAdapter {

List<Fragment> mFragmentCollection = new ArrayList<>();
List<String> mTitleCollection = new ArrayList<>();

public TabAdapter(FragmentManager fm){
    super(fm);
}

public void addFragment(String title, Fragment fragment){

    mTitleCollection.add(title);
    mFragmentCollection.add(fragment);
}

@Override
public CharSequence getPageTitle(int position){
    return mTitleCollection.get(position);
}

@Override
public int getCount(){
    return mFragmentCollection.size();
}

@Override
public Fragment getItem(int position) {
    return mFragmentCollection.get(position);
}
</code>```

Inside the onCreateView within FragmentTabPos

```<code>popupAdapter = new PopupAdapter(view.getContext(), list);
    recyclerView.setAdapter(popupAdapter);

    popupAdapter.setmListener(new PopupAdapter.OnPointClickedListener() {
        @Override
        public void OnItemClicked(String test) {
            //This works
            Toast.makeText(FragmentTabPositive.this.getContext(), test + " Inside FragTabPos", Toast.LENGTH_LONG).show();
        }
    });
</code>```

答: Solved: Had to implement my own listener in the Fragment and triggered it in DialogFragment. From there, I used an OnCompleteListener to pass the data back to the calling Activity.</p>

Body:
I have a DialogFragment that is using a FragmentPagerAdapter to display tabs. Each tab has a different Fragment that uses a RecyclerView. I can get what item is clicked passed to the Fragment, but how can I get the data from the Fragment to the DialogFragment in order to pass it to the calling Activity?

TabDialog extends DialogFragment:

public class TabDialog extends DialogFragment {

public interface OnCompleteListener{
    void onCompleteListener(String test);
}

private OnCompleteListener mListener;

TabLayout tabLayout;
ViewPager viewPager;
FragmentTabPositive tabPositive = new FragmentTabPositive();
FragmentTabNegative tabNegative = new FragmentTabNegative();
TabAdapter adapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    getDialog().setCanceledOnTouchOutside(true);
    View rootView = inflater.inflate(R.layout.dialog_layout, container, false);
    tabLayout = (TabLayout) rootView.findViewById(R.id.tabLayout1);
    viewPager = (ViewPager) rootView.findViewById(R.id.masterViewPager);
    adapter = new TabAdapter(getChildFragmentManager());
    adapter.addFragment("Positive", tabPositive);
    adapter.addFragment("Negative", tabNegative);
    viewPager.setAdapter(adapter);
    tabLayout.setupWithViewPager(viewPager);

    return rootView;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{
        this.mListener = (OnCompleteListener)context;
    } catch(ClassCastException e){
        throw new ClassCastException(context.toString() +
                " must Implement OnCompleteListener");
    }

}

TabAdapter extends FragmentPagerAdapter

public class TabAdapter extends FragmentPagerAdapter {

List<Fragment> mFragmentCollection = new ArrayList<>();
List<String> mTitleCollection = new ArrayList<>();

public TabAdapter(FragmentManager fm){
    super(fm);
}

public void addFragment(String title, Fragment fragment){

    mTitleCollection.add(title);
    mFragmentCollection.add(fragment);
}

@Override
public CharSequence getPageTitle(int position){
    return mTitleCollection.get(position);
}

@Override
public int getCount(){
    return mFragmentCollection.size();
}

@Override
public Fragment getItem(int position) {
    return mFragmentCollection.get(position);
}

Inside the onCreateView within FragmentTabPos

popupAdapter = new PopupAdapter(view.getContext(), list);
    recyclerView.setAdapter(popupAdapter);

    popupAdapter.setmListener(new PopupAdapter.OnPointClickedListener() {
        @Override
        public void OnItemClicked(String test) {
            //This works
            Toast.makeText(FragmentTabPositive.this.getContext(), test + " Inside FragTabPos", Toast.LENGTH_LONG).show();
        }
    });


问:
Java singltone exception Exception in thread "main" java.net.BindException: Address already in use: JVM_Bind
i have Server side i tried to make it Singeltone in order to accses server metodtds from another classes, but when i run server main and then i do Server.getInstance() from another class it throws this expection:

Exception in thread "main"
  java.net.BindException: Address already in use: JVM_Bind

i tried a lot of things but its not working

```<code> private static Server serverinstance = null;
        private static Object obj=new Object();

        public Server() throws IOException {
            server = new ServerSocket(222);
            hash = new HashMap<String, SocketData>();
        }

        public static Server getInstance() throws IOException {
            synchronized (obj) {
                if (serverinstance == null) {
                    serverinstance = new Server();
                    serverinstance.listenServer();
                }
                return serverinstance;
            }
        }

        private void listenServer() throws IOException {
            while (flag) {
                ans = server.accept();
                if (serverinstance != null)
                    new EchoThread(serverinstance, ans);
            }
        }

    public static void main(String args[]) throws IOException {
            Server.getInstance();
        }

    Class A()
    {
    public A()
    {
    Server.getInstance();
    }
    }
</code>```

答:
Java singleton guarantees one instance only per JVM and per ClassLoader.

In your case you are loading the same Server class into two different JVM and Classloaders by invoking two separate main methods. This causes the Server constructor to be called twice that in turn tries to create two ServerSocket on the same 222 port.

One quick solution is to have class A be created directly or indirectly from the main method that is calling Server.getInstance();.

Body:
i have Server side i tried to make it Singeltone in order to accses server metodtds from another classes, but when i run server main and then i do Server.getInstance() from another class it throws this expection:

Exception in thread "main"
  java.net.BindException: Address already in use: JVM_Bind

i tried a lot of things but its not working

 private static Server serverinstance = null;
        private static Object obj=new Object();

        public Server() throws IOException {
            server = new ServerSocket(222);
            hash = new HashMap<String, SocketData>();
        }

        public static Server getInstance() throws IOException {
            synchronized (obj) {
                if (serverinstance == null) {
                    serverinstance = new Server();
                    serverinstance.listenServer();
                }
                return serverinstance;
            }
        }

        private void listenServer() throws IOException {
            while (flag) {
                ans = server.accept();
                if (serverinstance != null)
                    new EchoThread(serverinstance, ans);
            }
        }

    public static void main(String args[]) throws IOException {
            Server.getInstance();
        }

    Class A()
    {
    public A()
    {
    Server.getInstance();
    }
    }


问:
Catching command-line errors using %x
Whenever you want to execute something on the command line, you can use the following syntax:

```<code>%x(command to run)
</code>```

However, I want to catch an error or at least get the response so I can parse it correctly. I tried setting:

```<code>result = %x(command to run)
</code>```

and using a try-catch

```<code>begin
  %x(command to run)
rescue
  "didn't work"
end
</code>```

to no avail. How can I capture the results instead of having them printed out?

答:
So this doesn't directly answer your question (won't capture the command's output).  But instead of trying begin/rescue, you can just check the exit code ($?) of the command:

```<code>%x(command to run)
unless $? == 0
   "ack! error occurred"
end
</code>```

Edit: Just remembered this new project.  I think it does exactly what you want:

https://github.com/envato/safe_shell

Title: Catching command-line errors using %x

Body:
Whenever you want to execute something on the command line, you can use the following syntax:

%x(command to run)

However, I want to catch an error or at least get the response so I can parse it correctly. I tried setting:

result = %x(command to run)

and using a try-catch

begin
  %x(command to run)
rescue
  "didn't work"
end

to no avail. How can I capture the results instead of having them printed out?

Body:
So this doesn't directly answer your question (won't capture the command's output).  But instead of trying begin/rescue, you can just check the exit code ($?) of the command:

%x(command to run)
unless $? == 0
   "ack! error occurred"
end

Edit: Just remembered this new project.  I think it does exactly what you want:

https://github.com/envato/safe_shell