问:
How to schedule a jar file on Linux for fixed time in future?
I need to run a jar file (datacollector.jar), say having path (/home/vagrant/datatool) on a Linux machine for a fixed interval of time. For example, from 18:00 10-06-2017 to 03:00 11-06-2017 in some future time. After that, the process should be killed.

I want to write a shell script for this which takes two arguments starting and ending time.

The script should also inform if its already running or not, and I should be able to manually stop it before ending time.

I am unable to figure this out after spending some researching online. How can I achieve this?

I come up with a solution in which myshell.sh take 4 arguments

  [start_date] [start_time] [end_date] [end_time].

and script code :

```<code>#!/bin/bash
JAR_PATH=/home/vagrant/datatool/datacollector.jar
PID_PATH=/tmp/datacollector-id

#calculate wait time to run the jar
wait=$(($(date -d "$1 $2" "+%s")-$(date "+%s")))
wait_mins=$((wait/60))

#calculate time for which jar file should be executed
run_interval=$(($(date -d "$3 $4" "+%s")-$(date -d "$1 $2" "+%s")))
run_interval_mins=$((run_interval/60))

echo "tool will satrt after $wait_mins"

#wait before running jar file
sleep "$wait_mins"m

#run the jar file
nohup java -jar $JAR_PATH /tmp 2>> /dev/null >> /dev/null &

echo $! > $PID_PATH

#wait for jar execution time
sleep "$run_interval_mins"m

#kill the jar process
PID=$(cat $PID_PATH);
echo "tool process killed"
kill $PID;

echo "program terminated"
</code>```

and I am running the code with command:

```<code>$ nohup ./myshell.sh 2017-06-08 20:07:00 2017-06-08 20:10:00 >> scriptoutput.txt  2>> /dev/null &
</code>```

and scriptoutput.txt contains:

```<code>tool will satrt after 3
tool process killed
program terminated
</code>```

Where I need to improve my code?
Is there any better way to do it?

答:
There are no wonders: considering your post, you are probably not allowed to modify its source code and recompile it. Thus, you need an external thing, some other process what

starts the jar with a JVM

stops it

informs the user about its start and stop.

The simplest way to do that are the

at command (you can start something in the future with it)

cron command (you can periodically can execute commands with it in the background)

and, the shell scripts.

If it is only a single-time execution, the "at" command would be the best.

Learn about the linux shellscripting by googling for "linux shell scripting tutorial". You can have more specific answers about your problem on the http://unix.stackexchange.com .

Body:
I need to run a jar file (datacollector.jar), say having path (/home/vagrant/datatool) on a Linux machine for a fixed interval of time. For example, from 18:00 10-06-2017 to 03:00 11-06-2017 in some future time. After that, the process should be killed.

I want to write a shell script for this which takes two arguments starting and ending time.

The script should also inform if its already running or not, and I should be able to manually stop it before ending time.

I am unable to figure this out after spending some researching online. How can I achieve this?

I come up with a solution in which myshell.sh take 4 arguments

  [start_date] [start_time] [end_date] [end_time].

and script code :

#!/bin/bash
JAR_PATH=/home/vagrant/datatool/datacollector.jar
PID_PATH=/tmp/datacollector-id

#calculate wait time to run the jar
wait=$(($(date -d "$1 $2" "+%s")-$(date "+%s")))
wait_mins=$((wait/60))

#calculate time for which jar file should be executed
run_interval=$(($(date -d "$3 $4" "+%s")-$(date -d "$1 $2" "+%s")))
run_interval_mins=$((run_interval/60))

echo "tool will satrt after $wait_mins"

#wait before running jar file
sleep "$wait_mins"m

#run the jar file
nohup java -jar $JAR_PATH /tmp 2>> /dev/null >> /dev/null &

echo $! > $PID_PATH

#wait for jar execution time
sleep "$run_interval_mins"m

#kill the jar process
PID=$(cat $PID_PATH);
echo "tool process killed"
kill $PID;

echo "program terminated"

and I am running the code with command:

$ nohup ./myshell.sh 2017-06-08 20:07:00 2017-06-08 20:10:00 >> scriptoutput.txt  2>> /dev/null &

and scriptoutput.txt contains:

tool will satrt after 3
tool process killed
program terminated

Where I need to improve my code?
Is there any better way to do it?


来源: stackexchange

问:
angularjs - apply filter on dynamic property of object
what i'm trying to do is ask user to choose the property on which they want to apply filter. the data is shown in table format using ng-repeat.
enter image description here

my code looks like this:
the form to add data:-

```<code><form name="myform">
                        <div class="form-group">
                            <input type="text" class="form-control" id="name" placeholder="Name" ng-model="data.name" required>
                        </div>
                        <div class="form-group">
                            <input type="email" class="form-control" id="email" placeholder="Email" ng-model="data.email" required>
                        </div>
                        <div class="form-group">
                            <textarea class="form-control" id="comment" placeholder="Comment" ng-model="data.comment" required></textarea>
                        </div>
                        <div class="row">
                            <div class="col-xs-6">
                                <button type="submit" class="btn btn-primary" ng-disabled="myform.$invalid" ng-click="add(data)">Submit</button>
                            </div>
                            <div class="col-xs-6">.
                                <button type="submit" class="btn btn-default" ng-click="reset()" ng-disabled="myform.$invalid">Reset</button>
                            </div>
                        </div>
                    </form>
</code>```

the table to show data:-

```<code><div class="col-sm-6 col-sm-offset-3" style="overflow-x:auto;">
            <div class="row">
                <div class="col-xs-6">
                    <select ng-options="key as value for (key, value) in keys" class="form-control" ng-model="filtercolumn">
                         <option value="">Select column</option>
                    </select>
                </div>
                <div class="col-xs-6">
                    <input type="text" class="form-control" ng-model="filtertxt" placeholder="filter">
                </div>
            </div>
            <br><br>
            <table class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>Sr</th>
                        <th>Date</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Comment</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="x in data | filter: {filtercolumn: filtertxt}">
                        <td>{{x.sr}}</td>
                        <td>{{x.date}}</td>
                        <td>{{x.name}}</td>
                        <td>{{x.email}}</td>
                        <td>{{x.comment}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
</code>```

and here is the controller:

```<code>app.controller("ctrl", ["$scope", function($scope){
    var i = 0;
    $scope.keys =  {"sr": 'Sr', "date": 'Date', "name": 'Name', "email": 'Email', "comment": 'Comment'};
    $scope.data = [];

    $scope.add = function(data){
        $scope.data.push({
            "sr": i++,
            "date": new Date().toDateString(),
            "name": data.name,
            "email": data.email,
            "comment": data.comment
        });
        $scope.data.name = "";
        $scope.data.email = "";
        $scope.data.comment = "";
    };

    $scope.reset = function(){
        $scope.data.name = "";
        $scope.data.email = "";
        $scope.data.comment = "";
    };
}]);
</code>```

as i'm new to angular, may be i'm missing some concept.

Thanks in advance

答:
Try this:

```<code><div class="col-sm-6 col-sm-offset-3" style="overflow-x:auto;">
            <div class="row">
                <div class="col-xs-6">
                    <select ng-options="key as value for (key, value) in keys" ng-change="change()" class="form-control" ng-model="filtercolumn">
                         <option value="">Select column</option>
                    </select>
                </div>
                <div class="col-xs-6">
                    <input type="Search" class="form-control" ng-init="filtercolumn= ''; filtertxt= ''" ng-model="filtertxt[filtercolumn]" placeholder="search..">
                </div>
            </div>
            <br><br>
            <table class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>Sr</th>
                        <th>Date</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Comment</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="x in data | filter: filtertxt">
                        <td>{{x.sr}}</td>
                        <td>{{x.date}}</td>
                        <td>{{x.name}}</td>
                        <td>{{x.email}}</td>
                        <td>{{x.comment}}</td>
                    </tr>
                </tbody>
            </table>
        </div>
</code>```

And here is controller:

```<code>app.controller("ctrl", ["$scope", function($scope){
    var i = 0;
    $scope.keys =   {"sr": 'Sr', "date": 'Date', "name": 'Name', "email": 'Email', "comment": 'Comment'};
    $scope.data = [];

    $scope.add = function(data){
        $scope.data.push({
            "sr": i++,
            "date": new Date().toDateString(),
            "name": data.name,
            "email": data.email,
            "comment": data.comment
        });
        $scope.data.name = "";
        $scope.data.email = "";
        $scope.data.comment = "";
    };
    $scope.filtercolumn = '';
    $scope.change = function() {
                        $scope.filtertxt = '';
                    };

    $scope.reset = function(){
        $scope.data.name = "";
        $scope.data.email = "";
        $scope.data.comment = "";
    };
}]);
</code>```

This will search for input text from the selected columnName.

ContentLicense: CC BY-SA 3.0

Body:
what i'm trying to do is ask user to choose the property on which they want to apply filter. the data is shown in table format using ng-repeat.
enter image description here

my code looks like this:
the form to add data:-

<form name="myform">

                            <input type="text" class="form-control" id="name" placeholder="Name" ng-model="data.name" required>

                            <input type="email" class="form-control" id="email" placeholder="Email" ng-model="data.email" required>

                            <textarea class="form-control" id="comment" placeholder="Comment" ng-model="data.comment" required></textarea>

                                <button type="submit" class="btn btn-primary" ng-disabled="myform.$invalid" ng-click="add(data)">Submit</button>

.
                                <button type="submit" class="btn btn-default" ng-click="reset()" ng-disabled="myform.$invalid">Reset</button>

                    </form>

