问:
how do vertically align login form between banner and footer
Given I have the html and css in the snippet below the question, how can I vertically centre the login view no matter what screen height is?

I have tried this for the .login-layout__positioner class:

```<code>.login-layout__positioner {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;

    top: 42%;
    transform: translateY(-42%);
}
</code>```

But this does not centre well in large screen heights?

Is there a better way?

body {
  height: 100%;
  background-color: #f7f7f4;
}

.app-layout__body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.app-layout__container {
  flex: 1 0 auto;
}

.banner__container {
  background-color: #fff
}

.banner__top {
  padding-top: 15px;
}

.login-layout__container {
  background-color: #f7f7f4;
  width: 100%;
}

.login-layout__positioner {
  text-align: center;
  margin: auto;
}

footer {
  background-color: #0065bd;
}

a {
  color: #fff;
}

ul {
  list-style: none;
  margin-left: 0;
}

li {
  display: inline;
}

.form__group {
  background-color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="root">
    <div class="main-content">
      <div class="app-layout__body">
        <div class="app-layout__container">
          <div class="banner__container">
            <div class="banner__top">
              <div>
                <div>
                  <h2>Banner</h2></div>
              </div>
            </div>
          </div>
          <div class="login-layout__container">
            <div class="login-layout__positioner">
              <div class="form__group">
                <div>
                  <form>
                    <div class="login__container">
                      <div class="login__wrapper">
                        <div>
                          <div>
                            <div class="login__form__elements">
                              <div>
                                <div>
                                  <h2 class="">Sign In</h2></div>
                              </div>
                              <div>
                                <div>
                                  <div>
                                    <label for="email" id="email-label" class="label__default label__strong label__double-margin">Email</label>
                                    <div>
                                      <input type="text" autocomplete="off" class="input__default form-control" id="email" name="email" aria-invalid="false" aria-describedby="email-error" value="">
                                    </div>
                                    <div id="email-error" aria-hidden="true" role="alert"></div>
                                  </div>
                                </div>
                              </div>
                              <div>
                                <div>
                                  <div>
                                    <label for="password" id="password-label">Password</label>
                                    <div>
                                      <input type="password" autocomplete="off" id="password" name="password" aria-invalid="false" aria-describedby="password-error" value="">
                                    </div>
                                    <div id="password-error" aria-hidden="true" role="alert"></div>
                                  </div>
                                </div>
                              </div>
                              <div>
                                <div>Forgotten your password?</div>
                                <div>
                                  <button type="submit">LOGIN</button>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
        <footer>
          <div>
            <div>
              <div>
                <ul>
                  <li>About</li>
                  <li>Accessibility</li>
                  <li>Cookies</li>
                  <li>Privacy</li>
                </ul>
              </div>
            </div>
          </div>
        </footer>
      </div>
    </div>
  </div>
</body></code>```

答: Flexbox and grid work great for this, the difference being that grid is said to be 2 dimensional whereas flexbox is 1 dimensional. See MDN's Relationship of flexbox to other layout methods. BTW: If you want a sticky footer add min-height: 100vh; to your container.

Body:
Given I have the html and css in the snippet below the question, how can I vertically centre the login view no matter what screen height is?

I have tried this for the .login-layout__positioner class:

.login-layout__positioner {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;

    top: 42%;
    transform: translateY(-42%);
}

But this does not centre well in large screen heights?

Is there a better way?

body {
  height: 100%;
  background-color: #f7f7f4;
}

.app-layout__body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.app-layout__container {
  flex: 1 0 auto;
}

.banner__container {
  background-color: #fff
}

.banner__top {
  padding-top: 15px;
}

.login-layout__container {
  background-color: #f7f7f4;
  width: 100%;
}

.login-layout__positioner {
  text-align: center;
  margin: auto;
}

footer {
  background-color: #0065bd;
}

a {
  color: #fff;
}

ul {
  list-style: none;
  margin-left: 0;
}

li {
  display: inline;
}

.form__group {
  background-color: #fff;
}

Banner

                  <form>

Sign In

                                    Email

                                      <input type="text" autocomplete="off" class="input__default form-control" id="email" name="email" aria-invalid="false" aria-describedby="email-error" value="">

                                    Password

                                      <input type="password" autocomplete="off" id="password" name="password" aria-invalid="false" aria-describedby="password-error" value="">

Forgotten your password?

                                  <button type="submit">LOGIN</button>

                  </form>

About

Accessibility

Cookies

Privacy


来源: stackexchange

问:
Angular 5 return object from http post
I'm struggling with passing json from service layer to component and then invoking functions sequentially. Here is what I've already accomplished:

```<code>users.service.ts

addUser(user: User) {
    return this.http.post('http://localhost:8080/user/create', user).map(res => res.json());
  }
</code>```

And then component layer:

```<code>async onSubmit(model) {
await new Promise(resolve => {
  setTimeout(() => {
    this.submitted = true;
    this.usersService.addUser(model).subscribe(data => this.savedModel = data);
    resolve();
  }, 500);
});
this.sendNotification();
}

@Output() notifyParent: EventEmitter<any> = new EventEmitter();
sendNotification() {
this.notifyParent.emit(JSON.stringify(this.savedModel));
}
</code>```

savedModel is undefined. How can I fix this/what am I doing wrong?

EDIT: Top of the component is:

```<code>@Component({
selector: 'app-user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.css']
})
export class UserFormComponent implements OnInit {

groups: Group[];
model: User;
savedModel;
</code>```

答:
It seems like addUser may be taking longer than 500 seconds, but rather than create an artificial timer you can emit when user service completes.

```<code>onSubmit(modal) {
  this.usersService.addUser(model).subscribe(data => {
    this.savedModel = data;
    this.sendNotification(); // or just .emit here
  });
}
</code>```

You also don't need to wrap this in a Promise or anything.

ContentLicense: CC BY-SA 3.0

Title: Angular 5 return object from http post

Body:
I'm struggling with passing json from service layer to component and then invoking functions sequentially. Here is what I've already accomplished:

users.service.ts

addUser(user: User) {
    return this.http.post('http://localhost:8080/user/create', user).map(res => res.json());
  }

And then component layer:

async onSubmit(model) {
await new Promise(resolve => {
  setTimeout(() => {
    this.submitted = true;
    this.usersService.addUser(model).subscribe(data => this.savedModel = data);
    resolve();
  }, 500);
});
this.sendNotification();
}

@Output() notifyParent: EventEmitter<any> = new EventEmitter();
sendNotification() {
this.notifyParent.emit(JSON.stringify(this.savedModel));
}

savedModel is undefined. How can I fix this/what am I doing wrong?

EDIT: Top of the component is:

@Component({
selector: 'app-user-form',
templateUrl: './user-form.component.html',
styleUrls: ['./user-form.component.css']
})
export class UserFormComponent implements OnInit {

groups: Group[];
model: User;
savedModel;

Body:
It seems like addUser may be taking longer than 500 seconds, but rather than create an artificial timer you can emit when user service completes.

onSubmit(modal) {
  this.usersService.addUser(model).subscribe(data => {
    this.savedModel = data;
    this.sendNotification(); // or just .emit here
  });
}

You also don't need to wrap this in a Promise or anything.


问:
ODBC - Coding Prepared Statements in C++

Hi all,

Plugging away at learning how to develop ODBC SQL driver and data source stuff, but I seem to have run into a bit of a snag. I'm currently working with prepared statements on the a database with the following statement:

```<code>select * from TEST1 where NAME = ? and LOCATION__LATITUDE__S = ?
</code>```

In English, find all records from TEST1 with to-be-specified name and latitudinal coordinate. I'm able to do the above with the ODBCTest app, so I know I can connect to the data source and query it with parameterized queries. Here's what I have for code for my problematic function:

```<code>void ExecPreparedStatement(const char* stmt) {
    HSTMT hstmt;
    SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);

    RETCODE rc = SQLPrepare(hstmt, (WCHAR*)stmt, SQL_NTS);

    SQLSMALLINT numParams;
    rc = SQLNumParams(hstmt, &numParams);

    WCHAR* param1 = (WCHAR*)L"Jacob";
    SQLFLOAT param2 = 40.0;

    rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 80, 0, (SQLPOINTER)param1, 300, NULL);
    rc = SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_C_FLOAT, SQL_FLOAT, 0, 0, &param2, 300, NULL);

    rc = SQLExecute(hstmt); /* <fails here> */

    SQLSMALLINT numCols;
    SQLNumResultCols(hstmt, &numCols);

    DisplayRecords(hstmt, numCols);

    SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
}
</code>```

This should give me the same results from the test app: 3 records of 13 attributes (3 rows, 13 columns). Instead, it fails on execution. For ease of reading, I've removed all of my RetCode handling from the code, but I do have it in there to check that the statements are completed and to handle it gracefully if they fail. There must be something I'm misunderstanding here - it also shows me that the number of parameters from the statement is 0 (with the numParams variable); I theorize that this is because it should be placed after the Execute call, but I can't test that right now because I never get to that point in execution.

Any ideas? Banging my head on a brick wall here; MSDN and other online sources are proving less than informative on this.

Clarification on the main question: Does anybody have any idea why the Execute function is failing?

ANSWER FOUND

The issue was malformed SQL through misused casting. Instead of passing in a const char* string to the function, I pass in a WCHAR*-casted string instead, and inside the function I use WCHAR*. The functional code now looks like this:

```<code>HSTMT hstmt;

SQLAllocStmt(hdbc, &hstmt);

TryODBC(hstmt, SQL_HANDLE_STMT, SQLPrepare(hstmt, stmt, SQL_NTS));
// Prepare passes test - we return 0.

WCHAR* param1 = (WCHAR*)L"Jacob";

TryODBC(hstmt, SQL_HANDLE_STMT,
    SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_WCHAR,
        SQL_WVARCHAR, 80, 0, (SQLPOINTER)param1, 300, NULL)
);

TryODBC(hstmt, SQL_HANDLE_STMT, SQLExecute(hstmt));

SQLSMALLINT numCols;
TryODBC(hstmt, SQL_HANDLE_STMT, SQLNumResultCols(hstmt, &numCols));
DisplayRecords(hstmt, numCols);