the table to show data:-

                    <select ng-options="key as value for (key, value) in keys" class="form-control" ng-model="filtercolumn">
                         <option value="">Select column</option>
                    </select>

                    <input type="text" class="form-control" ng-model="filtertxt" placeholder="filter">

                        Sr
                        Date
                        Name
                        Email
                        Comment

                        {{x.sr}}
                        {{x.date}}
                        {{x.name}}
                        {{x.email}}
                        {{x.comment}}

and here is the controller:

app.controller("ctrl", ["$scope", function($scope){
    var i = 0;
    $scope.keys =  {"sr": 'Sr', "date": 'Date', "name": 'Name', "email": 'Email', "comment": 'Comment'};
    $scope.data = [];

    $scope.add = function(data){
        $scope.data.push({
            "sr": i++,
            "date": new Date().toDateString(),
            "name": data.name,
            "email": data.email,
            "comment": data.comment
        });
        $scope.data.name = "";
        $scope.data.email = "";
        $scope.data.comment = "";
    };

    $scope.reset = function(){
        $scope.data.name = "";
        $scope.data.email = "";
        $scope.data.comment = "";
    };
}]);

as i'm new to angular, may be i'm missing some concept.

Thanks in advance

Body:
Try this:

<div class="col-sm-6 col-sm-offset-3" style="overflow-x:auto;">
            <div class="row">
                <div class="col-xs-6">
                    <select ng-options="key as value for (key, value) in keys" ng-change="change()" class="form-control" ng-model="filtercolumn">
                         <option value="">Select column</option>
                    </select>
                </div>
                <div class="col-xs-6">
                    <input type="Search" class="form-control" ng-init="filtercolumn= ''; filtertxt= ''" ng-model="filtertxt[filtercolumn]" placeholder="search..">
                </div>
            </div>
            <br><br>
            <table class="table table-striped table-bordered">
                <thead>
                    <tr>
                        <th>Sr</th>
                        <th>Date</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Comment</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="x in data | filter: filtertxt">
                        <td>{{x.sr}}</td>
                        <td>{{x.date}}</td>
                        <td>{{x.name}}</td>
                        <td>{{x.email}}</td>
                        <td>{{x.comment}}</td>
                    </tr>
                </tbody>
            </table>
        </div>

And here is controller:

app.controller("ctrl", ["$scope", function($scope){
    var i = 0;
    $scope.keys =   {"sr": 'Sr', "date": 'Date', "name": 'Name', "email": 'Email', "comment": 'Comment'};
    $scope.data = [];

    $scope.add = function(data){
        $scope.data.push({
            "sr": i++,
            "date": new Date().toDateString(),
            "name": data.name,
            "email": data.email,
            "comment": data.comment
        });
        $scope.data.name = "";
        $scope.data.email = "";
        $scope.data.comment = "";
    };
    $scope.filtercolumn = '';
    $scope.change = function() {
                        $scope.filtertxt = '';
                    };

    $scope.reset = function(){
        $scope.data.name = "";
        $scope.data.email = "";
        $scope.data.comment = "";
    };
}]);

This will search for input text from the selected columnName.


问:
toggle a checkbox attribute on a array of items in a carousel in Angular 2/Typescript
I have this carousel. Each item in the carousel has a checkbox above it. I want to be able to click on item and the checkbox gets a checked attribute. The code does this. The only problem I'm having is it toggles all check boxes in the carousel. I just want it to toggle the one clicked.</p>

```<code>      <tshq-carousel [dataSource]="brands" [selections]="selectedBrands"  (select)="onItemsSelected($event)" [changeKey]="changeKey" [pageSize]="5" [circular]="false"
    [enableSelection]="true"  mode="single">
    <ng-template let-brand>
      <ng-container [ngSwitch]="brand.icon&&brand.icon.length>0">
        <ng-container *ngSwitchCase="true" >
          <label class="apply carousel-checkbox">
          <input  type="checkbox" id="brandCheck" [checked]="isChecked" value="no" name = "brand">
          </label>
          <img [src]="formatLogo(brand.icon)" style="max-width:150px" (click)="isChecked = !isChecked" />
        </ng-container>
      </ng-container>
    </ng-template>

  </tshq-carousel>
</code>```

答:
You use isChecked variable to binding to all input checkbox of carousel, so when you change value (check or uncheck) 1 input checkbox, it also set to all remain ones.

I suggest you add 1 property to model brand and use it to binding to input checkbox or image.
Ex:

```<code><tshq-carousel [dataSource]="brands" [selections]="selectedBrands"  (select)="onItemsSelected($event)" [changeKey]="changeKey" [pageSize]="5" [circular]="false"
    [enableSelection]="true"  mode="single">
    <ng-template let-brand>
      <ng-container [ngSwitch]="brand.icon && brand.icon.length>0">
        <ng-container *ngSwitchCase="true" >
          <label class="apply carousel-checkbox">
          <input  type="checkbox" id="brandCheck" [checked]="brand.isChecked" value="no" name="brand">
          </label>
          <img [src]="formatLogo(brand.icon)" style="max-width:150px" (click)="brand.isChecked = !brand.isChecked" />
        </ng-container>
      </ng-container>
    </ng-template>

  </tshq-carousel>
</code>```

Body:
I have this carousel. Each item in the carousel has a checkbox above it. I want to be able to click on item and the checkbox gets a checked attribute. The code does this. The only problem I'm having is it toggles all check boxes in the carousel. I just want it to toggle the one clicked.

      <tshq-carousel [dataSource]="brands" [selections]="selectedBrands"  (select)="onItemsSelected($event)" [changeKey]="changeKey" [pageSize]="5" [circular]="false"
    [enableSelection]="true"  mode="single">
    <ng-template let-brand>
      <ng-container [ngSwitch]="brand.icon&&brand.icon.length>0">
        <ng-container *ngSwitchCase="true" >

          <input  type="checkbox" id="brandCheck" [checked]="isChecked" value="no" name = "brand">

        </ng-container>
      </ng-container>
    </ng-template>

  </tshq-carousel>

Body:
You use isChecked variable to binding to all input checkbox of carousel, so when you change value (check or uncheck) 1 input checkbox, it also set to all remain ones.

I suggest you add 1 property to model brand and use it to binding to input checkbox or image.
Ex:

<tshq-carousel [dataSource]="brands" [selections]="selectedBrands"  (select)="onItemsSelected($event)" [changeKey]="changeKey" [pageSize]="5" [circular]="false"
    [enableSelection]="true"  mode="single">
    <ng-template let-brand>
      <ng-container [ngSwitch]="brand.icon && brand.icon.length>0">
        <ng-container *ngSwitchCase="true" >
          <label class="apply carousel-checkbox">
          <input  type="checkbox" id="brandCheck" [checked]="brand.isChecked" value="no" name="brand">
          </label>
          <img [src]="formatLogo(brand.icon)" style="max-width:150px" (click)="brand.isChecked = !brand.isChecked" />
        </ng-container>
      </ng-container>
    </ng-template>

  </tshq-carousel>


问:
Find token in existing cassandra cluster
How do we find existing token assigned to cassandra nodes? I have 4 node cluster, how can i identify if nodes are unbalanced? What are values of currently assigned tokens? Is there any command used with nodetool.</p>

答:
You can use the "nodetool ring" command. http://docs.datastax.com/en/cassandra/2.1/cassandra/tools/toolsRing.html

It shows all the needed information regarding tokens assignment. It also shows the load under the data directory for each node in the cluster.


问:
Subtraction of unlike doubles resulting in 0.0
I am trying to subtract two small doubles, both of which I have gotten by using the system time like so:

```<code>start = System.currentTimeMillis();
end = System.currentTimeMillis();
</code>```

I then subtracted the two (end - start) and attempted to store the value into a double[] data array I made. For some reason the result of that, instead of being a double, keeps on outputting 0.0.

I initialized the data array as follows:

```<code>private double[] data = new double[maxTaps+1];
</code>```

where MaxTaps is some constant

I am using a textView to output onto the screen what the values are as I go. For some reason, when I just print out (end - start), it will give me a double that is non-zero. But if I put that double (end - start) into my data array and try to print the double from the data array, it results in 0.0.

For example: I am trying to get the time from when a button changes color to when it is tapped. After changing the color of the button I set the start time. Then when the user taps the specific button, the end time is recorded using the way above and the two are subtracted and added into my data array. The weird part is as follows: when I output the data like below, the result is always 0.0

```<code>bottomText.setText("Data point " + Integer.toString(taps) + ": " + String.valueOf(data[taps]));
</code>```

but, if I change data[taps] to (end - start) (shown below), then I get a reasonable value

```<code>bottomText.setText("Data point " + Integer.toString(taps) + ": " + String.valueOf((end - start));
</code>```

I am really lost here because they should be the same value.

Also, I am just including what one of my click listeners looks like for a button, that might also be useful

```<code>buttonTopLeft.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view){
            if (lit == 1) {
                end = System.currentTimeMillis();
                data[taps] = (end - start);
                taps++;
                buttonTopLeft.setBackgroundColor(Color.WHITE);

                mHandler.postDelayed(new Runnable() {
                    public void run(){
                        doUpdate();
                    }
                }, 1000);
            }
         }
    });
</code>```

答: The problem is most likelly because you are incrementing taps, after you are setting the value and the new data[taps] is actually zero. The data at data[taps-1] is the value you are after. Lets say taps is at 0, then you set the first element -data[0]= 15.0 . Then taps++ now taps is 1, and you will actually print data[1]  which is not set so it shows 0

Body:
I am trying to subtract two small doubles, both of which I have gotten by using the system time like so:

start = System.currentTimeMillis();
end = System.currentTimeMillis();

I then subtracted the two (end - start) and attempted to store the value into a double[] data array I made. For some reason the result of that, instead of being a double, keeps on outputting 0.0.

I initialized the data array as follows:

private double[] data = new double[maxTaps+1];

where MaxTaps is some constant

I am using a textView to output onto the screen what the values are as I go. For some reason, when I just print out (end - start), it will give me a double that is non-zero. But if I put that double (end - start) into my data array and try to print the double from the data array, it results in 0.0.

For example: I am trying to get the time from when a button changes color to when it is tapped. After changing the color of the button I set the start time. Then when the user taps the specific button, the end time is recorded using the way above and the two are subtracted and added into my data array. The weird part is as follows: when I output the data like below, the result is always 0.0

bottomText.setText("Data point " + Integer.toString(taps) + ": " + String.valueOf(data[taps]));

but, if I change data[taps] to (end - start) (shown below), then I get a reasonable value

bottomText.setText("Data point " + Integer.toString(taps) + ": " + String.valueOf((end - start));

I am really lost here because they should be the same value.

Also, I am just including what one of my click listeners looks like for a button, that might also be useful

buttonTopLeft.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view){
            if (lit == 1) {
                end = System.currentTimeMillis();
                data[taps] = (end - start);
                taps++;
                buttonTopLeft.setBackgroundColor(Color.WHITE);

                mHandler.postDelayed(new Runnable() {
                    public void run(){
                        doUpdate();
                    }
                }, 1000);
            }
         }
    });


问:
Unable to connect to SQL Server session database
My asp.net applications works fine everyday.
Until last month, my web start to get 2-3 time of problem with Sqlsession state server as
follow:

Blockquote
  System.Web.HttpException  Exception of type 'System.Web.HttpException' was thrown.     at System.Web.HttpAsyncResult.End()     at System.Web.SessionState.SessionStateModule.EndAcquireState(IAsyncResult ar)     at System.Web.HttpApplication.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar)  ==================================================  Exception: System.Web.HttpException  Unable to connect to SQL Server session database.     at System.Web.SessionState.SqlSessionStateStore.ThrowSqlConnectionException(SqlConnection conn, Exception e)     at System.Web.SessionState.SqlSessionStateStore.SqlStateConnection..ctor(SqlPartitionInfo sqlPartitionInfo)     at System.Web.SessionState.SqlSessionStateStore.GetConnection(String id, Boolean& usePooling)     at System.Web.SessionState.SqlSessionStateStore.DoGet(HttpContext context, String id, Boolean getExclusive, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags)     at System.Web.SessionState.SqlSessionStateStore.GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags)     at System.Web.SessionState.SessionStateModule.GetSessionStateItem()     at System.Web.SessionState.SessionStateModule.PollLockedSessionCallback(Object state)  ==================================================  Exception: System.InvalidOperationException  Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool.  This may have occurred because all pooled connections were in use and max pool size was reached.     at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)     at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)     at System.Data.SqlClient.SqlConnection.Open()     at System.Web.SessionState.SqlSessionStateStore.SqlStateConnection..ctor(SqlPartitionInfo sqlPartitionInfo)

Then I started to look into my session db server and did "exec sp_who" in my sql client that found a lot of records of AspState operation in result.

I don't know what causes this kind of problem because we do changed no serious things
in out application, just a few bug fixed.

Here is the detail of my web applications's environments:

asp.net 3.5 (convert from 1.1) ... work very well in
2 servers farm with sqlmode of session state.

Does anyone kwow about this problem or get any idea for investigation?
Thanks

答:
Has your load increased? You might have a lot of connections becuase you have a lot more users using the system. </p>

<p>One thing you can do is optimize your session usage. You can specify if a page uses session state or if it just does a read. This can be a preety big savings if you have pages which don't use or don't modify session. </p>

OwnerDisplayName: tongdee

ContentLicense: CC BY-SA 2.5

Body:
Has your load increased? You might have a lot of connections becuase you have a lot more users using the system.

One thing you can do is optimize your session usage. You can specify if a page uses session state or if it just does a read. This can be a preety big savings if you have pages which don't use or don't modify session.

OwnerDisplayName: Josh


问:
To fault or not to fault
I'm having a discussion with a colleague about when to throw faults and when not to throw faults in a WCF service.

One opinion is, that we only throw faults when the service operation could not do its work due to some error; and something may be in an invalid state because of it. So, some examples:

ValidateMember(string name, string password, string country)
-> would throw a fault if the mandatory parameters are not passed, because the validation itself could not be executed;
-> would throw fault if some internal error occured, like database was down
-> would return a status contract in all other cases, that specifies the result of the validation (MemberValidated, WrongPassword, MemberNotKnown,...)

GetMember(int memberId)
-> would only throw fault if something is down, in all other cases it would return the member or null if not found

The other opinion is that we should also throw faults when GetMember does not find the member, or in the case of ValidateMember the password is wrong.

What do you think?

答:
My opinion is that exceptions/fault should be thrown whenever what the method is supposed to do can't be achieved. So validation logic should never raise exception except if the validation can't be made (i.e. for technical reasons) but never just because the data are not valid (in that case it will return validation codes/messages or anything helping the caller to correct the data).

Now the GetMember case is an interesting one because it's all about semantic. The name of the method suggest that a member can be retrieved by passing an id (compare to a TryGetMember method for exemple). Of course the method should not throw the same exception if the id is nowhere to be found or if the database does not respond but a wrong id passed to this method is probably the sign that something is going wrong somewhere before that call. Except if the user can directly enter a member-id from within the interface in which case a validation should occurred before calling the method.

I hear a lot about the performance issue. I just made a simple test using C# and trow/catch 1000 exceptions. The time it took is 23ms for 1K Exeptions. That's 23µ per exception. I think performance is no longer the first argument here except if you plan to raise more than 2000 exception per second in which case you will have a 5% performance down, which I can start considering.

My humble opinion...

Title: To fault or not to fault


问:
Having issue with Vagrant I cant install any Vagrantbox
I saw scotch.io vagrant box and i was please with it. so i went ahead to download virtualbox and vagrant. also downloaded the scotch.io vagrantfile. but i when i enter the vagrant up in that dir using cmd an pc user.

it gives this error

```<code>C:\Users\Myusername\Desktop\scotch-box-master>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'scotch/box' could not be found. Attempting to find and install...
    default: Box Provider: virtualbox
    default: Box Version: >= 0
The box 'scotch/box' could not be found or
could not be accessed in the remote catalog. If this is a private
box on HashiCorp's Atlas, please verify you're logged in via
`vagrant login`. Also, please double-check the name. The expanded
URL and error message are shown below:

URL: ["https://atlas.hashicorp.com/scotch/box"]
Error:
</code>```

so i tried to install precise64 box it tries to download but it give an error back as follow

```<code>C:\Users\Myusername\Desktop\Vagrant>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'precise64' could not be found. Attempting to find and install...
    default: Box Provider: virtualbox
    default: Box Version: >= 0
==> default: Box file was not detected as metadata. Adding it directly...
==> default: Adding box 'precise64' (v0) for provider: virtualbox
    default: Downloading: http://files.vagrantup.com/precise64.box
    default: Progress: 100% (Rate: 24/s, Estimated time remaining: --:--:--)
An error occurred while downloading the remote file. The error
message, if any, is reproduced below. Please fix this error and try
again.
</code>```

please can some help me fix this error.
so i just downloaded the precise64.tar file how can i install it locally since remote installation is not working

答: I have used vagrant on windows successfully, and it works well with VirtualBox, but there are pitfalls compared to starting with OSX or Linux..  The best advice I found was here: http://tech.osteel.me/posts/2015/01/25/how-to-use-vagrant-on-windows.html For instance I needed to learn to start a command window as administrator and work around the symlink issues especially.  I have used scotchbox on a Mac though and it worked perfectly right out of the box, so fiddling first with the known Windows issues first might get you there?  </p>

Body:
I saw scotch.io vagrant box and i was please with it. so i went ahead to download virtualbox and vagrant. also downloaded the scotch.io vagrantfile. but i when i enter the vagrant up in that dir using cmd an pc user.

it gives this error

C:\Users\Myusername\Desktop\scotch-box-master>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'scotch/box' could not be found. Attempting to find and install...
    default: Box Provider: virtualbox
    default: Box Version: >= 0
The box 'scotch/box' could not be found or
could not be accessed in the remote catalog. If this is a private
box on HashiCorp's Atlas, please verify you're logged in via
`vagrant login`. Also, please double-check the name. The expanded
URL and error message are shown below:

URL: ["https://atlas.hashicorp.com/scotch/box"]
Error:

so i tried to install precise64 box it tries to download but it give an error back as follow

C:\Users\Myusername\Desktop\Vagrant>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Box 'precise64' could not be found. Attempting to find and install...
    default: Box Provider: virtualbox
    default: Box Version: >= 0
==> default: Box file was not detected as metadata. Adding it directly...
==> default: Adding box 'precise64' (v0) for provider: virtualbox
    default: Downloading: http://files.vagrantup.com/precise64.box
    default: Progress: 100% (Rate: 24/s, Estimated time remaining: --:--:--)
An error occurred while downloading the remote file. The error
message, if any, is reproduced below. Please fix this error and try
again.

please can some help me fix this error.
so i just downloaded the precise64.tar file how can i install it locally since remote installation is not working


问:
jQuery, how to replace a div content
I want to replace the div content of class="replaceDiv" with a button, "Delete"

Button:   <input type="button" value="Delete" />
====================================================================

      Delete

      <select class="form-control" name="FISCAL_YEAR_ID">
       <option value="15">FY15</option>
       <option value="16">FY16</option>
       <option value="17">FY17</option>
     </select>