SQLFreeStmt(hstmt, SQL_CLOSE);
</code>```

Where TryODBC() is a function as follows:

```<code>bool disconnectOnError = false;
if (rc == SQL_SUCCESS_WITH_INFO || rc == SQL_ERROR) {
    if (!Success(rc)) {
        disconnectOnError = true;
    }
    SQLWCHAR       state[6], errorMsg[SQL_MAX_MESSAGE_LENGTH];
    SQLINTEGER    nativeError;
    SQLSMALLINT   i = 1, msgLen;

    while ((rc = SQLGetDiagRec(handleType, handle, i, state,
        &nativeError, errorMsg, sizeof(errorMsg), &msgLen)) != SQL_NO_DATA)
    {
        ShowMessage(nativeError, errorMsg);
        i++;
    }
}
if (disconnectOnError) {
    Disconnect(-1);
}
</code>```

Massive thanks to @erg for directing me towards the SQLGetDiagRec() function.

答:
You are passing a wide string but specifying SQL_C_CHAR as the parameter type, this should be SQL_C_WCHAR.

300 as your BufferLength parameter makes no sense, for the string argument pass the correct number of bytes, for param2 just pass 0 (BufferLength is ignored for non-character or binary-string data).

And you really need to check the error code after every ODBC call, and if it's an error dump the diagnostics. Either that or turn on the trace connection attribute and look at the results.

Body:
Hi all,

Plugging away at learning how to develop ODBC SQL driver and data source stuff, but I seem to have run into a bit of a snag. I'm currently working with prepared statements on the a database with the following statement:

select * from TEST1 where NAME = ? and LOCATION__LATITUDE__S = ?

In English, find all records from TEST1 with to-be-specified name and latitudinal coordinate. I'm able to do the above with the ODBCTest app, so I know I can connect to the data source and query it with parameterized queries. Here's what I have for code for my problematic function:

void ExecPreparedStatement(const char* stmt) {
    HSTMT hstmt;
    SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);

    RETCODE rc = SQLPrepare(hstmt, (WCHAR*)stmt, SQL_NTS);

    SQLSMALLINT numParams;
    rc = SQLNumParams(hstmt, &numParams);

    WCHAR* param1 = (WCHAR*)L"Jacob";
    SQLFLOAT param2 = 40.0;

    rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 80, 0, (SQLPOINTER)param1, 300, NULL);
    rc = SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_C_FLOAT, SQL_FLOAT, 0, 0, &param2, 300, NULL);

    rc = SQLExecute(hstmt); /* <fails here> */

    SQLSMALLINT numCols;
    SQLNumResultCols(hstmt, &numCols);

    DisplayRecords(hstmt, numCols);

    SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
}

This should give me the same results from the test app: 3 records of 13 attributes (3 rows, 13 columns). Instead, it fails on execution. For ease of reading, I've removed all of my RetCode handling from the code, but I do have it in there to check that the statements are completed and to handle it gracefully if they fail. There must be something I'm misunderstanding here - it also shows me that the number of parameters from the statement is 0 (with the numParams variable); I theorize that this is because it should be placed after the Execute call, but I can't test that right now because I never get to that point in execution.

Any ideas? Banging my head on a brick wall here; MSDN and other online sources are proving less than informative on this.

Clarification on the main question: Does anybody have any idea why the Execute function is failing?

ANSWER FOUND

The issue was malformed SQL through misused casting. Instead of passing in a const char* string to the function, I pass in a WCHAR*-casted string instead, and inside the function I use WCHAR*. The functional code now looks like this:

HSTMT hstmt;

SQLAllocStmt(hdbc, &hstmt);

TryODBC(hstmt, SQL_HANDLE_STMT, SQLPrepare(hstmt, stmt, SQL_NTS));
// Prepare passes test - we return 0.

WCHAR* param1 = (WCHAR*)L"Jacob";

TryODBC(hstmt, SQL_HANDLE_STMT,
    SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_WCHAR,
        SQL_WVARCHAR, 80, 0, (SQLPOINTER)param1, 300, NULL)
);

TryODBC(hstmt, SQL_HANDLE_STMT, SQLExecute(hstmt));

SQLSMALLINT numCols;
TryODBC(hstmt, SQL_HANDLE_STMT, SQLNumResultCols(hstmt, &numCols));
DisplayRecords(hstmt, numCols);

SQLFreeStmt(hstmt, SQL_CLOSE);

Where TryODBC() is a function as follows:

bool disconnectOnError = false;
if (rc == SQL_SUCCESS_WITH_INFO || rc == SQL_ERROR) {
    if (!Success(rc)) {
        disconnectOnError = true;
    }
    SQLWCHAR       state[6], errorMsg[SQL_MAX_MESSAGE_LENGTH];
    SQLINTEGER    nativeError;
    SQLSMALLINT   i = 1, msgLen;

    while ((rc = SQLGetDiagRec(handleType, handle, i, state,
        &nativeError, errorMsg, sizeof(errorMsg), &msgLen)) != SQL_NO_DATA)
    {
        ShowMessage(nativeError, errorMsg);
        i++;
    }
}
if (disconnectOnError) {
    Disconnect(-1);
}

Massive thanks to @erg for directing me towards the SQLGetDiagRec() function.


问:
Javascript array.forEach(function) executing function twice as many times as expected
I have a html file with a single button on it

```<code><!DOCTYPE html>
<html>    <body>
<p>Click the button to list all the items in the array.</p>

<button onclick = "numbers.forEach(myFunction)" >Try it</button>

<p id="demo"></p>
</body>
</html>
</code>```

I also have the Javascript file containing the onclick function for the .forEach method.

When the button is clicked the I'd like to go through an array, looping through each instance of element in the array.

For every element in this array, I'd like to print out its index and value with a timer afterward that waits a second to display the next permutation.

```<code>demoP = document.getElementById("demo");
var numbers = [];

var random = Math.floor(Math.random() * 4) + 1;

numbers.push(random);