```

答:
You can try both
$('replaceDiv').replaceWith('
 new content
')
$('replaceDiv').html('
 new content
').

It's not clear what you want to do but those should work.

Title: jQuery, how to replace a div content

Body:
You can try both
$('replaceDiv').replaceWith('<p> new content</p>')
$('replaceDiv').html('<p> new content</p>').

It's not clear what you want to do but those should work.


问:
how to insert numeric(10,6) datatype column value in to numeric(8,6) datatype column
I have a table TABLEA with COL1 NUMERIC(8,6) and need to insert a value from second table TABLEB which contains a value 123.000000.I have tried below scenarios.In this case i have to use NVL function and CAST together

```<code>SELECT CAST(899.000000 AS NUMERIC(8,6))-- This gives Numeric overflow.  Value does not fit in a numeric(8,6)
</code>```

Tried below as well

```<code>CAST(NVL(COL1,0) AS NUMERIC(10,6)) -- ERROR:  0 : Numeric value out of range
</code>```

Any insights would be helpful.
Thanks in advance.

答:
An important note:
Decimal/numeric data types in netezza is stored as a floating point value under the covers. Therefore you will not 'waste' any space inside the database if you e.g. go from numeric(7,X) to numeric(14,X) or from numeric(4,X) to numeric(6,X)

Look here for more details on these super low-level data types here: https://www.tutorialspoint.com/cprogramming/c_data_types.htm
Just note that internally the CPU is working on binary data types (base number 2) and most humans use base-10 numbers to discuss these things. Other (more detailed) explanations of this exists on the web, but that is irrelevant for this point :)

Body:
I have a table TABLEA with COL1 NUMERIC(8,6) and need to insert a value from second table TABLEB which contains a value 123.000000.I have tried below scenarios.In this case i have to use NVL function and CAST together

SELECT CAST(899.000000 AS NUMERIC(8,6))-- This gives Numeric overflow.  Value does not fit in a numeric(8,6)

Tried below as well

CAST(NVL(COL1,0) AS NUMERIC(10,6)) -- ERROR:  0 : Numeric value out of range

Any insights would be helpful.
Thanks in advance.


答:
It's unclear from your question what you want to replace it with, but here's an example how it works in general:

$(document).ready(function() {
  $("#x").click(function() {
    $(".replaceDiv").html("blabla");
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="x" value="Delete" />

<div>
  <div class="col-sm-9" align="center">
    <div class="replaceDiv">
      Delete
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-9">
      <select class="form-control" id="FISCAL_YEAR_ID" name="FISCAL_YEAR_ID">
       <option value="15">FY15</option>
       <option value="16">FY16</option>
       <option value="17">FY17</option>
     </select>
    </div>
  </div>
</div></code>```

Title: jQuery, how to replace a div content

Body:
I want to replace the div content of class="replaceDiv" with a button, "Delete"

Button:   <input type="button" value="Delete" />
====================================================================

      Delete

      <select class="form-control" name="FISCAL_YEAR_ID">
       <option value="15">FY15</option>
       <option value="16">FY16</option>
       <option value="17">FY17</option>
     </select>

Body:
It's unclear from your question what you want to replace it with, but here's an example how it works in general:

$(document).ready(function() {
  $("#x").click(function() {
    $(".replaceDiv").html("blabla");
  })
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="x" value="Delete" />

<div>
  <div class="col-sm-9" align="center">
    <div class="replaceDiv">
      <a href="/xyz/delta/12">Delete</a>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-9">
      <select class="form-control" id="FISCAL_YEAR_ID" name="FISCAL_YEAR_ID">
       <option value="15">FY15</option>
       <option value="16">FY16</option>
       <option value="17">FY17</option>
     </select>
    </div>
  </div>
</div>


问:
Unexpected token in angular expression after filter
This expression works..

```<code>"startDate + ' ' + endDate"
</code>```

This also works

```<code>"startDate | date: mediumDate"
</code>```

This however, gives an error.

```<code>"startDate | date + ' ' + endDate"
</code>```

Syntax Error: Token '+' is an unexpected token at column 18 of the expression [startDate | date + ' ' + endDate] starting at [+ ' ' + endDate].

Is it possible to continue the expression after the filter?

EDIT:

My apologies, I copied the wrong expression.

答:
Try adding parentheses like this:
"(startDate | date) + ' ' + endDate"

Body:
This expression works..

"startDate + ' ' + endDate"

This also works

"startDate | date: mediumDate"

This however, gives an error.

"startDate | date + ' ' + endDate"

Syntax Error: Token '+' is an unexpected token at column 18 of the expression [startDate | date + ' ' + endDate] starting at [+ ' ' + endDate].

Is it possible to continue the expression after the filter?

EDIT:

My apologies, I copied the wrong expression.


问:
Is there something wrong with my form?
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?

I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""

I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.

I tried using

```<code><form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
</code>```

and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?

Form code:

```<code>echo '    <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" /><br />
                                              Email: <input name="email" type="text" /><br />
                                              Phone Number: <input name="phone" type="text" /><br /><br />
                                              Comment: <br/>
                                              <textarea name="comment" rows="5" cols="30"></textarea><br /><br />
                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form></div>
                                            <div style="clear:both;"></div><br /><br />';
</code>```

and the vaildator:

```<code>if(isset($_POST['submit'])) {

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
                                                }
                                                if ($errors) {
                                                    echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
                                                    echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
                                                } else {
                                                    mail( "email@hotmail.com", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'<span id="valid">Message has been sent</span><br/>';
                                                }
}
</code>```

答:
A part from the fact that that validator and html code has some big issues inside and things i'd change, what you are asking is: How could i make that the form compiled doesn't remove all the text from my input tags after the refresh.

Basically not knowing anything about your project, where the strings submitted goes, if they are stored in a database or somewhere else, what does that page means inside your project context i cannot write a specific script that makes submitted string remembered in a future reload of the page, but to clarify some things:

If there is a form that is defined as <form></form> and is submitted with a <input type="submit"/> (which should be enough, without giving it a name name="submit") the page is refreshed and it does not automatically remember the input your previously submitted.
To do that you have 2 choice:

Use Ajax (check Jquery as good framework for ajax), which will allow you to submit forms without refreshing the page. I choose it as first way because it is over-used by everyone and it is going to became more and more used because it is new and it works smoothly.

Make a php script that allows you to check if the input has already been submitted; in case the answer is true, then recover the values and get them in this way: <input type="text" value="<?php echo $value ?>"/>.

Also notice that you do not need of '.$_SERVER["PHP_SELF"].'?date='.$date.' since ?date='.$date.' is enough.

Title: Is there something wrong with my form?

Body:
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?

I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""

I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.

I tried using

<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">

and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?

Form code:

echo '

Interested in this coupon? Email us!

                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" />

                                              Email: <input name="email" type="text" />

                                              Phone Number: <input name="phone" type="text" />

                                              Comment:

                                              <textarea name="comment" rows="5" cols="30"></textarea>

                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form>

';

and the vaildator:

if(isset($_POST['submit'])) {

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = 'ERROR: Missing Name
';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = 'ERROR: You must insert a phone number or email
';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = 'ERROR: You must insert a phone number or email
';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = 'ERROR: Please Insert a valid Email
';
                                                }
                                                if ($errors) {
                                                    echo '
There were some errors:
 ';
                                                    echo '

', implode('

', $errors), '

';
                                                } else {
                                                    mail( "email@hotmail.com", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'Message has been sent
';
                                                }
}


问:
Checkbox's value is changed from blank to true when run in cmdline with msiexec
I inherited a setup project, and when I try to run the msi file using msiexec in the commandline, and I leave the property, or specify it to be {}, then it gets changed back to '1' or true.

This is not the case when I run the msi with the GUI. If I leave the checkbox unchecked, it remains unchecked.

Here is an example of what I run in the commandline:

```<code>msiexec.exe /i D:\BeanLocalDev\Development\Setup2015.msi CHKVSEXTENSION={} /QN /L*V D:\BeanLocalDev\Development\Setup2015\Debug\log.txt
</code>```

From the log file:

```<code>MSI (s) (F0:1C) [20:29:42:324]: Doing action:
CustomCheckA_SetProperty_CHECKBOX2
MSI (s) (F0:1C) [20:29:42:325]: Note: 1: 2235 2:  3: ExtendedType 4: SELECT
`Action`,`Type`,`Source`,`Target`, NULL, `ExtendedType` FROM `CustomAction`
WHERE `Action` = 'CustomCheckA_SetProperty_CHECKBOX2'
MSI (s) (F0:1C) [20:29:42:325]: PROPERTY CHANGE: Modifying CHKVSEXTENSION
property. Its current value is '{}'. Its new value: '1'.
Action start 20:29:42: CustomCheckA_SetProperty_CHECKBOX2.
Action ended 20:29:42: CustomCheckA_SetProperty_CHECKBOX2. Return value 1.
</code>```

How do I change this in Visual Studio in the Setup project?

答:
You can't change it directly in the setup project. For some reason VS inserts custom actions to blank the values of the checkboxes early in the UI sequence and execute sequence. It doesn't matter in the UI sequence because it's BEFORE the values are entered, but in the execute sequence it blanks the values from the command line. </p>

<p>This means you'd need to alter the MSI file after the build (for example with Orca). In the InstallExexecuteSequence table there'll be a call to the custom action that resets your property, something like CustomCheckA_SetProperty_CHECKBOX1. If the name of your property is CHKVSEXTENSION then add a condition in the Condition row of NOT CHKVSEXTENSION which means it will reset it only if it's not already been set. </p>

Body:
I inherited a setup project, and when I try to run the msi file using msiexec in the commandline, and I leave the property, or specify it to be {}, then it gets changed back to '1' or true.

This is not the case when I run the msi with the GUI. If I leave the checkbox unchecked, it remains unchecked.

Here is an example of what I run in the commandline:

msiexec.exe /i D:\BeanLocalDev\Development\Setup2015.msi CHKVSEXTENSION={} /QN /L*V D:\BeanLocalDev\Development\Setup2015\Debug\log.txt

From the log file:

MSI (s) (F0:1C) [20:29:42:324]: Doing action:
CustomCheckA_SetProperty_CHECKBOX2
MSI (s) (F0:1C) [20:29:42:325]: Note: 1: 2235 2:  3: ExtendedType 4: SELECT
`Action`,`Type`,`Source`,`Target`, NULL, `ExtendedType` FROM `CustomAction`
WHERE `Action` = 'CustomCheckA_SetProperty_CHECKBOX2'
MSI (s) (F0:1C) [20:29:42:325]: PROPERTY CHANGE: Modifying CHKVSEXTENSION
property. Its current value is '{}'. Its new value: '1'.
Action start 20:29:42: CustomCheckA_SetProperty_CHECKBOX2.
Action ended 20:29:42: CustomCheckA_SetProperty_CHECKBOX2. Return value 1.

How do I change this in Visual Studio in the Setup project?

Body:
You can't change it directly in the setup project. For some reason VS inserts custom actions to blank the values of the checkboxes early in the UI sequence and execute sequence. It doesn't matter in the UI sequence because it's BEFORE the values are entered, but in the execute sequence it blanks the values from the command line.

This means you'd need to alter the MSI file after the build (for example with Orca). In the InstallExexecuteSequence table there'll be a call to the custom action that resets your property, something like CustomCheckA_SetProperty_CHECKBOX1. If the name of your property is CHKVSEXTENSION then add a condition in the Condition row of NOT CHKVSEXTENSION which means it will reset it only if it's not already been set.


问:
Table class not working in css / html
Trying to add a table into the footer of a webpage, and this specific table needs to be 100% wide, black background. Have coded the css and html as below, and doesn't seem to recognise it at all. Anyone know where I'm going wrong?

table.sign {
    width:100%;
    background-color: rgba(0,0,0,0.6);
    align:center;
    border: none;
    padding: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="sign">
  <tr>
    <td>
      <b>Content will go here.</b>
    </td>
  </tr>
</table></code>```

答:
Try using text-align: center; on the td instead of the table</p>

```<code>table.sign {
    width:100%;
    background-color: rgba(0,0,0,0.6);
    border: none;
    padding: 0;
}
td {
    text-align: center;
}
</code>```

Title: Table class not working in css / html

Body:
Trying to add a table into the footer of a webpage, and this specific table needs to be 100% wide, black background. Have coded the css and html as below, and doesn't seem to recognise it at all. Anyone know where I'm going wrong?

table.sign {
    width:100%;
    background-color: rgba(0,0,0,0.6);
    align:center;
    border: none;
    padding: none;
}

      Content will go here.

Body:
Try using text-align: center; on the td instead of the table

table.sign {
    width:100%;
    background-color: rgba(0,0,0,0.6);
    border: none;
    padding: 0;
}
td {
    text-align: center;
}


问:
How to test form submission in React with Jest and Enzyme? Cannot read property 'preventDefault' of undefined
I'm writing a test to check if the error Notification component displays if the login form is submitted with no data.

```<code>describe('User signin', () => {
    it('should fail if no credentials are provided', () => {
        const loginComponent = shallow(<Login />);
        expect(loginComponent.find('.form-login').length).toBe(1);
        loginComponent.find('.form-login').simulate('submit');
        expect(loginComponent.find(Notification).length).toBe(1);
    });
});
</code>```

It looks like the .simulate is working as the test reaches my handleSubmit function, however I am running into this error in the test:

TypeError: Cannot read property 'preventDefault' of undefined

The handleSubmit function

```<code>handleSubmit(e) {
    e.preventDefault();  // <-- problem here
    const user = this.state.username;
    const pass = this.state.password;
    const gotoDashboard = () => this.props.history.push('/dashboard');

    const postLogin = (user, pass) => {
        api.userLogin(user, pass)
</code>```

My test will past if I remove the e.preventDefault(); line, however I need that line in there to prevent the default form submission event.

答:
Figured it out quickly... I just needed to create a fakeEvent with a fake preventDefault function and pass it along:</p>

```<code>describe('User signin', () => {
    it('should fail if no credentials are provided', () => {
        const fakeEvent = { preventDefault: () => console.log('preventDefault') };
        const loginComponent = shallow(<Login />);
        expect(loginComponent.find('.form-login').length).toBe(1);
        loginComponent.find('.form-login').simulate('submit', fakeEvent);
        expect(loginComponent.find(Notification).length).toBe(1);
    });
});
</code>```

Body:
I'm writing a test to check if the error Notification component displays if the login form is submitted with no data.

describe('User signin', () => {
    it('should fail if no credentials are provided', () => {
        const loginComponent = shallow(<Login />);
        expect(loginComponent.find('.form-login').length).toBe(1);
        loginComponent.find('.form-login').simulate('submit');
        expect(loginComponent.find(Notification).length).toBe(1);
    });
});

It looks like the .simulate is working as the test reaches my handleSubmit function, however I am running into this error in the test:

TypeError: Cannot read property 'preventDefault' of undefined

The handleSubmit function

handleSubmit(e) {
    e.preventDefault();  // <-- problem here
    const user = this.state.username;
    const pass = this.state.password;
    const gotoDashboard = () => this.props.history.push('/dashboard');

    const postLogin = (user, pass) => {
        api.userLogin(user, pass)

My test will past if I remove the e.preventDefault(); line, however I need that line in there to prevent the default form submission event.

Body:
Figured it out quickly... I just needed to create a fakeEvent with a fake preventDefault function and pass it along:

describe('User signin', () => {
    it('should fail if no credentials are provided', () => {
        const fakeEvent = { preventDefault: () => console.log('preventDefault') };
        const loginComponent = shallow(<Login />);
        expect(loginComponent.find('.form-login').length).toBe(1);
        loginComponent.find('.form-login').simulate('submit', fakeEvent);
        expect(loginComponent.find(Notification).length).toBe(1);
    });
});


问:
draggable and droppable jquery socket.io
With the use of "Jquery" I have been trying to make a simple drag and drop system. The "Jquery" drag and drop system I want to make works very well. It is created with a draggable and droppable function. Like shown here.

$(function() {
$( ".this-div" ).draggable({
        grid: [ 5, 5 ],
       appendTo: '#droppable',
        containment: $('#droppable'),
       cursor: 'hand',
        tolerance: 'fit',
       revertDuration: 100,
       revert: 'invalid',
        helper: 'clone'

    });

    $( "#droppable" ).droppable({
        accept: ".this-div",
            drop: function( event, ui ) {
                ui.helper.clone().appendTo('#droppable');
     }
});
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
margin: 0;
padding: 0;
}

html,body{
width: 100%;
height: 100%;
}

#droppable{
width: 80%;
height: 100%;
float: left;
border: 1px solid black;
}

.this-div{
width: 100px;
text-align: center;
padding: 2px;
height: 100px;
background-color: #444;
color: #fff;
font-family: sans-serif;
}

aside{
float: left;
}</code>```

<!DOCTYPE html>

        <title>Draggable and droppable - Jquery and Socket.io</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

Test

```

The result can be seen as picture here. click here to see picture.

Now what I want to know, is the easiest way to emit the drop of a cloned div in the droppable section to other clients. The target is to make all connected users on the page see the dropped clone in realtime. I have been searching for an example to get an idea about how to make this, all over the internet and found nothing useable, beside this Socket.IO and Complex JSON with Node.js, jQuery, so i know it's possible to move a div around in realtime, but is it possible to clone in realtime? In some how I think I will need to save the position of the dropped clone like drikk0 does, in the sample linked over here. So to make it short, what I want is people to drag and drop a clone which in realtime will be seen by all other connected users. But my problem is that I can't figure out how to do it in the best possible way, with a combination of jquery and socket.io.

Thanks in advance.

答:
(this is not the final solution but just a step on the right way)

After some research and work, I come up with this pretty simple solution on getting the individual position on the single dropped clone. Now what I need to understand is how I can send this position each time a clone is dropped (into the droppable section) to a Mysqli Database (or something like). So that I can save the change and show it to all connected users, in realtime. Here you can see what I have so far.

$(function(){

        $(".this-div").draggable({
            grid: [ 5, 5 ],
            appendTo: '#droppable',
            containment: $('#droppable'),
            cursor: 'hand',
            tolerance: 'fit',
            revertDuration: 100,
            revert: 'invalid',
            helper: 'clone'
        });

        $("#droppable").droppable({
          accept: '.this-div',

          drop: function(event, ui) {
            ui.helper.clone().appendTo('#droppable');

            leftPosition  = ui.offset.left - $(this).offset().left;
            topPosition   = ui.offset.top - $(this).offset().top;

            //Debug current dropped position
            $("#top").val(topPosition);
            $("#left").val(leftPosition);
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>*{
margin: 0;
padding: 0;
}

html,body{
width: 100%;
height: 100%;
}

#droppable{
width: 80%;
height: 100%;
float: left;
border: 1px solid black;
}

.this-div{
width: 100px;
text-align: center;
padding: 2px;
height: 100px;
background-color: #444;
color: #fff;
font-family: sans-serif;
}

aside{
float: left;
}</code>```

        <title>Pass Jquery Drop To MYSQLI DB</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <input id="top" value="Top Position">
        <input id="left" value="Left Position">

Test

```

Thanks in advance!

Body:
With the use of "Jquery" I have been trying to make a simple drag and drop system. The "Jquery" drag and drop system I want to make works very well. It is created with a draggable and droppable function. Like shown here.

$(function() {
$( ".this-div" ).draggable({
        grid: [ 5, 5 ],
       appendTo: '#droppable',
        containment: $('#droppable'),
       cursor: 'hand',
        tolerance: 'fit',
       revertDuration: 100,
       revert: 'invalid',
        helper: 'clone'

    });

    $( "#droppable" ).droppable({
        accept: ".this-div",
            drop: function( event, ui ) {
                ui.helper.clone().appendTo('#droppable');
     }
});
});

*{
margin: 0;
padding: 0;
}

html,body{
width: 100%;
height: 100%;
}

#droppable{
width: 80%;
height: 100%;
float: left;
border: 1px solid black;
}

.this-div{
width: 100px;
text-align: center;
padding: 2px;
height: 100px;
background-color: #444;
color: #fff;
font-family: sans-serif;
}

aside{
float: left;
}

<!DOCTYPE html>

        <title>Draggable and droppable - Jquery and Socket.io</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

Test

The result can be seen as picture here. click here to see picture.

Now what I want to know, is the easiest way to emit the drop of a cloned div in the droppable section to other clients. The target is to make all connected users on the page see the dropped clone in realtime. I have been searching for an example to get an idea about how to make this, all over the internet and found nothing useable, beside this Socket.IO and Complex JSON with Node.js, jQuery, so i know it's possible to move a div around in realtime, but is it possible to clone in realtime? In some how I think I will need to save the position of the dropped clone like drikk0 does, in the sample linked over here. So to make it short, what I want is people to drag and drop a clone which in realtime will be seen by all other connected users. But my problem is that I can't figure out how to do it in the best possible way, with a combination of jquery and socket.io.

Thanks in advance.

Body:
(this is not the final solution but just a step on the right way)

After some research and work, I come up with this pretty simple solution on getting the individual position on the single dropped clone. Now what I need to understand is how I can send this position each time a clone is dropped (into the droppable section) to a Mysqli Database (or something like). So that I can save the change and show it to all connected users, in realtime. Here you can see what I have so far.

$(function(){

        $(".this-div").draggable({
            grid: [ 5, 5 ],
            appendTo: '#droppable',
            containment: $('#droppable'),
            cursor: 'hand',
            tolerance: 'fit',
            revertDuration: 100,
            revert: 'invalid',
            helper: 'clone'
        });

        $("#droppable").droppable({
          accept: '.this-div',

          drop: function(event, ui) {
            ui.helper.clone().appendTo('#droppable');

            leftPosition  = ui.offset.left - $(this).offset().left;
            topPosition   = ui.offset.top - $(this).offset().top;

            //Debug current dropped position
            $("#top").val(topPosition);
            $("#left").val(leftPosition);
        }
    });
});

*{
margin: 0;
padding: 0;
}

html,body{
width: 100%;
height: 100%;
}

#droppable{
width: 80%;
height: 100%;
float: left;
border: 1px solid black;
}

.this-div{
width: 100px;
text-align: center;
padding: 2px;
height: 100px;
background-color: #444;
color: #fff;
font-family: sans-serif;
}

aside{
float: left;
}

<html>
    <head>
        <title>Pass Jquery Drop To MYSQLI DB</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <!-- Jquery Implimentation -->
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>
    <body>
        <input id="top" value="Top Position">
        <input id="left" value="Left Position">
        <section id="droppable"></section>
        <aside>
            <div class="this-div">Test</div>
        </aside>
    </body>
</html>

Thanks in advance!


问:
Node + Connect + WebSockets
I am looking for a WebSockets lib/middleware for connect

The one I found so far is Socket.IO-connect however it uses patched version of Connect.

This is an issue mainly due to the separation of patched version of Connect from the main branch.

Can you recommend a good library?

答:
You do not need a connect middleware for socket.io, and infact it's probably not the best way to go about using socket.io with connect. Here is what I do:</p>

```<code>var connect = require('connect');
var io = require('socket.io');

var server = connect.createServer(
  connect.router(function(app) {
    app.get('/', function(req, res, next) {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end(fs.readFileSync(__dirname + '/assets/index.html', 'utf8'));
      // above file contains <script src="/socket.io/socket.io.js" type="text/javascript"></script>
    });
  })
).listen(80);

var socket = io.listen(server);
socket.on('connection', function(client) {
  client.on('message', function(message) {console.log(message)});
  client.on('disconnect', function() {});
});
</code>```

Title: Node + Connect + WebSockets

Body:
You do not need a connect middleware for socket.io, and infact it's probably not the best way to go about using socket.io with connect. Here is what I do:

var connect = require('connect');
var io = require('socket.io');

var server = connect.createServer(
  connect.router(function(app) {
    app.get('/', function(req, res, next) {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.end(fs.readFileSync(__dirname + '/assets/index.html', 'utf8'));
      // above file contains <script src="/socket.io/socket.io.js" type="text/javascript"></script>
    });
  })
).listen(80);

var socket = io.listen(server);
socket.on('connection', function(client) {
  client.on('message', function(message) {console.log(message)});
  client.on('disconnect', function() {});
});


问:
drain array values in the url
Array

```<code>var array = [
    {
        item: "abcd1234",
        data: "something"
    },
    {
        item: "4321dcba",
        data: "something"
    },
];
</code>```

Array length can be randomly from 1 to 10

I'm making http request for all these items.

```<code>array.forEach(function(item) {

    var url = "www.something.com?id=" + item.item;

    //making request

});
</code>```

Now I need 1 - 10 requests per array depends on a array length.

Lets say I have 10 arrays with 10 elements in it. Its 100 requests.

I could do this with only 1 request per array if I use url like this

www.something.com?id=abcd1234&id2=4321dcba

How do I loop all array values to the url if I don't know how many elements there is?

答:
```<code>var url = "www.something.com?"+items.map((item,id)=>"id"+((id||-1)+1)+"="+item.item).join("&");
</code>```

You can map each item to its query parameter, and then join with the &...

Title: drain array values in the url

Body:
Array

var array = [
    {
        item: "abcd1234",
        data: "something"
    },
    {
        item: "4321dcba",
        data: "something"
    },
];

Array length can be randomly from 1 to 10

I'm making http request for all these items.

array.forEach(function(item) {

    var url = "www.something.com?id=" + item.item;

    //making request

});

Now I need 1 - 10 requests per array depends on a array length.

Lets say I have 10 arrays with 10 elements in it. Its 100 requests.

I could do this with only 1 request per array if I use url like this

www.something.com?id=abcd1234&id2=4321dcba

How do I loop all array values to the url if I don't know how many elements there is?

Body:
var url = "www.something.com?"+items.map((item,id)=>"id"+((id||-1)+1)+"="+item.item).join("&");

You can map each item to its query parameter, and then join with the &...


问:
Conditional Panel based on number of user selected inputs
I am trying to get a different number of fields to populate based on the number of entries selected in a selectInput with multiple = TRUE.  So if 1 entry from the "numfields" input is selected, the first conditionalPanel appears, and so on. What I have now shows the inputs I want to be conditional without any user input.

```<code>  a <- c("A","B","C")

  Choices <- as.character(a)

  ui <- fluidPage(
    fluidRow(
      selectInput(inputId = "numfields", label = "Select Entries", choices = Choices, multiple = TRUE, selectize = TRUE),
      conditionalPanel(
          condition = "count(input$numfields) >= 1",
          textInput(inputId = "field1", label = "First One", value = "")
        ),
      conditionalPanel(
        condition = "count(input$numfields) >= 2",
        textInput(inputId = "field2", label = "Second One", value = "")
      ),
      conditionalPanel(
        condition = "count(input$numfields) >= 3",
        textInput(inputId = "field3", label = "Third One", value = "")
      )
      )
    )

  server <- function(input, output, session)
  {}

  shinyApp(ui=ui, server=server)
</code>```

Also, on a related note, Shiny automatically defaults to have no entries selected for selectInput fields where multiple = TRUE.  Is there a way to have it select the first entry like it does when multiple = FALSE?

Any help is appreciated, thank you.

答:
Here another solution via the server.
The obvious solution would be renderUI(), but if you want to use condtionalPanel():

```<code>a <- c("A","B","C")

Choices <- as.character(a)

ui <- fluidPage(
  fluidRow(
    selectInput(inputId = "numfields", label = "Select Entries", choices = Choices, multiple = TRUE, selectize = TRUE),
    conditionalPanel(
      condition = "output.check > 0",
      textInput(inputId = "field1", label = "First One", value = "")
    ),
    conditionalPanel(
      condition = "output.check >= 2",
      textInput(inputId = "field2", label = "Second One", value = "")
    ),
    conditionalPanel(
      condition = "output.check >= 3",
      textInput(inputId = "field3", label = "Third One", value = "")
    )
  )
)

server <- function(input, output, session){

  output$check <- reactive({
    length(input$numfields)
  })

  outputOptions(output, 'check', suspendWhenHidden=FALSE)
}

shinyApp(ui=ui, server=server)
</code>```

Body:
I am trying to get a different number of fields to populate based on the number of entries selected in a selectInput with multiple = TRUE.  So if 1 entry from the "numfields" input is selected, the first conditionalPanel appears, and so on. What I have now shows the inputs I want to be conditional without any user input.

  a <- c("A","B","C")

  Choices <- as.character(a)

  ui <- fluidPage(
    fluidRow(
      selectInput(inputId = "numfields", label = "Select Entries", choices = Choices, multiple = TRUE, selectize = TRUE),
      conditionalPanel(
          condition = "count(input$numfields) >= 1",
          textInput(inputId = "field1", label = "First One", value = "")
        ),
      conditionalPanel(
        condition = "count(input$numfields) >= 2",
        textInput(inputId = "field2", label = "Second One", value = "")
      ),
      conditionalPanel(
        condition = "count(input$numfields) >= 3",
        textInput(inputId = "field3", label = "Third One", value = "")
      )
      )
    )

  server <- function(input, output, session)
  {}

  shinyApp(ui=ui, server=server)

Also, on a related note, Shiny automatically defaults to have no entries selected for selectInput fields where multiple = TRUE.  Is there a way to have it select the first entry like it does when multiple = FALSE?

Any help is appreciated, thank you.

Body:
Here another solution via the server.
The obvious solution would be renderUI(), but if you want to use condtionalPanel():

a <- c("A","B","C")

Choices <- as.character(a)

ui <- fluidPage(
  fluidRow(
    selectInput(inputId = "numfields", label = "Select Entries", choices = Choices, multiple = TRUE, selectize = TRUE),
    conditionalPanel(
      condition = "output.check > 0",
      textInput(inputId = "field1", label = "First One", value = "")
    ),
    conditionalPanel(
      condition = "output.check >= 2",
      textInput(inputId = "field2", label = "Second One", value = "")
    ),
    conditionalPanel(
      condition = "output.check >= 3",
      textInput(inputId = "field3", label = "Third One", value = "")
    )
  )
)

server <- function(input, output, session){

  output$check <- reactive({
    length(input$numfields)
  })

  outputOptions(output, 'check', suspendWhenHidden=FALSE)
}

shinyApp(ui=ui, server=server)


答:
You can use the reduce() method:

const array = [
  {
    item: "abcd1234",
    data: "something"
  },
  {
    item: "4321dcba",
    data: "something"
  }
];
const url = array.reduce(
  (acc, x, i) => acc + (i === 0 ? `?id=${x.item}` : `&id${i + 1}=${x.item}`),
  'www.something.com'
);
console.log(url);```
</div>
</div>
</p>

<p>If your array looks like <code>["abcd1234", "4321dcba"]</code>, try this:</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>const array = ['abcd1234', '4321dcba'];
const url = array.reduce(
  (acc, x, i) => acc + (i === 0 ? `?id=${x}` : `&id${i + 1}=${x}`),
  'www.something.com'
);
console.log(url);</code>```

Title: drain array values in the url

Body:
You can use the reduce() method:

const array = [
  {
    item: "abcd1234",
    data: "something"
  },
  {
    item: "4321dcba",
    data: "something"
  }
];
const url = array.reduce(
  (acc, x, i) => acc + (i === 0 ? `?id=${x.item}` : `&id${i + 1}=${x.item}`),
  'www.something.com'
);
console.log(url);

If your array looks like ["abcd1234", "4321dcba"], try this:

const array = ['abcd1234', '4321dcba'];
const url = array.reduce(
  (acc, x, i) => acc + (i === 0 ? `?id=${x}` : `&id${i + 1}=${x}`),
  'www.something.com'
);
console.log(url);


问:
AWS Add Account Error
First of all I am new to spinnaker so I am still learning the ropes.  Said that, I'm adding an account to the aws provider like this:

hal config provider aws account add ServiceAccountSpinnaker \
   --account-id XXXXXXXXXXX \
   --assume-role role/spinnakerManaged

where the XXXXXXXXXXX is my actual account ID, i've created a user account named
ServiceAccountSpinnaker with a configured role of spinnakerManaged,

All as specified in Spinnaker Documentation:

https://www.spinnaker.io/setup/providers/aws/

After executing the Hal command here's what I am getting back:

Get current deployment   Success

Add the ServiceAccountSpinnaker account   Failure Problems in default.provider.aws.ServiceAccountSpinnaker: ! ERROR Account name
  must match pattern   ^[a-z0-9]+([-a-z0-9_]*[a-z0-9])?$ ? It must start
  and end with a lower-case character or number, and   only container
  lower-case character, numbers, dashes, or underscores

WARNING No validation for the AWS provider has been   implemented.

Failed to add account ServiceAccountSpinnaker for provider   aws.

So basically I have a problem with the account name, some enlightening is actually needed, since I've spent as an idiot, 45 minutes trying so many combinations to a simple thing.

I appreciate the help.

EN

答:
Absolutely right, so the answer is based on two facts,
1. this account name is only relevant within Spinnaker.
2. Changed my Account name from ServiceAccountSpinnaker to serviceaccountspinnaker

then I succeeded on adding an account.

Title: AWS Add Account Error


问:
What is the git log pretty format placeholder that will show the same as the --source option?
I can use the --source option to show me one of the branches that each git commit listed is on, for example

```<code>git log --branches --author=Tim --since='February' --decorate --oneline --source
</code>```

shows me all my commits since February and one of the branches that the commit can be reached from. Here's how the output looks for me

I'd like to add in the date do I have swapped to using the --pretty option:

```<code>git log --branches --author=Tim --since=February --pretty=format:"%C(yellow)%h%Creset %Cred%d%Creset %C(cyan)%ar%Creset : %s"
</code>```

and the corresponding output

The pretty format placeholder %d adds the "ref names, like the --decorate option" (from the documentation here). What is the pretty format placeholder to include the ref name by which each commit was reached, like the --source option?

答:
What is the pretty format placeholder to include the ref name by which each commit was reached, like the --source option?

There isn't one.  The --source option sets a flag that makes the revision walk add the appropriate command-line reference name to each commit the first time the commit is reached.  The same flag is tested, and the saved information shown directly to a stdio stream, in show_decorations in log-tree.c, but nothing in pretty.c uses that field.

(Other code uses ->util but for other purposes, hence the field name, util.  Note that it should be fairly easy to add a new format character that expands to the util field if saved, but you'd still have to set the flag.)

Body:
I can use the --source option to show me one of the branches that each git commit listed is on, for example

git log --branches --author=Tim --since='February' --decorate --oneline --source

shows me all my commits since February and one of the branches that the commit can be reached from. Here's how the output looks for me

I'd like to add in the date do I have swapped to using the --pretty option:

git log --branches --author=Tim --since=February --pretty=format:"%C(yellow)%h%Creset %Cred%d%Creset %C(cyan)%ar%Creset : %s"

and the corresponding output

The pretty format placeholder %d adds the "ref names, like the --decorate option" (from the documentation here). What is the pretty format placeholder to include the ref name by which each commit was reached, like the --source option?


问:
BigQuery load_table_from_storage won't recognize uri
I'm running into the following error when trying to load a table from google cloud storage:
BadRequest: 400 Load configuration must specify at least one source URI (POST https://www.googleapis.com/bigquery/v2/projects/fansidata/jobs)

Meanwhile my uri is valid (ie: i can see it in the gcs web app)

```<code>uris = ['gs://my-bucket-name/datastore_backup_analytics_2016_12_21_2_User/1569751766512529035929A5AA9742/output-0']

job_name = 'Load_User'
destinationTable = dataset.table('Transfer')
job = bigquery_client.load_table_from_storage(job_name, destinationTable, uris)
job.begin()
</code>```

答:
Client.load_table_from_storage takes one or more source URIs (that is what *soure_uris means in python).  E.g.:

```<code>job = client.load_table_from_storage(
    'load-job-123', my_table_object,
    'gs://my-bucket-name/table_one',
    'gs://my-bucket-name/table_two')
</code>```

Body:
I'm running into the following error when trying to load a table from google cloud storage:
BadRequest: 400 Load configuration must specify at least one source URI (POST https://www.googleapis.com/bigquery/v2/projects/fansidata/jobs)

Meanwhile my uri is valid (ie: i can see it in the gcs web app)

uris = ['gs://my-bucket-name/datastore_backup_analytics_2016_12_21_2_User/1569751766512529035929A5AA9742/output-0']

job_name = 'Load_User'
destinationTable = dataset.table('Transfer')
job = bigquery_client.load_table_from_storage(job_name, destinationTable, uris)
job.begin()

Body:
Client.load_table_from_storage takes one or more source URIs (that is what *soure_uris means in python).  E.g.:

job = client.load_table_from_storage(
    'load-job-123', my_table_object,
    'gs://my-bucket-name/table_one',
    'gs://my-bucket-name/table_two')


问:
WebException in getResponse()
here my code-

```<code>private string HttpContent(string url)
{
    WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
    StreamReader sr = new StreamReader(objRequest.GetResponse().GetResponseStream());
    string result = sr.ReadToEnd();
    sr.Close();
    return result;
}
</code>```

exception comes in 2nd line in objRequest.GetResponse(). If I open it quick watch window I get:

'objRequest.GetResponse()' threw an exception of type 'System.Net.WebException'

    "The remote server returned an error:(404) Not Found."

答:
the problem is that the path [url] is incorrect you pass to method().

the URL may be not well form or check the url that 's work or not. if you not sure that's should always correct then you can use try catch if you want.

Title: WebException in getResponse()

Body:
here my code-

private string HttpContent(string url)
{
    WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
    StreamReader sr = new StreamReader(objRequest.GetResponse().GetResponseStream());
    string result = sr.ReadToEnd();
    sr.Close();
    return result;
}

exception comes in 2nd line in objRequest.GetResponse(). If I open it quick watch window I get:

'objRequest.GetResponse()' threw an exception of type 'System.Net.WebException'

    "The remote server returned an error:(404) Not Found."

OwnerDisplayName: Steven Spielberg


问:
Unable to add remote source with Vora 1.4 and Spark controller 2.0
I have been try to connect Vora 1.4 to HANA 1.0 SPS12 through Spark controller 2.0. Remote source can be added to HANA studio but Vora tables are invisible. When trying to refresh remote source, a class not found error appears in Spark controller error log. Following are the error messages:

*

17/05/23 10:11:46 ERROR HanaSQLContext: Failed to set up Exended Store
  java.lang.ClassNotFoundException: at java.lang.Class.forName0(Native
  Method) at java.lang.Class.forName(Class.java:264) at
  org.apache.spark.sql.hana.hdfs.store.HDFSStore$$anonfun$apply$2.apply(HDFSSt>ore.scala:212)
  at
  org.apache.spark.sql.hana.hdfs.store.HDFSStore$$anonfun$apply$2.apply(HDFSSt>ore.scala:187)
  at scala.Option.getOrElse(Option.scala:120) at
  org.apache.spark.sql.hana.hdfs.store.HDFSStore$.apply(HDFSStore.scala:186)
  at
  org.apache.spark.sql.hana.HanaSQLContext.getExtendedStore(HanaSQLContext.sca>la:104)
  at
  com.sap.hana.spark.core.session.Session.(SessionManager.scala:191)
  at
  com.sap.hana.spark.core.session.Session.(SessionManager.scala:166)
  at
  com.sap.hana.spark.core.session.Session$.apply(SessionManager.scala:136)
  at
  com.sap.hana.spark.core.session.SessionManager$.startNewSession(SessionManag>er.scala:72)
  at
  com.sap.hana.spark.network.CommandHandler$$anonfun$receive$3.applyOrElse(Com>mandRouter.scala:549)
  at akka.actor.Actor$class.aroundReceive(Actor.scala:467) at
  com.sap.hana.spark.network.CommandHandler.aroundReceive(CommandRouter.scala:>432)
  at akka.actor.ActorCell.receiveMessage(ActorCell.scala:516) at
  akka.actor.ActorCell.invoke(ActorCell.scala:487) at
  akka.dispatch.Mailbox.processMailbox(Mailbox.scala:238) at
  akka.dispatch.Mailbox.run(Mailbox.scala:220) at
  akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDis>patcher.scala:397)
  at
  scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
  at
  scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1>339)
  at
  scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
  at
  scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java>:107)

*

Any one has any idea?

Thanks!

答:
To troubleshooting the issue, I uninstalled Spark controller 2.0 and installed Spark controller 1.6. There are no more error message in Spark controller error log. But the issue remains, the Vora tables are invisible from remote source in HANA studio. There is no error in index server log on HANA side either. It seems that Vora 1.4 has serious problem with Spark controller as 1.4 is not on the any version of Spark controller compatibility matrix. I am hoping that someone already found a fix for this.

Spark controller 1.6 log:

```<code>SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/usr/hdp/2.5.3.0-37/spark/lib/spark-assembly-1.6.2.2.5.3.0-37-hadoop2.7.3.2.5.3.0-37.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/hdp/2.5.3.0-37/hadoop/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
 INFO [main] (HanaESConfig.scala:67) - Loaded HANA Extended Store Configuration
Found Spark Libraries. Proceeding with Current Class Path
17/06/07 13:20:48 INFO Server: Starting Spark Controller
17/06/07 13:21:01 INFO CommandRouterDefault: Connecting to Vora Engine
17/06/07 13:21:01 INFO CommandRouterDefault: Initialized Router!
17/06/07 13:21:01 INFO CommandRouterDefault: Server started
17/06/07 13:21:28 INFO VoraClientFactory: returning a Vora catalog client of this Vora catalog server: bdesxi14.localdomain:20298
17/06/07 13:21:28 INFO CatalogFactory: returning a Vora catalog client of this Vora catalog server: bdesxi14.localdomain:20298
17/06/07 13:21:28 INFO CBinder: searching for compat-sap-c++.so at /opt/rh/SAP/lib64/compat-sap-c++.so
17/06/07 13:21:28 INFO CBinder: loading compat package from /opt/rh/SAP/lib64/compat-sap-c++.so
17/06/07 13:21:28 INFO CBinder: searching for libpam.so.0 at /lib64/libpam.so.0
17/06/07 13:21:28 INFO CBinder: loading libpam.so.0 from /lib64/libpam.so.0
17/06/07 13:21:28 INFO CBinder: loading library libprotobuf.so
17/06/07 13:21:28 INFO CBinder: loading library libprotoc.so
17/06/07 13:21:28 INFO CBinder: loading library libtbbmalloc.so
17/06/07 13:21:28 INFO CBinder: loading library libtbb.so
17/06/07 13:21:28 INFO CBinder: loading library libkrb5support.so
17/06/07 13:21:28 INFO CBinder: loading library libk5crypto.so
17/06/07 13:21:28 INFO CBinder: loading library libcom_err.so
17/06/07 13:21:28 INFO CBinder: loading library libkrb5.so
17/06/07 13:21:28 INFO CBinder: loading library libgsasl.so
17/06/07 13:21:28 INFO CBinder: loading library libgssapi_krb5.so
17/06/07 13:21:28 INFO CBinder: loading library libgssrpc.so
17/06/07 13:21:28 INFO CBinder: loading library libv2runtime.so
17/06/07 13:21:28 INFO CBinder: loading library libv2auth.so
17/06/07 13:21:28 INFO CBinder: loading library libv2net.so
17/06/07 13:21:28 INFO CBinder: loading library libv2catalog_connector.so
</code>```

Body:
To troubleshooting the issue, I uninstalled Spark controller 2.0 and installed Spark controller 1.6. There are no more error message in Spark controller error log. But the issue remains, the Vora tables are invisible from remote source in HANA studio. There is no error in index server log on HANA side either. It seems that Vora 1.4 has serious problem with Spark controller as 1.4 is not on the any version of Spark controller compatibility matrix. I am hoping that someone already found a fix for this.

Spark controller 1.6 log:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/usr/hdp/2.5.3.0-37/spark/lib/spark-assembly-1.6.2.2.5.3.0-37-hadoop2.7.3.2.5.3.0-37.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/hdp/2.5.3.0-37/hadoop/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
 INFO [main] (HanaESConfig.scala:67) - Loaded HANA Extended Store Configuration
Found Spark Libraries. Proceeding with Current Class Path
17/06/07 13:20:48 INFO Server: Starting Spark Controller
17/06/07 13:21:01 INFO CommandRouterDefault: Connecting to Vora Engine
17/06/07 13:21:01 INFO CommandRouterDefault: Initialized Router!
17/06/07 13:21:01 INFO CommandRouterDefault: Server started
17/06/07 13:21:28 INFO VoraClientFactory: returning a Vora catalog client of this Vora catalog server: bdesxi14.localdomain:20298
17/06/07 13:21:28 INFO CatalogFactory: returning a Vora catalog client of this Vora catalog server: bdesxi14.localdomain:20298
17/06/07 13:21:28 INFO CBinder: searching for compat-sap-c++.so at /opt/rh/SAP/lib64/compat-sap-c++.so
17/06/07 13:21:28 INFO CBinder: loading compat package from /opt/rh/SAP/lib64/compat-sap-c++.so
17/06/07 13:21:28 INFO CBinder: searching for libpam.so.0 at /lib64/libpam.so.0
17/06/07 13:21:28 INFO CBinder: loading libpam.so.0 from /lib64/libpam.so.0
17/06/07 13:21:28 INFO CBinder: loading library libprotobuf.so
17/06/07 13:21:28 INFO CBinder: loading library libprotoc.so
17/06/07 13:21:28 INFO CBinder: loading library libtbbmalloc.so
17/06/07 13:21:28 INFO CBinder: loading library libtbb.so
17/06/07 13:21:28 INFO CBinder: loading library libkrb5support.so
17/06/07 13:21:28 INFO CBinder: loading library libk5crypto.so
17/06/07 13:21:28 INFO CBinder: loading library libcom_err.so
17/06/07 13:21:28 INFO CBinder: loading library libkrb5.so
17/06/07 13:21:28 INFO CBinder: loading library libgsasl.so
17/06/07 13:21:28 INFO CBinder: loading library libgssapi_krb5.so
17/06/07 13:21:28 INFO CBinder: loading library libgssrpc.so
17/06/07 13:21:28 INFO CBinder: loading library libv2runtime.so
17/06/07 13:21:28 INFO CBinder: loading library libv2auth.so
17/06/07 13:21:28 INFO CBinder: loading library libv2net.so
17/06/07 13:21:28 INFO CBinder: loading library libv2catalog_connector.so


问:
ruby hash block in ': undefined method `[]='
This works using the hash.update method:

```<code>[4, 8, 15, 16, 23, 42].inject({}) { |a, i| a.update(i => i) }
</code>```

But this snippet using a[i] = i:

```<code>[4, 8, 15, 16, 23, 42].inject({}) { |a, i| a[i] = i }
</code>```

Results in the following error:

```<code><code>NoMethodError: undefined method \`[]=' for 4:Integer
Did you mean?  []
    from (irb):1:in \`block in irb_binding'>
    from (irb):1:in \`each'
    from (irb):1:in \`inject'
    from (irb):1
</code>
</code>```

Would someone please explain to me why I get this error? Thanks.

答:
Block should return accumulator:

```<code>[4, 8, 15, 16, 23, 42].inject({}) { |a, i| a[i] = i; a }
#=> {4=>4, 8=>8, 15=>15, 16=>16, 23=>23, 42=>42}
</code>```

This is how inject works. The first instance works because Hash#update returns updated hash.

Title: ruby hash block in <main>': undefined method `[]='

Body:
This works using the hash.update method:

[4, 8, 15, 16, 23, 42].inject({}) { |a, i| a.update(i => i) }

But this snippet using a[i] = i:

[4, 8, 15, 16, 23, 42].inject({}) { |a, i| a[i] = i }

Results in the following error:

NoMethodError: undefined method \`[]=' for 4:Integer
Did you mean?  []
    from (irb):1:in \`block in irb_binding'>
    from (irb):1:in \`each'
    from (irb):1:in \`inject'
    from (irb):1

Would someone please explain to me why I get this error? Thanks.

Body:
Block should return accumulator:

[4, 8, 15, 16, 23, 42].inject({}) { |a, i| a[i] = i; a }
#=> {4=>4, 8=>8, 15=>15, 16=>16, 23=>23, 42=>42}

This is how inject works. The first instance works because Hash#update returns updated hash.