function myFunction(item, index) {
  random = Math.floor(Math.random() * 4) + 1;
  numbers.push(random);
  demoP.innerHTML = demoP.innerHTML + "numbers[" + index + "]: " + item + "<br>";
  //demoP.innerHTML = demoP.innerHTML + "<br>" //add magic spacing between permutation
  sleep(100);
  //switch to this and see how slow?
  //sleep(1000);
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
</code>```

What I'd like the result to show when the user clicks the button is:

```<code>numbers[0] = 4
//waits a second and adds a <br> here to separate
numbers[0] = 4
numbers[1] = 2
//waits a second and adds a <br> here
numbers[0] = 4
numbers[1] = 2
numbers[2] = 3
</code>```

and so on.

Currently the code outputs at least twice as many elements, and the sleep() seems to be lasting way longer than it should.

答:
Apart from the hideous sleep function. You are using myFunction as the callback of forEach, and in myFunction, you are pushing new elements to numbers which is the same array you are calling forEach on.

forEach won't call the callback on the newly pushed items while still looping the array. But by the end of the loop, the items in the array will be doubled. As according to MDN:

The range of elements processed by forEach() is set before the first invocation of callback. Elements that are appended to the array after the call to forEach() begins will not be visited by callback.

If the array contains N elements, then when a click happens, N elements will be shown, and myFunction will push N other elements, and when the next click happen 2N elements will be shown this time, ...

So after each click, the elements in the array will be doubled.

Body:
I have a html file with a single button on it

<!DOCTYPE html>

Click the button to list all the items in the array.

<button onclick = "numbers.forEach(myFunction)" >Try it</button>

I also have the Javascript file containing the onclick function for the .forEach method.

When the button is clicked the I'd like to go through an array, looping through each instance of element in the array.

For every element in this array, I'd like to print out its index and value with a timer afterward that waits a second to display the next permutation.

demoP = document.getElementById("demo");
var numbers = [];

var random = Math.floor(Math.random() * 4) + 1;

numbers.push(random);

function myFunction(item, index) {
  random = Math.floor(Math.random() * 4) + 1;
  numbers.push(random);
  demoP.innerHTML = demoP.innerHTML + "numbers[" + index + "]: " + item + "
";
  //demoP.innerHTML = demoP.innerHTML + "
" //add magic spacing between permutation
  sleep(100);
  //switch to this and see how slow?
  //sleep(1000);
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

What I'd like the result to show when the user clicks the button is:

numbers[0] = 4
//waits a second and adds a
 here to separate
numbers[0] = 4
numbers[1] = 2
//waits a second and adds a
 here
numbers[0] = 4
numbers[1] = 2
numbers[2] = 3

and so on.

Currently the code outputs at least twice as many elements, and the sleep() seems to be lasting way longer than it should.


问:
Comparing values from different keys in scala / spark
I am trying to find the difference between values for keys that are related (but not the same). For example, lets say that I have the following map:

```<code>(“John_1”,[“a”,”b”,”c”])
(“John_2”,[“a”,”b”])
(“John_3”,[”b”,”c”])
(“Mary_5”,[“a”,”d”])
(“John_5”,[“c”,”d”,”e”])
</code>```

I want to compare the contents of Name_# to Name_(#-1) and get the difference. So, for the example above, I would like to get (ex:

```<code>(“John_1”,[“a”,”b”,”c”]) //Since there is no John_0, all of the contents are new, so I keep them all
(“John_2”,[])  //Since all of the contents of John_2 appear in John_1, the resulting list is empty (for now, I don’t care about what happened to “c”
(“John_3”,[”c”])  //In this case, “c” is a new item (because I don’t care whether it existed prior to John_2). Again, I don’t care what happened to “a”.
(“Mary_5”,[“a”,”d”]) //There is no Mary_4 so all the items are kept
(“John_5”,[“c”,”d”,”e”]) //There is no John_4 so all the items are kept.
</code>```

I was thinking on doing some kind of aggregateByKey and then just find the difference between the lists, but I do not know how to make the match between the keys that I care about, namely Name_# with Name_(#-1).

答:
Split "id":

```<code>import org.apache.spark.sql.functions._

val df = Seq(
  ("John_1", Seq("a","b","c")), ("John_2", Seq("a","b")),
  ("John_3", Seq("b","c")), ("Mary_5", Seq("a","d")),
  ("John_5", Seq("c","d","e"))
).toDF("key", "values").withColumn(
  "user", split($"key", "_")(0)
).withColumn("id", split($"key", "_")(1).cast("long"))
</code>```

Add window:

```<code>val w = org.apache.spark.sql.expressions.Window
  .partitionBy($"user").orderBy($"id")
</code>```

and udf

```<code>val diff = udf((x: Seq[String], y: Seq[String]) => y.diff(x)
</code>```

and compute:

```<code> df
   .withColumn("is_previous", coalesce($"id" - lag($"id", 1).over(w) === 1, lit(false)))
   .withColumn("diff", when($"is_previous", diff( lag($"values", 1).over(w), $"values")).otherwise($"values"))
   .show

// +------+---------+----+---+-----------+---------+
// |   key|   values|user| id|is_previous|     diff|
// +------+---------+----+---+-----------+---------+
// |Mary_5|   [a, d]|Mary|  5|      false|   [a, d]|
// |John_1|[a, b, c]|John|  1|      false|[a, b, c]|
// |John_2|   [a, b]|John|  2|       true|       []|
// |John_3|   [b, c]|John|  3|       true|      [c]|
// |John_5|[c, d, e]|John|  5|      false|[c, d, e]|
// +------+---------+----+---+-----------+---------+
</code>```

Body:
I am trying to find the difference between values for keys that are related (but not the same). For example, lets say that I have the following map:

(“John_1”,[“a”,”b”,”c”])
(“John_2”,[“a”,”b”])
(“John_3”,[”b”,”c”])
(“Mary_5”,[“a”,”d”])
(“John_5”,[“c”,”d”,”e”])

I want to compare the contents of Name_# to Name_(#-1) and get the difference. So, for the example above, I would like to get (ex:

(“John_1”,[“a”,”b”,”c”]) //Since there is no John_0, all of the contents are new, so I keep them all
(“John_2”,[])  //Since all of the contents of John_2 appear in John_1, the resulting list is empty (for now, I don’t care about what happened to “c”
(“John_3”,[”c”])  //In this case, “c” is a new item (because I don’t care whether it existed prior to John_2). Again, I don’t care what happened to “a”.
(“Mary_5”,[“a”,”d”]) //There is no Mary_4 so all the items are kept
(“John_5”,[“c”,”d”,”e”]) //There is no John_4 so all the items are kept.

I was thinking on doing some kind of aggregateByKey and then just find the difference between the lists, but I do not know how to make the match between the keys that I care about, namely Name_# with Name_(#-1).

Body:
Split "id":

import org.apache.spark.sql.functions._

val df = Seq(
  ("John_1", Seq("a","b","c")), ("John_2", Seq("a","b")),
  ("John_3", Seq("b","c")), ("Mary_5", Seq("a","d")),
  ("John_5", Seq("c","d","e"))
).toDF("key", "values").withColumn(
  "user", split($"key", "_")(0)
).withColumn("id", split($"key", "_")(1).cast("long"))

Add window:

val w = org.apache.spark.sql.expressions.Window
  .partitionBy($"user").orderBy($"id")

and udf

val diff = udf((x: Seq[String], y: Seq[String]) => y.diff(x)

and compute:

 df
   .withColumn("is_previous", coalesce($"id" - lag($"id", 1).over(w) === 1, lit(false)))
   .withColumn("diff", when($"is_previous", diff( lag($"values", 1).over(w), $"values")).otherwise($"values"))
   .show

// +------+---------+----+---+-----------+---------+
// |   key|   values|user| id|is_previous|     diff|
// +------+---------+----+---+-----------+---------+
// |Mary_5|   [a, d]|Mary|  5|      false|   [a, d]|
// |John_1|[a, b, c]|John|  1|      false|[a, b, c]|
// |John_2|   [a, b]|John|  2|       true|       []|
// |John_3|   [b, c]|John|  3|       true|      [c]|
// |John_5|[c, d, e]|John|  5|      false|[c, d, e]|
// +------+---------+----+---+-----------+---------+


问:
Why does Horspool not work on binaries?
I'm trying to make a quick and simple signature detection program in C. It should read a binary file (.exe, ELF, a library, etc...) and search for binary data (sometimes strings, sometimes bytes);

I have a simple test program in C:

```<code>#include <stdio.h>
#include <unistd.h>

const char *str = "TestingOneTwoThree";

int main()
{
    while(1)
    {
        fprintf(stdout, "%s %ld\n", str, (long)getpid());
        sleep(1);
    }

}
</code>```

Here is the horspool algorithm I'm using. I adapted it directly from the wikipedia pseudocode found here: https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define HORSPOOL_COUNT 256
#define BLOCK_SIZE 1024
#define MAX(a, b) a > b ? a : b

ssize_t horspool_find(const char *buf, size_t buflen, const char *egg, size_t egglen)
{
    int table[HORSPOOL_COUNT];
    ssize_t shift = 0, i, tmp;

    for(i = 0; i < HORSPOOL_COUNT; ++i)
    {
        table[i] = (int)egglen;
    }

    for(i = 0; i < egglen - 1; ++i)
    {
        table[(int)egg[i]] = egglen - i - 1;
    }

    while(shift <= buflen - egglen)
    {
        i = egglen - 1;
        while(buf[shift + i] == egg[i])
        {
            if(i == 0)
            {
                return shift;
            }
            i--;
        }
        shift += MAX(1, table[(int)buf[shift + egglen - 1]]);
    }
    return -1;
}

char *readfile(const char *filename, size_t *size)
{
    int ch;
    size_t used = 0, allocated = 0;
    char *buf = NULL, *tmp = NULL;
    FILE *f;

    if((f = fopen(filename, "rb")) == NULL)
    {
        if(size) *size = 0;
        return perror("fopen"), NULL;
    }

    while((ch=fgetc(f)) != EOF)
    {
        if(used >= allocated)
        {
            allocated += BLOCK_SIZE;
            tmp = realloc(buf, allocated);
            if(tmp == NULL)
            {
                free(buf);
                if(size) *size = 0;
                fclose(f);
                return perror("realloc"), NULL;
            }
            buf = tmp;
        }
        buf[used++] = (char)ch;
    }

    fclose(f);
    if(size) *size = used;
    return realloc(buf, used);
}

ssize_t naivealg_find(const char *buf, size_t buflen, const char *find, size_t findlen)
{
    size_t i, j, diff = buflen - findlen;
    for(i = 0; i < diff; ++i)
    {
        for(j = 0; j < findlen; ++j)
        {
            if(buf[i+j] != find[j])
            {
                break;
            }
        }
        if(j == findlen)
        {
            return (ssize_t)i;
        }
    }
    return -1;
}

int main()
{
    size_t size;
    char *buf = readfile("./a.out", &size);
    char *pat = "TestingOneTwoThree";
    ssize_t pos1 = horspool_find(buf, size, pat, strlen(pat));
    ssize_t pos2 = naivealg_find(buf, size, pat, strlen(pat));
    fprintf(stdout, "Offsets: %zd ~ %zd\n", pos1, pos2);
    return 0;
}
</code>```

Output is something along the lines of:

Offsets: -1 ~ 2052

Notes:

The same buffer and "egg" work with the naive search implementation.

The horspool implementation seems to work correctly with normal strings as the buf and egg parameters.

答:
Code was using a signed char and with binary data, from time to time, would index incorrectly with a negative index.

```<code>// table[(int)buf[shift + egglen - 1]]
table[(unsigned char )buf[shift + egglen - 1]]
</code>```

This problem also exists in the the egg pattern.

```<code>// table[(int) egg[i]] = egglen - i - 1;
table[(unsigned char) egg[i]] = egglen - i - 1;
</code>```

Other sign issues occur when buflen < egglen

```<code>// while (shift <= buflen - egglen)
// change to avoid underflow
while (shift + egglen <= buflen)
</code>```

Also consider opening the file in binary and:

```<code>ssize_t shift,i; --> size_t shift,i;

int table[HORSPOOL_COUNT]; -- > size_t table[HORSPOOL_COUNT];
</code>```

Add ()s to #define MAX(a, b) (((a) > (b)) ? (a) : (b))

Title: Why does Horspool not work on binaries?

Body:
I'm trying to make a quick and simple signature detection program in C. It should read a binary file (.exe, ELF, a library, etc...) and search for binary data (sometimes strings, sometimes bytes);

I have a simple test program in C:

#include <stdio.h>
#include <unistd.h>

const char *str = "TestingOneTwoThree";

int main()
{
    while(1)
    {
        fprintf(stdout, "%s %ld\n", str, (long)getpid());
        sleep(1);
    }

}

Here is the horspool algorithm I'm using. I adapted it directly from the wikipedia pseudocode found here: https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define HORSPOOL_COUNT 256
#define BLOCK_SIZE 1024
#define MAX(a, b) a > b ? a : b

ssize_t horspool_find(const char *buf, size_t buflen, const char *egg, size_t egglen)
{
    int table[HORSPOOL_COUNT];
    ssize_t shift = 0, i, tmp;

    for(i = 0; i < HORSPOOL_COUNT; ++i)
    {
        table[i] = (int)egglen;
    }

    for(i = 0; i < egglen - 1; ++i)
    {
        table[(int)egg[i]] = egglen - i - 1;
    }

    while(shift <= buflen - egglen)
    {
        i = egglen - 1;
        while(buf[shift + i] == egg[i])
        {
            if(i == 0)
            {
                return shift;
            }
            i--;
        }
        shift += MAX(1, table[(int)buf[shift + egglen - 1]]);
    }
    return -1;
}

char *readfile(const char *filename, size_t *size)
{
    int ch;
    size_t used = 0, allocated = 0;
    char *buf = NULL, *tmp = NULL;
    FILE *f;

    if((f = fopen(filename, "rb")) == NULL)
    {
        if(size) *size = 0;
        return perror("fopen"), NULL;
    }

    while((ch=fgetc(f)) != EOF)
    {
        if(used >= allocated)
        {
            allocated += BLOCK_SIZE;
            tmp = realloc(buf, allocated);
            if(tmp == NULL)
            {
                free(buf);
                if(size) *size = 0;
                fclose(f);
                return perror("realloc"), NULL;
            }
            buf = tmp;
        }
        buf[used++] = (char)ch;
    }

    fclose(f);
    if(size) *size = used;
    return realloc(buf, used);
}

ssize_t naivealg_find(const char *buf, size_t buflen, const char *find, size_t findlen)
{
    size_t i, j, diff = buflen - findlen;
    for(i = 0; i < diff; ++i)
    {
        for(j = 0; j < findlen; ++j)
        {
            if(buf[i+j] != find[j])
            {
                break;
            }
        }
        if(j == findlen)
        {
            return (ssize_t)i;
        }
    }
    return -1;
}

int main()
{
    size_t size;
    char *buf = readfile("./a.out", &size);
    char *pat = "TestingOneTwoThree";
    ssize_t pos1 = horspool_find(buf, size, pat, strlen(pat));
    ssize_t pos2 = naivealg_find(buf, size, pat, strlen(pat));
    fprintf(stdout, "Offsets: %zd ~ %zd\n", pos1, pos2);
    return 0;
}

Output is something along the lines of:

Offsets: -1 ~ 2052

Notes:

The same buffer and "egg" work with the naive search implementation.

The horspool implementation seems to work correctly with normal strings as the buf and egg parameters.

Body:
Code was using a signed char and with binary data, from time to time, would index incorrectly with a negative index.

// table[(int)buf[shift + egglen - 1]]
table[(unsigned char )buf[shift + egglen - 1]]

This problem also exists in the the egg pattern.

// table[(int) egg[i]] = egglen - i - 1;
table[(unsigned char) egg[i]] = egglen - i - 1;

Other sign issues occur when buflen < egglen

// while (shift <= buflen - egglen)
// change to avoid underflow
while (shift + egglen <= buflen)

Also consider opening the file in binary and:

ssize_t shift,i; --> size_t shift,i;

int table[HORSPOOL_COUNT]; -- > size_t table[HORSPOOL_COUNT];

Add ()s to #define MAX(a, b) (((a) > (b)) ? (a) : (b))


问:
Parallel Python for loop
I work primarily with arcgis and pci flavours of python 2.7. I have a number of processes that I've created that run outside of these programs but use these libraries. They are run via .bat files through cmd.

Currently, they run the processes in a series of for loops. And each for loop processes sequentially. I was wondering if there was a way to run the processing within the for loop for each object in the list at the same time. That is in parallel. The only way I can think of this is opening a cmd for each object in the list, and running the processing separately.

Is what I am asking even possible? Where should I look for solutions?

答:
Look into Subprocess So youd want a new commandline window created in the background where test.bat runs in parallel.. and in your  case you don't want to wait for the command to complete before you continue your program, so use subprocess.Popen instead (may be something to look into as
well)

```<code>subprocess.call
</code>```

Run the command described by args. Wait for command to complete, then return the returncode attribute.

If you want to start an external program from your python script pass the program's filename to subprocess.Popen() on Ubuntu Linux you would enter something like

```<code>>>>import subprocess
>>>subprocess.Popen('/usr/bin/gnome-...')
<subprocess.Popen Object at 0x7f2bcf93b20
</code>```

The Return value is a Popen object which has two useful methods : poll() & wait()

poll() is like asking your friend if he has finished running the code you gave him.
wait() is like waiting for your friend to finish working on his code before you keep working on yours.(something you might want to look into)

Title: Parallel Python for loop

Body:
Look into Subprocess So youd want a new commandline window created in the background where test.bat runs in parallel.. and in your  case you don't want to wait for the command to complete before you continue your program, so use subprocess.Popen instead (may be something to look into as
well)

subprocess.call

Run the command described by args. Wait for command to complete, then return the returncode attribute.

If you want to start an external program from your python script pass the program's filename to subprocess.Popen() on Ubuntu Linux you would enter something like

>>>import subprocess
>>>subprocess.Popen('/usr/bin/gnome-...')
<subprocess.Popen Object at 0x7f2bcf93b20

The Return value is a Popen object which has two useful methods : poll() & wait()

poll() is like asking your friend if he has finished running the code you gave him.
wait() is like waiting for your friend to finish working on his code before you keep working on yours.(something you might want to look into)


问:
bootstrap 4 center items except first element

.c-footer {
  background: #000;
  padding: 20px 0;
  color: #fff; }
  .c-footer__logo {
    display: inline; }
  .c-footer__link {
    color: inherit; }
    .c-footer__link a {
      color: inherit; }
      .c-footer__link a:hover {
        color: #fff; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="c-footer text-center">
 <div class="c-footer__logo">
  <img src="http://dynamicdog.se/wp-content/themes/dynamicdog/img/logo.png">
 </div>
 <span class="c-footer__link">
  Malmö<span> - </span>
 </span>
 <span class="c-footer__link">
  Stockholm<span> - </span>
 </span>
  <span class="c-footer__link">
  Malmö<span> - </span>
 </span>
 <span class="c-footer__link">
  Stockholm<span> - </span>
 </span>
  <span class="c-footer__link">
  Malmö<span> - </span>
 </span>
 <span class="c-footer__link">
  Stockholm
 </span>
</div></code>```

I want to accomplish the picture below:

Centering the text while having the image floated to the left. I tried with the bootstrap class center-text however it centers all elements...

Heres my markup:

```<code><div class="c-footer">
 <div class="c-footer__logo">
  <img src="/static/media/q-logo.98ed5701.png">
 </div>
 <span class="c-footer__link">
  <a href="#">Malmö</a><span> - </span>
 </span>
 <span class="c-footer__link">
  <a href="#">Stockholm</a><span> - </span>
 </span>
</div>
</code>```

How would you accomplish this?

答:
In my approach, I use text-align and float. text-align will align all inline items. this affects both the text and the image since both are inline. Since we want the image to stay on the left side, we can float the image.This should place the image along the left side of its container.

Those two combined makes the image stick to the left while rest of the content inside c-footer is aligned to the center regardless of device width! :)

.c-footer {
  background-color: #000;
  height: 80px;
  text-align: center;
}

.c-footer__logo {
  padding-left: 20px;
  float: left;
}

.c-footer__logo img {
  height: 80px; /* Just for the looks of the example */
}

.c-footer__link a{
  line-height: 80px;
  color: #fff;
}

.c-footer__link:after {
  color: #fff;
  content: '\00a0-\00a0'
}
.c-footer__link:last-child:after {
  content: ''
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer class="c-footer">
  <div class="c-footer__logo">
    <img src="https://i.gyazo.com/1e2e3e71c2e236cb827f8026d1aa813e.png">
  </div>
    <span class="c-footer__link">
      Bergen
    </span>
    <span class="c-footer__link">
      Oslo
    </span>
    <span class="c-footer__link">
      Stavanger
    </span>
    <span class="c-footer__link">
      Kristiansand
    </span>
    <span class="c-footer__link">
      Trondheim
    </span>
    <span class="c-footer__link">
      Drammen
    </span>
</footer></code>```

Body:
.c-footer {
  background: #000;
  padding: 20px 0;
  color: #fff; }
  .c-footer__logo {
    display: inline; }
  .c-footer__link {
    color: inherit; }
    .c-footer__link a {
      color: inherit; }
      .c-footer__link a:hover {
        color: #fff; }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

  Malmö -

  Stockholm -

  Malmö -

  Stockholm -

  Malmö -

  Stockholm

I want to accomplish the picture below:

Centering the text while having the image floated to the left. I tried with the bootstrap class center-text however it centers all elements...

Heres my markup:

  Malmö -

  Stockholm -

How would you accomplish this?

Body:
In my approach, I use text-align and float. text-align will align all inline items. this affects both the text and the image since both are inline. Since we want the image to stay on the left side, we can float the image.This should place the image along the left side of its container.

Those two combined makes the image stick to the left while rest of the content inside c-footer is aligned to the center regardless of device width! :)

.c-footer {
  background-color: #000;
  height: 80px;
  text-align: center;
}

.c-footer__logo {
  padding-left: 20px;
  float: left;
}

.c-footer__logo img {
  height: 80px; /* Just for the looks of the example */
}

.c-footer__link a{
  line-height: 80px;
  color: #fff;
}

.c-footer__link:after {
  color: #fff;
  content: '\00a0-\00a0'
}
.c-footer__link:last-child:after {
  content: ''
}

<footer class="c-footer">
  <div class="c-footer__logo">
    <img src="https://i.gyazo.com/1e2e3e71c2e236cb827f8026d1aa813e.png">
  </div>
    <span class="c-footer__link">
      <a href="#">Bergen</a>
    </span>
    <span class="c-footer__link">
      <a href="#">Oslo</a>
    </span>
    <span class="c-footer__link">
      <a href="#">Stavanger</a>
    </span>
    <span class="c-footer__link">
      <a href="#">Kristiansand</a>
    </span>
    <span class="c-footer__link">
      <a href="#">Trondheim</a>
    </span>
    <span class="c-footer__link">
      <a href="#">Drammen</a>
    </span>
</footer>


问:
Entity Framework Feature CTP5 Append Model?
I am using EF Feature CTP5 and need to be able to just append changes to the database structure when making changes to the model or my class objects?

Is there a way to do this or does it need to drop and recreate the database every time you make a change to the class objects?

答:
No, as of CTP5 only DropCreateDatabaseAlways and DropCreateDatabaseIfModelChanges strategies are supported which essentially recreate your DB every time.

That said, EF team is actively working on a Code First Database Evolution (aka Migrations) feature which is exactly what you are looking for: Altering DB instead of dropping it. We likely get this feature in the RTM this year.

ContentLicense: CC BY-SA 2.5


问:
Menu Inflater doesn't render items outside menu xml
I am trying to create menu according to https://guides.codepath.com/android/Using-the-App-Toolbar

Menu items are shown perfectly only in menu_main.xml. I cant see items in toolbar_main.xml or activity_main.xml... According to other solutions posted on stack, I didn't solve my problem. Everything is done according to these docs at codepath and should work.

What should be done to see menu in main activity, or this is normal behavior?

答: Turns out that's normal behavior. Strange not to see render in root coming from web :D</p>


问:
Need help in refreshing the page after submit
I am developing an web application following the 3 tier architecture.When i am hitting on submit button data is storing in database but not showing response message like "Record submitted successfully" and fields are not refreshing. Here is my code:

```<code>protected void BtnSubmit_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
            return;

        NewuserBAL NUB = new NewuserBAL();

        string UserName = TxtUserName.Text;
        string Password = PWD.Text;
        string EmailId = Email.Text;

        try
        {
            NUB.newinsert(UserName, Password, EmailId);
            Response.Write("<b>New User Created Successfully</b>");
            TxtUserName.Text = "";
            PWD.Text = "";
            CnfrmPwd.Text = "";
            Email.Text = "";
        }
        catch
        {
            throw;

        }

        finally
        {
            NUB = null;

        }

    }
</code>```

Thanks,
Masum

答: Rather than using Response.Write, set a label such as labelResults to display the outcome. Response.Write is not going to show up in the proper place in your rendered HTML.</p>

OwnerDisplayName: Masuma Aktar

Body:
I am developing an web application following the 3 tier architecture.When i am hitting on submit button data is storing in database but not showing response message like "Record submitted successfully" and fields are not refreshing. Here is my code:

protected void BtnSubmit_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
            return;

        NewuserBAL NUB = new NewuserBAL();

        string UserName = TxtUserName.Text;
        string Password = PWD.Text;
        string EmailId = Email.Text;

        try
        {
            NUB.newinsert(UserName, Password, EmailId);
            Response.Write("New User Created Successfully");
            TxtUserName.Text = "";
            PWD.Text = "";
            CnfrmPwd.Text = "";
            Email.Text = "";
        }
        catch
        {
            throw;

        }

        finally
        {
            NUB = null;

        }

    }

Thanks,
Masum

LastEditorDisplayName: John Sheehan

OwnerDisplayName: David Thomas Garcia


问:
where can I find a good wordlist
I'm looking for a file that is a wordlist and also is set up by type of word. For example something in this format

```<code>Nouns: {
    bus
    car
    deck
    elephant
    ...
}
Adjectives {
    awful
    bashful
    ...
}
Advervb {
    ...
}
</code>```

Any ideas?

答:
Here is a good list of nouns / verbs ...

Nouns

http://www.momswhothink.com/reading/list-of-nouns.html

Verbs

http://www.momswhothink.com/reading/list-of-verbs.html

Adverbs

http://www.momswhothink.com/reading/list-of-adverbs.html

Title: where can I find a good wordlist

Body:
I'm looking for a file that is a wordlist and also is set up by type of word. For example something in this format

Nouns: {
    bus
    car
    deck
    elephant
    ...
}
Adjectives {
    awful
    bashful
    ...
}
Advervb {
    ...
}

Any ideas?


问:
How do i access this Json with PHP
am having issues trying to get contents of this json, am using php.

```<code>{"song":{"returncode":"200","returnmsg":"OK","title":"Despacito Ft. Justin Bieber","artist":"Luis Fonsi, Daddy Yankee","album":"","size":"9193600","url":"http://sami-server.info/Bita6/04.96/Billboard%20Hot%20100%20Singles/Billboard%20Hot%20100%20Singles/01.%20Luis%20Fonsi%2C%20Daddy%20Yankee%20-%20Despacito%20ft.%20Justin%20Bieber.mp3","time":"1499079781","date":"Jul 3, 2017","source":"","active":"1","albumart":"https://images-na.ssl-images-amazon.com/images/I/5150NxehQtL._AC_US160_.jpg","speed":"21","counter":"850850"}
</code>```

this is my function, that returns the json

```<code>public function getSong($id) {
        $song_url = 'http://databrainz.com/api/data_api_new.cgi?jsoncallback=&id='.$id.'&r=mpl&format=json&_=';
        $api = Api::getSpotOn($song_url);
        $song = $api->{'song'};
         return $song;
    }
</code>```

I want to get all it content.

Thanks!

答:
In the json example you provided a final '}' is missing and the json_decode will return Null without it as it's non a valid json.

But, since you have the getSong method the following should work:

```<code>$retObject = json_decode(getSong($songId));
$song = $retObject->song;

print_r($song);

echo 'returncode:'.$song->returncode.'<br/>';
echo 'returnmsg:'.$song->returnmsg.'<br/>';
echo 'title:'.$song->title.'<br/>';
echo 'artist:'.$song->artist.'<br/>';
echo 'album:'.$song->album.'<br/>';
echo 'size:'.$song->size.'<br/>';
echo 'url:'.$song->url.'<br/>';
echo 'time:'.$song->time.'<br/>';
echo 'date:'.$song->date.'<br/>';
echo 'source:'.$song->source.'<br/>';
echo 'active:'.$song->active.'<br/>';
echo 'albumart:'.$song->albumart.'<br/>';
echo 'speed:'.$song->speed.'<br/>';
echo 'counter:'.$song->counter.'<br/>';
</code>```

Title: How do i access this Json with PHP

Body:
am having issues trying to get contents of this json, am using php.

{"song":{"returncode":"200","returnmsg":"OK","title":"Despacito Ft. Justin Bieber","artist":"Luis Fonsi, Daddy Yankee","album":"","size":"9193600","url":"http://sami-server.info/Bita6/04.96/Billboard%20Hot%20100%20Singles/Billboard%20Hot%20100%20Singles/01.%20Luis%20Fonsi%2C%20Daddy%20Yankee%20-%20Despacito%20ft.%20Justin%20Bieber.mp3","time":"1499079781","date":"Jul 3, 2017","source":"","active":"1","albumart":"https://images-na.ssl-images-amazon.com/images/I/5150NxehQtL._AC_US160_.jpg","speed":"21","counter":"850850"}

this is my function, that returns the json

public function getSong($id) {
        $song_url = 'http://databrainz.com/api/data_api_new.cgi?jsoncallback=&id='.$id.'&r=mpl&format=json&_=';
        $api = Api::getSpotOn($song_url);
        $song = $api->{'song'};
         return $song;
    }

I want to get all it content.

Thanks!

Body:
In the json example you provided a final '}' is missing and the json_decode will return Null without it as it's non a valid json.

But, since you have the getSong method the following should work:

$retObject = json_decode(getSong($songId));
$song = $retObject->song;

print_r($song);

echo 'returncode:'.$song->returncode.'<br/>';
echo 'returnmsg:'.$song->returnmsg.'<br/>';
echo 'title:'.$song->title.'<br/>';
echo 'artist:'.$song->artist.'<br/>';
echo 'album:'.$song->album.'<br/>';
echo 'size:'.$song->size.'<br/>';
echo 'url:'.$song->url.'<br/>';
echo 'time:'.$song->time.'<br/>';
echo 'date:'.$song->date.'<br/>';
echo 'source:'.$song->source.'<br/>';
echo 'active:'.$song->active.'<br/>';
echo 'albumart:'.$song->albumart.'<br/>';
echo 'speed:'.$song->speed.'<br/>';
echo 'counter:'.$song->counter.'<br/>';


问:
How to import SQL database from PC to Android app
I'm working on Android app which will use SQL database. I created the database with data on my PC. I have SQL dump file for this database. I would like to use this dump file to create and use SQLite database as a part of the app. How could I achieve this? I will appreciate the hints.

Thanks!

答: If you have the sql file on your PC then just drag and drop it in a folder in Android Studio let it be under /Database. Then you can use it in your application.</p>


问:
React native: How to ignore a JSON object if it doesn't exist
I'm trying to get data out of a Open Weathermap API but it's a dynamic API, for some reason.

To get to the amount of rainfall per three hours you have to go to:

```<code>json.list[0].rain['3h']
</code>```

Now if it's snowing, the 'rain' turns into

```<code>json.list[0].snow['3h']
</code>```

I got the code like this:

```<code>return fetch(url)
    .then(res => res.json())
    .then(json => ({
        temp1: json.list[0].main.temp,
        tempmin1: json.list[0].main.temp_mix,
        tempmax1: json.list[0].main.temp_max,
        weather1: json.list[0].weather[0].main,
        time: json.list[0].dt_txt,
        name: json.city.name,
        rainmillimeter1: json.list[0].rain['3h'],
        snowmillimeter1: json.list[0].snow['3h'],
        wind1: json.list[0].wind['speed'],
        vochtigheid1: json.list[0].main['humidity'],
        luchtdruk1: json.list[0].main['pressure'],
</code>```

But then it gets an Unhandled Promise Rejection, and doesn't load any of the API.
Is there a way to let it ignore either rain or snow, if it doesn't exist?

Thanks!

答:
You can use ternary operators to check if one of the objects aren't there:

```<code>rainmillimeter1: (json.list[0].rain) ? json.list[0].rain['3h'] : null,
snowmillimeter1: (json.list[0].snow) ? json.list[0].snow['3h'] : null,
</code>```

Also, Unhandled Promise Rejection is usually when a promise fails and there is no error handling using .catch((e) => {}). Something you probably should account for incase the API is unreachable at any time.

More details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

Body:
I'm trying to get data out of a Open Weathermap API but it's a dynamic API, for some reason.

To get to the amount of rainfall per three hours you have to go to:

json.list[0].rain['3h']

Now if it's snowing, the 'rain' turns into

json.list[0].snow['3h']

I got the code like this:

return fetch(url)
    .then(res => res.json())
    .then(json => ({
        temp1: json.list[0].main.temp,
        tempmin1: json.list[0].main.temp_mix,
        tempmax1: json.list[0].main.temp_max,
        weather1: json.list[0].weather[0].main,
        time: json.list[0].dt_txt,
        name: json.city.name,
        rainmillimeter1: json.list[0].rain['3h'],
        snowmillimeter1: json.list[0].snow['3h'],
        wind1: json.list[0].wind['speed'],
        vochtigheid1: json.list[0].main['humidity'],
        luchtdruk1: json.list[0].main['pressure'],

But then it gets an Unhandled Promise Rejection, and doesn't load any of the API.
Is there a way to let it ignore either rain or snow, if it doesn't exist?

Thanks!

Body:
You can use ternary operators to check if one of the objects aren't there:

rainmillimeter1: (json.list[0].rain) ? json.list[0].rain['3h'] : null,
snowmillimeter1: (json.list[0].snow) ? json.list[0].snow['3h'] : null,

Also, Unhandled Promise Rejection is usually when a promise fails and there is no error handling using .catch((e) => {}). Something you probably should account for incase the API is unreachable at any time.

More details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch


问:
Fatal error: Class 'Dotenv\Dotenv' not found in .../Bootstrap/DetectEnvironment.php on line 24
Not sure why I am getting this message:

Fatal error: Uncaught Symfony\Component\Debug\Exception\FatalThrowableError: Class 'Dotenv\Dotenv' not found in /home/vagrant/devbox/devbox.local/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/DetectEnvironment.php on line 24

Below is the DetectEnvironment.php code:

```<code><?php

namespace Illuminate\Foundation\Bootstrap;

use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
use Symfony\Component\Console\Input\ArgvInput;
use Illuminate\Contracts\Foundation\Application;

class DetectEnvironment
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Application $app)
    {
        if (! $app->configurationIsCached()) {
            $this->checkForSpecificEnvironmentFile($app);

            try {
                (new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
            } catch (InvalidPathException $e) {
                //
            }
        }
    }
</code>```

My project had been working correctly until I restarted the computer and server. Whenever I go to the site or run a composer or artisan command I get the error above.

I have tried various solutions that I have found but none have worked. This includes:

specifically adding vlucas/phpdotenv to the composer file (it already existed in the vendor file structure, but added it to make sure)

running composer update and composer dumpautoload

creating a new .env file

Creating a new laravel project works, but I really don't want to have to do that (there must be an easy explanation/fix for this).

Similar issues as listed in, but neither have answers that work for me:

PHP Fatal error: Class 'Dotenv' not found in

Fatal error: Class 'Dotenv\Dotenv' not found in

I am using the latest Laravel version and running it on Homestead.

Any guidance is greatly appreciated!

答: Try deleting the contents (not the directories themselves) in /bootstrap/cache/, and delete your /vendor/compiled.php, then run composer install again.

Body:
Not sure why I am getting this message:

Fatal error: Uncaught Symfony\Component\Debug\Exception\FatalThrowableError: Class 'Dotenv\Dotenv' not found in /home/vagrant/devbox/devbox.local/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/DetectEnvironment.php on line 24

Below is the DetectEnvironment.php code:

<?php

namespace Illuminate\Foundation\Bootstrap;

use Dotenv\Dotenv;
use Dotenv\Exception\InvalidPathException;
use Symfony\Component\Console\Input\ArgvInput;
use Illuminate\Contracts\Foundation\Application;

class DetectEnvironment
{
    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Application $app)
    {
        if (! $app->configurationIsCached()) {
            $this->checkForSpecificEnvironmentFile($app);

            try {
                (new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
            } catch (InvalidPathException $e) {
                //
            }
        }
    }

My project had been working correctly until I restarted the computer and server. Whenever I go to the site or run a composer or artisan command I get the error above.

I have tried various solutions that I have found but none have worked. This includes:

specifically adding vlucas/phpdotenv to the composer file (it already existed in the vendor file structure, but added it to make sure)

running composer update and composer dumpautoload

creating a new .env file

Creating a new laravel project works, but I really don't want to have to do that (there must be an easy explanation/fix for this).

Similar issues as listed in, but neither have answers that work for me:

PHP Fatal error: Class 'Dotenv' not found in

Fatal error: Class 'Dotenv\Dotenv' not found in

I am using the latest Laravel version and running it on Homestead.

Any guidance is greatly appreciated!


问:
Suppressing HTML output in SAS
I'm trying to suppress HTML output and get PROC PRINT to output only to CSV, but ODS HTML Close doesn't seem to work.

My code is:

```<code>ODS HTML close;
ODS CSV file="\\..output folder..\filename.csv";
proc print data=test;
run;
ODS CSV close;
ODS HTML;
</code>```

答:
I'm been trying all day and finally got it for me.  What I wanted suppress from the results viewer is just below here (and the end of a macro).  The results I wanted in the results viewer and now called in a separate macro at the end...
Brubumski</p>

```<code>  ODS HTML close;   * bsk;
  ods results off;  * bsk;
  ods csvall file="&file1";
  proc print data=tr_outds noobs; run;
  ods csvall close; * bsk;
  ods results on;   * bsk;
  ODS HTML;         * bsk;

  %OdsOn1(outds,outds2,tr_outds, file1, file2); * bsk;

%mend process_input_data_10_10;

%macro OdsOn1(outds,outds2,tr_outds, file1, file2);
  proc freq data=outds;tables Group_nm/missing;run;
  proc freq data=outds2;tables case_id/missing;run;
  proc print data=tr_outds(obs=10) noobs; run;* bsk;

  ods csvall file="&file2";
  proc print data=cases noobs; run;
  ods csvall close;
%mend OdsOn1;
</code>```

Title: Suppressing HTML output in SAS

Body:
I'm trying to suppress HTML output and get PROC PRINT to output only to CSV, but ODS HTML Close doesn't seem to work.

My code is:

ODS HTML close;
ODS CSV file="\\..output folder..\filename.csv";
proc print data=test;
run;
ODS CSV close;
ODS HTML;

Body:
I'm been trying all day and finally got it for me.  What I wanted suppress from the results viewer is just below here (and the end of a macro).  The results I wanted in the results viewer and now called in a separate macro at the end...
Brubumski

  ODS HTML close;   * bsk;
  ods results off;  * bsk;
  ods csvall file="&file1";
  proc print data=tr_outds noobs; run;
  ods csvall close; * bsk;
  ods results on;   * bsk;
  ODS HTML;         * bsk;

  %OdsOn1(outds,outds2,tr_outds, file1, file2); * bsk;

%mend process_input_data_10_10;

%macro OdsOn1(outds,outds2,tr_outds, file1, file2);
  proc freq data=outds;tables Group_nm/missing;run;
  proc freq data=outds2;tables case_id/missing;run;
  proc print data=tr_outds(obs=10) noobs; run;* bsk;

  ods csvall file="&file2";
  proc print data=cases noobs; run;
  ods csvall close;
%mend OdsOn1;


问:
Are CSS Stylesheets loaded Asynchronously
When loading stylesheets via the  tag, are the stylesheets loaded asynchronously or synchronously?  I have a design with two stylesheets: mura.css and typography.css.  They are loaded in the  area of the page and typography.css is loaded just before mura.css.  For some reason though mura.css attributes are showing in the Chrome Webtools as being overwritten with typography.css.</p>

答:
CSS files are loaded in the order they are included in the file.

If something from the first CSS file is overwriting something in the second CSS file, it is most likely due to your selectors being used incorrectly. Double-check your selectors for the elements of the page that are incorporating the style incorrectly.


问:
Is it possible to set ISR Handler at runtime on M0+
I have a "default" resetVectors.c file for my SAMD21 ARM M0+. It has something that looks like:

```<code>__attribute__ ((section(".vectors")))
const DeviceVectors exception_table = {
    ...
};
</code>```

in it that defines where different handler stubs. For testing purposes, I want to use one of the unused peripheral IRQs.

By default, the unused ones are set to NULL addresses. I have demonstrated to myself that I can modify that file and at compile time change my unused IRQ (21) to fire a handler. BUT, is it possible to do this outside of compile time?

I observed that the table appears to be based at offset 0. So I tried this:

```<code>DeviceVectors *table = 0x0000000;
table->pvReserved21 = PV21Handler;
</code>```

But that just hangs the board. Is there a dynamic way to assign the handler at runtime?

答: You can place the vector table in in the RAM or if you do not want it there you can copy it to the new location in the FLASH memory changing the ISR vector. Then you can change the address of the of the vector table itself.</p>

Body:
I have a "default" resetVectors.c file for my SAMD21 ARM M0+. It has something that looks like:

__attribute__ ((section(".vectors")))
const DeviceVectors exception_table = {
    ...
};

in it that defines where different handler stubs. For testing purposes, I want to use one of the unused peripheral IRQs.

By default, the unused ones are set to NULL addresses. I have demonstrated to myself that I can modify that file and at compile time change my unused IRQ (21) to fire a handler. BUT, is it possible to do this outside of compile time?

I observed that the table appears to be based at offset 0. So I tried this:

DeviceVectors *table = 0x0000000;
table->pvReserved21 = PV21Handler;

But that just hangs the board. Is there a dynamic way to assign the handler at runtime?


问:
Gray Level CoOccurence Features Do Not Match Equations
Consider a simple glcm matrix.

```<code>glcm = [0 1 2 3;1 1 2 3;1 0 2 0;0 0 0 3];
</code>```

Calculate the statistics using Matlab's built in features.

```<code>stats = graycoprops(glcm)

   Contrast: 2.8947
Correlation: 0.0783
     Energy: 0.1191
Homogeneity: 0.5658
</code>```

Now, instead, calculate them manually using the definition of these equations as given at the bottom of this page: https://www.mathworks.com/help/images/ref/graycoprops.html

```<code>contrast = 0;
energy = 0
for i = 1:4
    for j = 1:4
        contrast = contrast + glcm(i,j)*(i-j)^2;
        energy = energy + glcm(i,j)^2;
    end
end
</code>```

Which gives:

```<code>contrast =

   110

energy =

    43
</code>```

What is the deal? Is some type of normalization being done? It is not simply dividing by the number of elements which is 16...

Any thoughts? Thanks!

答:
As I told you already in my comment, the documentation for graycoprops clearly states that:

graycoprops normalizes the gray-level co-occurrence matrix (GLCM) so
  that the sum of its elements is equal to 1.

But if you want to find the inner workings of this function, the best thing you can do is delve into the function code itself and find out how it does what it does. This is done best by doing a step-by-step debugging of the code.

If you type edit graycoprops in the Command Window, you can access the source code of the function.

If you do that, you will be able to see that around line 84 there is an if statement that calls another function called normalizeGLCM. This last function lives on the same file, so if you scroll down, around line 119 you can find how it works:

```<code>function glcm = normalizeGLCM(glcm)

% Normalize glcm so that sum(glcm(:)) is one.
if any(glcm(:))
  glcm = glcm ./ sum(glcm(:));
end
</code>```

So, essentially, if you add the above normalization to your code, it will generate the same results as the graycoprops function:

```<code>glcm = [0 1 2 3;1 1 2 3;1 0 2 0;0 0 0 3];

stats = graycoprops(glcm)

glcm_norm = glcm ./ sum(glcm(:)); % <-- Normalize.

contrast = 0;
energy = 0;
for i = 1:4
    for j = 1:4
        contrast = contrast + glcm_norm(i,j)*(i-j)^2;
        energy = energy + glcm_norm(i,j)^2;
    end
end
</code>```

Compare the results of graycoprops:

```<code>>> stats

stats =

  struct with fields:

       Contrast: 2.8947
    Correlation: 0.0783
         Energy: 0.1191
    Homogeneity: 0.5658
</code>```

With your results:

```<code>>> contrast

contrast =

    2.8947

>> energy

energy =

    0.1191
</code>```

They match perfectly.

Body:
Consider a simple glcm matrix.

glcm = [0 1 2 3;1 1 2 3;1 0 2 0;0 0 0 3];

Calculate the statistics using Matlab's built in features.

stats = graycoprops(glcm)

   Contrast: 2.8947
Correlation: 0.0783
     Energy: 0.1191
Homogeneity: 0.5658

Now, instead, calculate them manually using the definition of these equations as given at the bottom of this page: https://www.mathworks.com/help/images/ref/graycoprops.html

contrast = 0;
energy = 0
for i = 1:4
    for j = 1:4
        contrast = contrast + glcm(i,j)*(i-j)^2;
        energy = energy + glcm(i,j)^2;
    end
end

Which gives:

contrast =

   110

energy =

    43

What is the deal? Is some type of normalization being done? It is not simply dividing by the number of elements which is 16...

Any thoughts? Thanks!

Body:
As I told you already in my comment, the documentation for graycoprops clearly states that:

graycoprops normalizes the gray-level co-occurrence matrix (GLCM) so
  that the sum of its elements is equal to 1.

But if you want to find the inner workings of this function, the best thing you can do is delve into the function code itself and find out how it does what it does. This is done best by doing a step-by-step debugging of the code.

If you type edit graycoprops in the Command Window, you can access the source code of the function.

If you do that, you will be able to see that around line 84 there is an if statement that calls another function called normalizeGLCM. This last function lives on the same file, so if you scroll down, around line 119 you can find how it works:

function glcm = normalizeGLCM(glcm)

% Normalize glcm so that sum(glcm(:)) is one.
if any(glcm(:))
  glcm = glcm ./ sum(glcm(:));
end

So, essentially, if you add the above normalization to your code, it will generate the same results as the graycoprops function:

glcm = [0 1 2 3;1 1 2 3;1 0 2 0;0 0 0 3];

stats = graycoprops(glcm)

glcm_norm = glcm ./ sum(glcm(:)); % <-- Normalize.

contrast = 0;
energy = 0;
for i = 1:4
    for j = 1:4
        contrast = contrast + glcm_norm(i,j)*(i-j)^2;
        energy = energy + glcm_norm(i,j)^2;
    end
end

Compare the results of graycoprops:

>> stats

stats =

  struct with fields:

       Contrast: 2.8947
    Correlation: 0.0783
         Energy: 0.1191
    Homogeneity: 0.5658

With your results:

>> contrast

contrast =

    2.8947

>> energy

energy =

    0.1191

They match perfectly.


问:
vba excel list to word with chapters
From this:

I would like to move and style the content in

Word as this :

using VBA.

I succeeded in identify the "component" duplicates to use this as chapters names in Word. But now, for me the hard part is to select "spare parts" only related to concerned "component", copy them and paste them. I know how to open Word, create a Word document, and paste into it. But I'm just blocked in selecting the right thing to be pasted.

Thanks in advance for your advices.

答:
Following code will load data from Excel into 2D array. First the dimensions of the array are determined, than the data is saved into the array. New Word document is created and data from array is saved to Word file. Every first item from the array is saved as new paragraph, other data is saved in the table. No Word formating is done.</p>

```<code>Option Base 1
Option Explicit
Sub TwoD_Tbl_to_Word()
    Dim MyArr() As String
    Dim comidx As Long
    Dim partidx As Long
    Dim partidxtmp As Long
    Dim i As Long
    Dim teststr As String

    Dim objWd As Word.Application
    Dim objDoc As Word.Document
    Dim myRange As Word.Range

    teststr = Cells(5, 2)
    comidx = 1
    partidx = 1
    partidxtmp = 1

'detect 2D Array Indexes
    For i = 6 To ActiveSheet.Columns("B").Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
        If Cells(i, 2) = teststr Then
            partidxtmp = partidxtmp + 1
        Else
        teststr = Cells(i, 2)
        If partidxtmp > partidx Then
            partidx = partidxtmp
        End If
        partidxtmp = 1
        comidx = comidx + 1
        End If
    Next i

'if the last item is the biggest
    If partidxtmp > partidx Then
        partidx = partidxtmp
    End If
'redefine array
    ReDim MyArr(comidx, partidx + 1)

'load Excel into Array
    teststr = Cells(5, 2)
    MyArr(1, 1) = Cells(5, 2)
    MyArr(1, 2) = Cells(5, 3)
    partidxtmp = 2
    comidx = 1

    For i = 6 To ActiveSheet.Columns("B").Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
        If Cells(i, 2) = teststr Then
           partidxtmp = partidxtmp + 1
           MyArr(comidx, partidxtmp) = Cells(i, 3)
        Else
           comidx = comidx + 1
           teststr = Cells(i, 2)
           MyArr(comidx, 1) = Cells(i, 2)
           MyArr(comidx, 2) = Cells(i, 3)
           partidxtmp = 2
        End If
    Next i
'Create Word
    Set objWd = CreateObject("word.application")
    objWd.Visible = True
    Set objDoc = objWd.Documents.Add

    For i = 1 To UBound(MyArr, 1)
        objWd.Selection.EndKey Unit:=wdStory
        objWd.Selection.TypeText Text:=i & ". " & MyArr(i, 1)
        objWd.Selection.TypeParagraph
        Set myRange = objWd.Selection.Range
        partidx = 1
'number of rows in Word table
        For partidxtmp = 2 To UBound(MyArr, 2)
            If Not MyArr(i, partidxtmp) = vbNullString Then
                partidx = partidx + 1
            End If
        Next partidxtmp

        objDoc.Tables.Add Range:=myRange, NumRows:=partidx - 1, NumColumns:=1

        For partidxtmp = 1 To partidx - 1
            objDoc.Tables(i).Cell(partidxtmp, 1).Range.Text = MyArr(i, partidxtmp + 1)
        Next partidxtmp

        Set myRange = objDoc.Tables(i).Range
        myRange.EndOf wdStory, wdMove
        myRange.InsertAfter vbCr
    Next i

    Set objDoc = Nothing
    Set objWd = Nothing

End Sub
</code>```

Title: vba excel list to word with chapters

Body:
Following code will load data from Excel into 2D array. First the dimensions of the array are determined, than the data is saved into the array. New Word document is created and data from array is saved to Word file. Every first item from the array is saved as new paragraph, other data is saved in the table. No Word formating is done.

Option Base 1
Option Explicit
Sub TwoD_Tbl_to_Word()
    Dim MyArr() As String
    Dim comidx As Long
    Dim partidx As Long
    Dim partidxtmp As Long
    Dim i As Long
    Dim teststr As String

    Dim objWd As Word.Application
    Dim objDoc As Word.Document
    Dim myRange As Word.Range

    teststr = Cells(5, 2)
    comidx = 1
    partidx = 1
    partidxtmp = 1

'detect 2D Array Indexes
    For i = 6 To ActiveSheet.Columns("B").Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
        If Cells(i, 2) = teststr Then
            partidxtmp = partidxtmp + 1
        Else
        teststr = Cells(i, 2)
        If partidxtmp > partidx Then
            partidx = partidxtmp
        End If
        partidxtmp = 1
        comidx = comidx + 1
        End If
    Next i

'if the last item is the biggest
    If partidxtmp > partidx Then
        partidx = partidxtmp
    End If
'redefine array
    ReDim MyArr(comidx, partidx + 1)

'load Excel into Array
    teststr = Cells(5, 2)
    MyArr(1, 1) = Cells(5, 2)
    MyArr(1, 2) = Cells(5, 3)
    partidxtmp = 2
    comidx = 1

    For i = 6 To ActiveSheet.Columns("B").Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
        If Cells(i, 2) = teststr Then
           partidxtmp = partidxtmp + 1
           MyArr(comidx, partidxtmp) = Cells(i, 3)
        Else
           comidx = comidx + 1
           teststr = Cells(i, 2)
           MyArr(comidx, 1) = Cells(i, 2)
           MyArr(comidx, 2) = Cells(i, 3)
           partidxtmp = 2
        End If
    Next i
'Create Word
    Set objWd = CreateObject("word.application")
    objWd.Visible = True
    Set objDoc = objWd.Documents.Add

    For i = 1 To UBound(MyArr, 1)
        objWd.Selection.EndKey Unit:=wdStory
        objWd.Selection.TypeText Text:=i & ". " & MyArr(i, 1)
        objWd.Selection.TypeParagraph
        Set myRange = objWd.Selection.Range
        partidx = 1
'number of rows in Word table
        For partidxtmp = 2 To UBound(MyArr, 2)
            If Not MyArr(i, partidxtmp) = vbNullString Then
                partidx = partidx + 1
            End If
        Next partidxtmp

        objDoc.Tables.Add Range:=myRange, NumRows:=partidx - 1, NumColumns:=1

        For partidxtmp = 1 To partidx - 1
            objDoc.Tables(i).Cell(partidxtmp, 1).Range.Text = MyArr(i, partidxtmp + 1)
        Next partidxtmp

        Set myRange = objDoc.Tables(i).Range
        myRange.EndOf wdStory, wdMove
        myRange.InsertAfter vbCr
    Next i

    Set objDoc = Nothing
    Set objWd = Nothing

End Sub


问:
How do I create an intent to launch any e-mail app?
I have found various topics here and elsewhere on creating an intent for sending e-mail and that seems to be pretty straightforward. I'm looking for an intent to just launch any e-mail client the user might have.

Here is the code I've seen for sending an e-mail (posted just for reference, this doesn't serve my needs as I don't want to send a new message):

```<code>Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"recipient@example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "Subject of the message");
i.putExtra(Intent.EXTRA_TEXT   , "Body of the message");
</code>```

Here is the code I put together for specifically launching the Gmail client by package name:

```<code>PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.google.android.gm");
startActivity(intent);
</code>```

The code above works but isn't flexible in that a user might not be using Gmail but the other built-in e-mail application or a 3rd party e-mail app. I'm looking for an intent that would bring up the chooser in this case so the user can decide which app to launch to read e-mail.

Does anyone know how to accomplish this?

答:
Can a mailto URL be used in some fashion to accomplish this?
--Edit--
I was able to accomplish this using the following code sample:</p>

```<code>mt = MailTo.parse("mailto:yourname@gmail.com");
sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{mt.getTo()});
sendIntent.putExtra(Intent.EXTRA_TEXT, "");
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Enter a subject");
sendIntent.setType("message/rfc822");
startActivity(Intent.createChooser(sendIntent, "Send a Message:"));
</code>```

Body:
I have found various topics here and elsewhere on creating an intent for sending e-mail and that seems to be pretty straightforward. I'm looking for an intent to just launch any e-mail client the user might have.

Here is the code I've seen for sending an e-mail (posted just for reference, this doesn't serve my needs as I don't want to send a new message):

Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"recipient@example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "Subject of the message");
i.putExtra(Intent.EXTRA_TEXT   , "Body of the message");

Here is the code I put together for specifically launching the Gmail client by package name:

PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.google.android.gm");
startActivity(intent);

The code above works but isn't flexible in that a user might not be using Gmail but the other built-in e-mail application or a 3rd party e-mail app. I'm looking for an intent that would bring up the chooser in this case so the user can decide which app to launch to read e-mail.

Does anyone know how to accomplish this?

Body:
Can a mailto URL be used in some fashion to accomplish this?
--Edit--
I was able to accomplish this using the following code sample:

mt = MailTo.parse("mailto:yourname@gmail.com");
sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{mt.getTo()});
sendIntent.putExtra(Intent.EXTRA_TEXT, "");
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Enter a subject");
sendIntent.setType("message/rfc822");
startActivity(Intent.createChooser(sendIntent, "Send a Message:"));


问:
How to pass component's state to the navigationOptions in react native (react navigation)
I am trying to pass a state to the top bar inside react native navigation.

Here is how my component looks:

```<code>export default class Main extends Component {
    constructor() {
    super()
    this.state = {
        value: ""
    };
  }

    static navigationOptions = {

    tabBarLabel: () => (
        <View style={styles.container}>
        <Text style={styles.text}>
{this.state.value}
        </Text>
        </View>
    ),
  };
}
</code>```

I am receiving an error Type Error: Cannot read property 'value' of undefined on line {this.state.value}. Am I doing something wrong?

答:
Yeah, this is one of the pain points of react-navigation. The static keyword indicates that this object is a part of the class Main, but does not require an instance of the class to run. So you could invoke it like so:

```<code>Main.navigationOptions.tabBarLabel()
</code>```

This means that you can't refer to component state from functions declared as properties of the navigationOptions object. What you can do is call navigation.setParams({ foo: ... }) from, say, componentDidMount or other lifecycle functions if you need to alter a title or label from within the component.

I try to steer clear of this kind of update as much as possible, as it can appear somewhat slow to the user if the value isn't defined before the component mounts.

Body:
I am trying to pass a state to the top bar inside react native navigation.

Here is how my component looks:

export default class Main extends Component {
    constructor() {
    super()
    this.state = {
        value: ""
    };
  }

    static navigationOptions = {

    tabBarLabel: () => (
        <View style={styles.container}>
        <Text style={styles.text}>
{this.state.value}
        </Text>
        </View>
    ),
  };
}

I am receiving an error Type Error: Cannot read property 'value' of undefined on line {this.state.value}. Am I doing something wrong?

Body:
Yeah, this is one of the pain points of react-navigation. The static keyword indicates that this object is a part of the class Main, but does not require an instance of the class to run. So you could invoke it like so:

Main.navigationOptions.tabBarLabel()

This means that you can't refer to component state from functions declared as properties of the navigationOptions object. What you can do is call navigation.setParams({ foo: ... }) from, say, componentDidMount or other lifecycle functions if you need to alter a title or label from within the component.

I try to steer clear of this kind of update as much as possible, as it can appear somewhat slow to the user if the value isn't defined before the component mounts.


问:
Asynchronous scope
There is something I didn't really understand clearly, If somebody could help me:

```<code>let arr = [1,2,3,4,5,6,7];

let b = 0
for (let a of arr) {
    setTimeout(() => {
        console.log(b, a)
    }, 2000)
    b = b + 1;
}
/* Output
7 1
7 2
7 3
7 4
7 5
7 6
7 7
*/
</code>```

Let's say b is equal to 7 because 2 seconds later, the variable b is equal to 7, then why a has a different behaviour than b ?

答:
The difference is how scoped variables work with the let keyword. In this case, you are defining a new a for each iteration of the loop. But it is the same b variable for every iteration.

The timeouts don't actually start firing until after the loop ends. By this time, each timeout function scope was given a different a, but are grabbing the same final value of b.

Title: Asynchronous scope

Body:
There is something I didn't really understand clearly, If somebody could help me:

let arr = [1,2,3,4,5,6,7];

let b = 0
for (let a of arr) {
    setTimeout(() => {
        console.log(b, a)
    }, 2000)
    b = b + 1;
}
/* Output
7 1
7 2
7 3
7 4
7 5
7 6
7 7
*/

Let's say b is equal to 7 because 2 seconds later, the variable b is equal to 7, then why a has a different behaviour than b ?


问:
is it possible variable inhrit the my turtles label
i want my variable to inherit the label of my turtles.

im making routes for them and want them to remember the last place they visited.

so theyll continue to the next place in the chain.

```<code>ifelse last_place = home

[set place min-one-of (turtles with [label = "mall"])[distancemyself]]

[set place min-one-of (turtles with [label = "home"])[distancemyself]]
</code>```

i cant use my actual code in here but hopefully, you get the gist

if

```<code>place = one-of turtles with [label = "mallI]
</code>```

I want to add

set last_place label of place

i want last_place to get the label of place.

i know it can create loops if i have the same place twice in the same route but i want to create a list to prevent them but right now i need a sort of where flag that will make my turtles keep going to the end.

答:
Hard to say without seeing more of your code- it's hard to know what turtle is doing what. If your code is sensitive, I'd recommend following the tips in the MCVE guidelines to make a reproducible example- it might be easier to address your exact problem that way!

As an alternative, instead of using a label it's probably better to just have the turtles store the "location" turtle or patch in a turtle-variable. Using this simple example setup:

```<code>breed [ walkers walker ]
breed [ locations location ]

walkers-own [ location-list ]

to setup
  ca
  create-walkers 10 [
    setxy random-pxcor random-pycor
    set location-list []
    pd
  ]
  create-locations 20 [
    set size 1.5
    set shape "house"
    setxy random-pxcor random-pycor
  ]
  reset-ticks
end
</code>```

You can have turtles store the places they visit in a list and reference them that way.

```<code>to go
  ask walkers [

    ; Build an agrentset of locations that do not belong
    ; to each turtle's 'location-list'
    let unvisited-locations locations with [
      not member? self [location-list] of myself
    ]

    ; Target the nearest unvisited location
    let target min-one-of unvisited-locations [ distance myself ]

    ; if the target exists, move towards it
    if target != nobody [
      face target
      ifelse distance target > 1 [
        fd 1
      ] [
        move-to target
        set location-list lput target location-list
      ]
    ]

    ; if a turtle visits all locations, remove the
    ; first location visited from the 'location-list'
    ; so that it will follow the same pattern continuously
    if length location-list = count locations [
      set location-list but-first location-list
    ]
  ]
  tick
end
</code>```

Body:
i want my variable to inherit the label of my turtles.

im making routes for them and want them to remember the last place they visited.

so theyll continue to the next place in the chain.

ifelse last_place = home

[set place min-one-of (turtles with [label = "mall"])[distancemyself]]

[set place min-one-of (turtles with [label = "home"])[distancemyself]]

i cant use my actual code in here but hopefully, you get the gist

if

place = one-of turtles with [label = "mallI]

I want to add

set last_place label of place

i want last_place to get the label of place.

i know it can create loops if i have the same place twice in the same route but i want to create a list to prevent them but right now i need a sort of where flag that will make my turtles keep going to the end.

Body:
Hard to say without seeing more of your code- it's hard to know what turtle is doing what. If your code is sensitive, I'd recommend following the tips in the MCVE guidelines to make a reproducible example- it might be easier to address your exact problem that way!

As an alternative, instead of using a label it's probably better to just have the turtles store the "location" turtle or patch in a turtle-variable. Using this simple example setup:

breed [ walkers walker ]
breed [ locations location ]

walkers-own [ location-list ]

to setup
  ca
  create-walkers 10 [
    setxy random-pxcor random-pycor
    set location-list []
    pd
  ]
  create-locations 20 [
    set size 1.5
    set shape "house"
    setxy random-pxcor random-pycor
  ]
  reset-ticks
end

You can have turtles store the places they visit in a list and reference them that way.

to go
  ask walkers [

    ; Build an agrentset of locations that do not belong
    ; to each turtle's 'location-list'
    let unvisited-locations locations with [
      not member? self [location-list] of myself
    ]

    ; Target the nearest unvisited location
    let target min-one-of unvisited-locations [ distance myself ]

    ; if the target exists, move towards it
    if target != nobody [
      face target
      ifelse distance target > 1 [
        fd 1
      ] [
        move-to target
        set location-list lput target location-list
      ]
    ]

    ; if a turtle visits all locations, remove the
    ; first location visited from the 'location-list'
    ; so that it will follow the same pattern continuously
    if length location-list = count locations [
      set location-list but-first location-list
    ]
  ]
  tick
end


问:
Jest test: "state.get is not a function"
I'm trying to test Counter reducer with jest, but I get TypeError: state.get is not a function when dispatching INCREMENT.
Here's my code...

```<code>// module.js
import { fromJS } from 'immutable';
...

const initialState = fromJS({
  value: 0,
});

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case INCREMENT:
      return state.set('value', state.get('value') + 1);
    case DECREMENT:
      return state.set('value', state.get('value') - 1);
    case INCREMENT_IF_ODD:
      return (state % 2 !== 0) ? state.set('value', state.get('value') + 1) : state;
    default:
      return state;
  }
}

// module.test.js
import { fromJS } from 'immutable';

import reducer, { types } from './module';

const { INCREMENT, DECREMENT, INCREMENT_IF_ODD } = types;

describe('Counter reducer', () => {
  it('should return the initial state', () => {
    expect(reducer(undefined, {})).toEqual(fromJS({
      value: 0,
    }));
  });

  it(`should handle ${INCREMENT}`, () => {
    expect(reducer(0, { type: INCREMENT })).toEqual(fromJS({
      value: 1,
    }));
  });

  ...
});
</code>```

I don't get what's the problem with my code since it's working fine running on browser.

Here's the errors

```<code> FAIL  src/containers/Counter/module.test.js
  ● Counter reducer › should handle Counter/INCREMENT

    TypeError: state.get is not a function

      at reducer (src/containers/Counter/module.js:34:50)
      at Object.<anonymous> (src/containers/Counter/module.test.js:25:33)
          at new Promise (<anonymous>)
          at <anonymous>
</code>```

答:
Error is because store passed to reducer is 0, so inside reducer function try to do 0.get(..).
First arg passed to reducer should be initial store:

```<code>it(`should handle ${INCREMENT}`, () => {
  const initialState = fromJS({
    value: 0,
  });

  expect(reducer(initialState, { type: INCREMENT })).toEqual(fromJS({
    value: 1,
  }));
});
</code>```

Body:
I'm trying to test Counter reducer with jest, but I get TypeError: state.get is not a function when dispatching INCREMENT.
Here's my code...

// module.js
import { fromJS } from 'immutable';
...

const initialState = fromJS({
  value: 0,
});

export default function reducer(state = initialState, action) {
  switch (action.type) {
    case INCREMENT:
      return state.set('value', state.get('value') + 1);
    case DECREMENT:
      return state.set('value', state.get('value') - 1);
    case INCREMENT_IF_ODD:
      return (state % 2 !== 0) ? state.set('value', state.get('value') + 1) : state;
    default:
      return state;
  }
}

// module.test.js
import { fromJS } from 'immutable';

import reducer, { types } from './module';

const { INCREMENT, DECREMENT, INCREMENT_IF_ODD } = types;

describe('Counter reducer', () => {
  it('should return the initial state', () => {
    expect(reducer(undefined, {})).toEqual(fromJS({
      value: 0,
    }));
  });

  it(`should handle ${INCREMENT}`, () => {
    expect(reducer(0, { type: INCREMENT })).toEqual(fromJS({
      value: 1,
    }));
  });

  ...
});

I don't get what's the problem with my code since it's working fine running on browser.

Here's the errors

 FAIL  src/containers/Counter/module.test.js
  ● Counter reducer › should handle Counter/INCREMENT

    TypeError: state.get is not a function

      at reducer (src/containers/Counter/module.js:34:50)
      at Object.<anonymous> (src/containers/Counter/module.test.js:25:33)
          at new Promise (<anonymous>)
          at <anonymous>

Body:
Error is because store passed to reducer is 0, so inside reducer function try to do 0.get(..).
First arg passed to reducer should be initial store:

it(`should handle ${INCREMENT}`, () => {
  const initialState = fromJS({
    value: 0,
  });

  expect(reducer(initialState, { type: INCREMENT })).toEqual(fromJS({
    value: 1,
  }));
});


问:
Public Datasets on Azure Data Lake Store to use with Data Lake Analytics
Does Azure Data Lake store Public Datasets to use with Azure Data Lake Analytics? Google BigQuery provides public datasets, something similar to that, so that it would be easy to create tables.</p>

答:
Thanks for reaching out.  Today we don't yet have broadly available public data-sets.  This is something that we are working on, but I don't have a timeframe that I can share.

Thank you,
Guy


问:
Move SELECT to SQL Server side
I have an SQLCLR trigger. It contains a large and messy SELECT inside, with parts like:

```<code>(CASE WHEN EXISTS(SELECT * FROM INSERTED I WHERE I.ID = R.ID)
THEN '1' ELSE '0' END) AS IsUpdated -- Is selected row just added?
</code>```

as well as JOINs etc. I like to have the result as a single table with all included.

Question 1. Can I move this SELECT to SQL Server side? If yes, how to do this?

Saying "move", I mean to create a stored procedure or something else that can be executed before reading dataset in while cycle.

The 2 following questions make sense only if answer is "yes".

Why do I want to move SELECT? First off, I don't like mixing SQL with C# code. At second, I suppose that server-side queries run faster, since the server have more chances to cache them.

Question 2. Am I right? Is it some sort of optimizing?

Also, the SELECT contains constant strings, but they are localizable. For instance,

```<code>WHERE R.Status = "Enabled"
</code>```

"Enabled" should be changed for French, German etc. So, I want to write 2 static methods -- OnCreate and OnDestroy -- then mark them as stored procedures. When registering/unregistering my assembly on server side, just call them respectively. In OnCreate format the SELECT string, replacing {0}, {1}... with required values from the assembly resources. Then I can localize resources only, not every script.

Question 3. Is it good idea? Is there an existing attribute to mark methods to be executed by SQL Server automatically after (un)registartion an assembly?

Regards,

答:
To start with, you probably do not need to do that type of subquery inside of whatever query you are doing.  The INSERTED table only has rows that have been updated (or inserted but we can assume this is an UPDATE Trigger based on the comment in your code).  So you can either INNER JOIN and you will only match rows in the Table with the alias of "R" or you can LEFT JOIN and you can tell which rows in R have been updated as the ones showing NULL for all columns were not updated.

Question 1) As marc_s said below, the Trigger executes in the context of the database.  But it goes beyond that.  ALL database related code, including SQLCLR executes in the database.  There is no client-side here.  This is the issue that most people have with SQLCLR: it runs inside of the SQL Server context.  And regarding wanting to call a Stored Proc from the Trigger: it can be done BUT the INSERTED and DELETED tables only exist within the context of the Trigger itself.

Question 2) It appears that this question should have started with the words "Also, the SELECT".  There are two things to consider here.  First, when testing for "Status" values (or any Lookup values) since this is not displayed to the user you should be using numeric values.  A "status" of "Enabled" should be something like "1" so that the language is not relevant.  A side benefit is that not only will storing Status values as numbers take up a lot less space, but they also compare much faster.  Second is that any text that is to be displayed to the user that needs to be sensitive to language differences should be in a table so that you can pass in a LanguageId or LocaleId to get the appropriate French, German, etc. strings to display.  You can set the LocaleId of the user or system in general in another table.

Question 3) If by "registration" you mean that the Assembly is either CREATED or DROPPED, then you can trap those events via DDL Triggers.  You can look here for some basics:

http://msdn.microsoft.com/en-us/library/ms175941(v=SQL.90).aspx

But CREATE ASSEMBLY and DROP ASSEMBLY are events that are trappable.

If you are speaking of when Assemblies are loaded and unloaded from memory, then I do not know of a way to trap that.

Title: Move SELECT to SQL Server side

Body:
I have an SQLCLR trigger. It contains a large and messy SELECT inside, with parts like:

(CASE WHEN EXISTS(SELECT * FROM INSERTED I WHERE I.ID = R.ID)
THEN '1' ELSE '0' END) AS IsUpdated -- Is selected row just added?

as well as JOINs etc. I like to have the result as a single table with all included.

Question 1. Can I move this SELECT to SQL Server side? If yes, how to do this?

Saying "move", I mean to create a stored procedure or something else that can be executed before reading dataset in while cycle.

The 2 following questions make sense only if answer is "yes".

Why do I want to move SELECT? First off, I don't like mixing SQL with C# code. At second, I suppose that server-side queries run faster, since the server have more chances to cache them.

Question 2. Am I right? Is it some sort of optimizing?

Also, the SELECT contains constant strings, but they are localizable. For instance,

WHERE R.Status = "Enabled"

"Enabled" should be changed for French, German etc. So, I want to write 2 static methods -- OnCreate and OnDestroy -- then mark them as stored procedures. When registering/unregistering my assembly on server side, just call them respectively. In OnCreate format the SELECT string, replacing {0}, {1}... with required values from the assembly resources. Then I can localize resources only, not every script.

Question 3. Is it good idea? Is there an existing attribute to mark methods to be executed by SQL Server automatically after (un)registartion an assembly?

Regards,