问:
RxJava2 in CursorLoader’s onLoadFinished callback
To get data from database I use CursorLoader in the app. Once onLoadFinished() callback method calls the logic of app converts Cursor object to List of objects within business model requirements. That conversion (heavy operation) takes some time if there is a lot of data. That slows UI thread. I tried to start conversion in non-UI Thread using RxJava2 passing Cursor object, but got Exception:

```<code>Caused by: android.database.StaleDataException: Attempting to access a closed CursorWindow.Most probable cause: cursor is deactivated prior to calling this method.
</code>```

Here is the part of Fragment's code:

```<code>@Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        QueryBuilder builder;
        switch (id) {
            case Constants.FIELDS_QUERY_TOKEN:
                builder = QueryBuilderFacade.getFieldsQB(activity);
                return new QueryCursorLoader(activity, builder);
            default:
                return null;
        }
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        if (cursor.getCount() > 0) {
            getFieldsObservable(cursor)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this::showFields);
        } else {
            showNoData();
        }
    }

private static Observable<List<Field>> getFieldsObservable(Cursor cursor) {
            return Observable.defer(() -> Observable.just(getFields(cursor))); <-- Exception raised at this line

        }

private static List<Field> getFields(Cursor cursor) {
            List<Field> farmList = CursorUtil.cursorToList(cursor, Field.class);
            CursorUtil.closeSafely(cursor);
            return farmList;
        }
</code>```

The purpose of using CursorLoader here is to get notifications from DB if there is data store updated.

Update
As Tin Tran suggested, I removed CursorUtil.closeSafely(cursor); and now I get another exception:

```<code>Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: /data/user/0/com.my.project/databases/db_file
                                                          at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
                                                          at android.database.CursorWindow.getNumRows(CursorWindow.java:225)
                                                          at android.database.sqlite.SQLiteCursor.onMove(SQLiteCursor.java:121)
                                                          at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:236)
                                                          at android.database.AbstractCursor.moveToNext(AbstractCursor.java:274)
                                                          at android.database.CursorWrapper.moveToNext(CursorWrapper.java:202)
                                                          at com.db.util.CursorUtil.cursorToList(CursorUtil.java:44)
                                                          at com.my.project.MyFragment.getFields(MyFragment.java:230)
</code>```

cursorToList() method of CursorUtil

```<code>public static <T> ArrayList<T> cursorToList(Cursor cursor, Class<T> modelClass) {
        ArrayList<T> items = new ArrayList<T>();
        if (!isCursorEmpty(cursor)) {
            while (cursor.moveToNext()) { <-- at this line (44) of the method raised that issue
                final T model = buildModel(modelClass, cursor);
                items.add(model);
            }
        }
        return items;
    }
</code>```

答:
The loader will release the data once it knows the application is no longer using it. For example, if the data is a cursor from a CursorLoader, you should not call close() on it yourself.
  From: https://developer.android.com/guide/components/loaders.html

You should not close the cursor yourself which I think CursorUtil.closeSafely(cursor) does.

You can use switchMap operator to implement that. It does exactly what we want

```<code>private PublishSubject<Cursor> cursorSubject = PublishSubject.create()

public void onCreate(Bundle savedInstanceState) {
    cursorSubject
        .switchMap(new Func1<Cursor, Observable<List<Field>>>() {
             @Override public Observable<List<Field>> call(Cursor cursor) {
                  return getFieldsObservable(cursor);
             }
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(this::showFields);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    cursorSubject.onNext(cursor)
}
</code>```

You now need to modify showFields to and getFieldsObservable to account for empty Cursor

Body:
To get data from database I use CursorLoader in the app. Once onLoadFinished() callback method calls the logic of app converts Cursor object to List of objects within business model requirements. That conversion (heavy operation) takes some time if there is a lot of data. That slows UI thread. I tried to start conversion in non-UI Thread using RxJava2 passing Cursor object, but got Exception:

Caused by: android.database.StaleDataException: Attempting to access a closed CursorWindow.Most probable cause: cursor is deactivated prior to calling this method.

Here is the part of Fragment's code:

@Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        QueryBuilder builder;
        switch (id) {
            case Constants.FIELDS_QUERY_TOKEN:
                builder = QueryBuilderFacade.getFieldsQB(activity);
                return new QueryCursorLoader(activity, builder);
            default:
                return null;
        }
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        if (cursor.getCount() > 0) {
            getFieldsObservable(cursor)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(this::showFields);
        } else {
            showNoData();
        }
    }

private static Observable<List<Field>> getFieldsObservable(Cursor cursor) {
            return Observable.defer(() -> Observable.just(getFields(cursor))); <-- Exception raised at this line

        }

private static List<Field> getFields(Cursor cursor) {
            List<Field> farmList = CursorUtil.cursorToList(cursor, Field.class);
            CursorUtil.closeSafely(cursor);
            return farmList;
        }

The purpose of using CursorLoader here is to get notifications from DB if there is data store updated.

Update
As Tin Tran suggested, I removed CursorUtil.closeSafely(cursor); and now I get another exception:

Caused by: java.lang.IllegalStateException: attempt to re-open an already-closed object: /data/user/0/com.my.project/databases/db_file
                                                          at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
                                                          at android.database.CursorWindow.getNumRows(CursorWindow.java:225)
                                                          at android.database.sqlite.SQLiteCursor.onMove(SQLiteCursor.java:121)
                                                          at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:236)
                                                          at android.database.AbstractCursor.moveToNext(AbstractCursor.java:274)
                                                          at android.database.CursorWrapper.moveToNext(CursorWrapper.java:202)
                                                          at com.db.util.CursorUtil.cursorToList(CursorUtil.java:44)
                                                          at com.my.project.MyFragment.getFields(MyFragment.java:230)

cursorToList() method of CursorUtil

public static <T> ArrayList<T> cursorToList(Cursor cursor, Class<T> modelClass) {
        ArrayList<T> items = new ArrayList<T>();
        if (!isCursorEmpty(cursor)) {
            while (cursor.moveToNext()) { <-- at this line (44) of the method raised that issue
                final T model = buildModel(modelClass, cursor);
                items.add(model);
            }
        }
        return items;
    }

Body:
The loader will release the data once it knows the application is no longer using it. For example, if the data is a cursor from a CursorLoader, you should not call close() on it yourself.
  From: https://developer.android.com/guide/components/loaders.html

You should not close the cursor yourself which I think CursorUtil.closeSafely(cursor) does.

You can use switchMap operator to implement that. It does exactly what we want

private PublishSubject<Cursor> cursorSubject = PublishSubject.create()

public void onCreate(Bundle savedInstanceState) {
    cursorSubject
        .switchMap(new Func1<Cursor, Observable<List<Field>>>() {
             @Override public Observable<List<Field>> call(Cursor cursor) {
                  return getFieldsObservable(cursor);
             }
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(this::showFields);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    cursorSubject.onNext(cursor)
}

You now need to modify showFields to and getFieldsObservable to account for empty Cursor


来源: stackexchange

问:
Multiple Models in View by ViewModel
I am beginner in ASP.NET MVC and trying to add multiple models in view by using ViewModel.cs but I can't get it in my view Index.cshtml anyone can guide me how can I get it?

ViewModel.cs

```<code>public class ViewModel
    {
        public IEnumerable<ContactLens.Models.manufacturer> manufacturer {get; set;}
        public IEnumerable<ContactLens.Models.brand> brand { get; set; }
    }
</code>```

HomeController.cs

```<code>public class HomeController : Controller
    {
        private Entities db = new Entities();

        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to my demo!";
            ViewModel mymodel = new ViewModel();
            mymodel.manufacturer = db.manufacturers.ToList();
            mymodel.brand = db.brands.ToList();
            return View(mymodel);
        }
     }
</code>```

Index.cshtml

```<code>@model ViewModel
@{
    ViewBag.Title = "Home Page";
}
     --------
<h3 class="menu_head">Top Manufacturers</h3>
 <ul class="menu">
        @foreach (var manufacturer in Model)
        {
           <li class="item1">
           <a href="#"><img class="arrow-img" src="images/f_menu.png" alt="" /> @manufacturer.man_name </a>
           </li>
        }
</ul>
 <h3 class="menu_head">Top Brands</h3>
  <ul class="menu">
         @foreach (var brand in Model)
         {
           <li class="item1">
           <a href="#"><img class="arrow-img" src="images/f_menu.png" alt="" /> @brand.brand_name </a>
           </li>
         }
</ul>
  -------
</code>```

It is showing me an error at @model ViewModeldue to it, I can't access models in Index.cshtml.

答:
it should be

```<code>@model [Full Path of Your Model]
</code>```

So in your case it might be:

```<code>@model [SolutionName].[ModelDirectoryIfAny].[Model]
</code>```

Edit

```<code>@{
    ViewBag.Title = "Home Page";
}
     --------
<h3 class="menu_head">Top Manufacturers</h3>
 <ul class="menu">
        @foreach (var manufacturer in Model.manufacturer)
        {

        }
</ul>
 <h3 class="menu_head">Top Brands</h3>
  <ul class="menu">
         @foreach (var brand in Model.brand)
         {

         }
</ul>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Multiple Models in View by ViewModel

Body:
I am beginner in ASP.NET MVC and trying to add multiple models in view by using ViewModel.cs but I can't get it in my view Index.cshtml anyone can guide me how can I get it?

ViewModel.cs

public class ViewModel
    {
        public IEnumerable<ContactLens.Models.manufacturer> manufacturer {get; set;}
        public IEnumerable<ContactLens.Models.brand> brand { get; set; }
    }

HomeController.cs

public class HomeController : Controller
    {
        private Entities db = new Entities();

        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to my demo!";
            ViewModel mymodel = new ViewModel();
            mymodel.manufacturer = db.manufacturers.ToList();
            mymodel.brand = db.brands.ToList();
            return View(mymodel);
        }
     }

Index.cshtml

@model ViewModel
@{
    ViewBag.Title = "Home Page";
}
     --------

Top Manufacturers

        @foreach (var manufacturer in Model)
        {

            @manufacturer.man_name

        }

Top Brands

         @foreach (var brand in Model)
         {

            @brand.brand_name

         }

  -------

It is showing me an error at @model ViewModeldue to it, I can't access models in Index.cshtml.

Body:
it should be

@model [Full Path of Your Model]

So in your case it might be:

@model [SolutionName].[ModelDirectoryIfAny].[Model]

Edit

@{
    ViewBag.Title = "Home Page";
}
     --------
<h3 class="menu_head">Top Manufacturers</h3>
 <ul class="menu">
        @foreach (var manufacturer in Model.manufacturer)
        {

        }
</ul>
 <h3 class="menu_head">Top Brands</h3>
  <ul class="menu">
         @foreach (var brand in Model.brand)
         {

         }
</ul>


问:
jquery .css script doesn't work
Morning,
I'm trying to display a div onmouseover. I created a function but i don't know what is wrong. Could you help me please.

The HTML code:

```<code><!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="utf-8">
    <title> PHOTOGALLERY</title>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <link rel="stylesheet" href="css/smoothness/jquery-ui-
         1.9.2.custom.css"/>
    <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
    <script src="http://malsup.github.com/jquery.cycle2.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.9.2.custom.js">
    </script>
    <script>
        function show_img_container() {
            $("#image_container").css("display", "block");
        }
    </script>
</head>
<body>
    <div id="div_container">
        <div id="div_image" class="cycle-slideshow">
            <img src="images/2.jpg" style="height:100%; width:100%">
            <img src="images/3.jpg" style="height:100%; width:100%">
            <img src="images/4.jpg" style="height:100%; width:100%">
            <img src="images/5.jpg" style="height:100%; width:100%">
        </div>
        <div id="image_container" onmouseover="show_img_container()"></div>
    </div>
</body>
</html>
</code>```

In the css file i have a image_container id where the attribute display is set to 'none';

答:
In the css file i have a image_container id where the attribute display is set to 'none';

It is not possible to hover a none blocked element.

You can use the opacity attribute to hide your div.

div {
    opacity: 0;
}

div:hover {
    opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>Stuff shown on hover</div></code>```

Title: jquery .css script doesn't work

Body:
Morning,
I'm trying to display a div onmouseover. I created a function but i don't know what is wrong. Could you help me please.

The HTML code:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title> PHOTOGALLERY</title>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <link rel="stylesheet" href="css/smoothness/jquery-ui-
         1.9.2.custom.css"/>

In the css file i have a image_container id where the attribute display is set to 'none';

Body:
In the css file i have a image_container id where the attribute display is set to 'none';

It is not possible to hover a none blocked element.

You can use the opacity attribute to hide your div.

div {
    opacity: 0;
}

div:hover {
    opacity: 1;
}

<div>Stuff shown on hover</div>


问:
How could I check if string is only match into an other string
I'm actually a beginner into web developpment.

I have a problem with my actual condition.

Exemple :

```<code>$rooms = 10;
</code>```

In my code, I check if $rooms is equal to 1,0 or 10 so :

```<code>if(strpos($rooms, '1')){echo 1;}
if(strpos($rooms, '0')){echo 0};
if(strpos($rooms, '10')){echo 10;}
</code>```

My result :

```<code>1
0
10
</code>```

My condition match for 1, 0 and 10, where I only need to match the number 10

How can I only pass into my third condition ?

Thx

答:
You can see from php documentation that strpos is just getting you the index of a substring in a string.

If you want to comepare string just use compare string functions:

```<code>if (strcmp($var1, $var2) == 0) echo 'we are equal';
</code>```

Here you should check the documentation of string compare.

Body:
I'm actually a beginner into web developpment.

I have a problem with my actual condition.

Exemple :

$rooms = 10;

In my code, I check if $rooms is equal to 1,0 or 10 so :

if(strpos($rooms, '1')){echo 1;}
if(strpos($rooms, '0')){echo 0};
if(strpos($rooms, '10')){echo 10;}

My result :

1
0
10

My condition match for 1, 0 and 10, where I only need to match the number 10

How can I only pass into my third condition ?

Thx

Body:
You can see from php documentation that strpos is just getting you the index of a substring in a string.

If you want to comepare string just use compare string functions:

if (strcmp($var1, $var2) == 0) echo 'we are equal';

Here you should check the documentation of string compare.


问:
Java OO static ultility method help!
I recently did a method in the User class which looks like this;

```<code>  public static boolean checkUN(String username) {
  boolean check = false;
  ResultSet rs;
  String dbQuery;
  SQLController db = new SQLController();
  db.setUp();
  dbQuery = "SELECT * FROM User WHERE User_name ='" + username + "'";
  try {
   db.setUp();
   rs = db.readRequest(dbQuery);
   if (rs.next()) {
    check = true;
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  db.terminate();
  return check;
 }
</code>```

I intended it to be a validation check before the User is able to continue to the next step of registration.

When I showed it to the teacher, she said that it would be ok, as im using it as a ultility method. However, she changed her mind later on, saying that I should change this to an instance method, then creating a new User object to do the validation.

Which way is more effective?

```<code>user.checkUsername(jTextUN.getText());
</code>```

and the instance way
(assuming I changed the method, removing static and the input parameter);

```<code>User user = new User();
user.setUsername(jTextUN.getText());
user.checkUsername();
</code>```

Cheers!

答:
First off, I don't like the solution that involves creating a new User object and then calling checkUsername() on it for several reasons:

If no valid user exists with a given username, you shouldn't have any User object representing that user... because they don't exist. This isn't a hard and fast rule, since sometimes you might want a User object representing a user you're about to create or some such, but here I find it unnatural.

It violates expectations about what data objects can do. Creating a new User() and then having checkUsername() return different values depending on what username that user is given would be surprising.

Now, I know you're in a class and so this may go beyond what you're learning, but to go even further:

Neither solution seems very good to me because both tightly couple any code that uses them to the database, making that code difficult to test.

The general solution to this is to wrap the code that would make components that use it difficult to test in an interface, something like this:

```<code>public interface UserService {
  boolean checkUsername(String username);
  ...
}
</code>```

Then you can create an implementation of UserService that talks to the database, and classes that need to use that code can have an implementation of it injected in their constructors:

```<code>public class UserServiceClient {
  private final UserService userService;

  public UserServiceClient(UserService userService) {
    this.userService = userService;
  }

  ...
}
</code>```

This is the principle of dependency injection. In addition to just making your code more flexible, it allows you to provide fake implementations of UserService for testing. If you want to test what happens in a certain class when checkUsername returns true and what happens when it returns false, you can just use fake implementations that always return true or always return false. You don't have to worry about setting up database connections or ensuring that the right data is present or ensuring that the database state is properly reset after a test, and equally importantly a test is far faster when it doesn't have to do database communication.

Another thing you might want to do that falls somewhere in between the two approaches would be to have a User object that stores data on a user (but can't communicate with the database or any such thing itself) and to put a method like this in your UserService:

```<code>User getUser(String username);
</code>```

This method would return the User object for the user with the given username if one existed and null otherwise. You could also implement checkUsername as just

```<code>return getUser(username) != null;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Java OO static ultility method help!

Body:
I recently did a method in the User class which looks like this;

  public static boolean checkUN(String username) {
  boolean check = false;
  ResultSet rs;
  String dbQuery;
  SQLController db = new SQLController();
  db.setUp();
  dbQuery = "SELECT * FROM User WHERE User_name ='" + username + "'";
  try {
   db.setUp();
   rs = db.readRequest(dbQuery);
   if (rs.next()) {
    check = true;
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  db.terminate();
  return check;
 }

I intended it to be a validation check before the User is able to continue to the next step of registration.

When I showed it to the teacher, she said that it would be ok, as im using it as a ultility method. However, she changed her mind later on, saying that I should change this to an instance method, then creating a new User object to do the validation.

Which way is more effective?

user.checkUsername(jTextUN.getText());

and the instance way
(assuming I changed the method, removing static and the input parameter);

User user = new User();
user.setUsername(jTextUN.getText());
user.checkUsername();

Cheers!

Body:
First off, I don't like the solution that involves creating a new User object and then calling checkUsername() on it for several reasons:

If no valid user exists with a given username, you shouldn't have any User object representing that user... because they don't exist. This isn't a hard and fast rule, since sometimes you might want a User object representing a user you're about to create or some such, but here I find it unnatural.

It violates expectations about what data objects can do. Creating a new User() and then having checkUsername() return different values depending on what username that user is given would be surprising.

Now, I know you're in a class and so this may go beyond what you're learning, but to go even further:

Neither solution seems very good to me because both tightly couple any code that uses them to the database, making that code difficult to test.

The general solution to this is to wrap the code that would make components that use it difficult to test in an interface, something like this:

public interface UserService {
  boolean checkUsername(String username);
  ...
}

Then you can create an implementation of UserService that talks to the database, and classes that need to use that code can have an implementation of it injected in their constructors:

public class UserServiceClient {
  private final UserService userService;

  public UserServiceClient(UserService userService) {
    this.userService = userService;
  }

  ...
}

This is the principle of dependency injection. In addition to just making your code more flexible, it allows you to provide fake implementations of UserService for testing. If you want to test what happens in a certain class when checkUsername returns true and what happens when it returns false, you can just use fake implementations that always return true or always return false. You don't have to worry about setting up database connections or ensuring that the right data is present or ensuring that the database state is properly reset after a test, and equally importantly a test is far faster when it doesn't have to do database communication.

Another thing you might want to do that falls somewhere in between the two approaches would be to have a User object that stores data on a user (but can't communicate with the database or any such thing itself) and to put a method like this in your UserService:

User getUser(String username);

This method would return the User object for the user with the given username if one existed and null otherwise. You could also implement checkUsername as just

return getUser(username) != null;


问:
Replace double quotes with space using sed or tr command in windows batch file
I am writing a script in batch file for Windows. I want to replace double quotes with space in a file.

Input file File1.txt contains:

"05-09-2017", "07:00:14"

  "05-09-2017", "07:00:14"

  "05-09-2017", "07:00:14"

  "05-09-2017", "07:00:14"

  "05-09-2017", "07:00:14"

I have tried the following:

```<code>tr.exe "\"" " " < "File1.txt" >  "File2.txt"
</code>```

The above line gives me an error like

tr.exe: too many arguments

And I have also tried:

```<code>sed.exe "s/\"/ /g" "File1.txt" >  "File2.txt"
</code>```

The above gives me an error like

sed.exe: can't read >: Invalid argument

I need output file like this:

05-09-2017 , 07:00:14

  05-09-2017 , 07:00:14

  05-09-2017 , 07:00:14

  05-09-2017 , 07:00:14

  05-09-2017 , 07:00:14

Can you please look into this.

答:
Why using Unix tools and not native Windows commands for this simple task?

```<code>@echo off
if not exist "File1.txt" goto :EOF
setlocal EnableDelayedExpansion
del "File2.txt" 2>nul
for /F "usebackq delims=" %%I in ("File1.txt") do (
    set "Line=%%I"
    set "Line=!Line:"= !"
    echo !Line!>>"File2.txt"
)
endlocal
</code>```

Note: The command FOR as used here skips empty lines and lines starting with a semicolon.

I would replace the double quotes by nothing which means deleting the space character after equal sign.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

del /?

echo /?

endlocal /?

for /?

goto /?

if /?

set /?

setlocal /?

Read also the Microsoft article about Using Command Redirection Operators.

Body:
I am writing a script in batch file for Windows. I want to replace double quotes with space in a file.

Input file File1.txt contains:

"05-09-2017", "07:00:14"

  "05-09-2017", "07:00:14"

  "05-09-2017", "07:00:14"

  "05-09-2017", "07:00:14"

  "05-09-2017", "07:00:14"

I have tried the following:

tr.exe "\"" " " < "File1.txt" >  "File2.txt"

The above line gives me an error like

tr.exe: too many arguments

And I have also tried:

sed.exe "s/\"/ /g" "File1.txt" >  "File2.txt"

The above gives me an error like

sed.exe: can't read >: Invalid argument

I need output file like this:

05-09-2017 , 07:00:14

  05-09-2017 , 07:00:14

  05-09-2017 , 07:00:14

  05-09-2017 , 07:00:14

  05-09-2017 , 07:00:14

Can you please look into this.

Body:
Why using Unix tools and not native Windows commands for this simple task?

@echo off
if not exist "File1.txt" goto :EOF
setlocal EnableDelayedExpansion
del "File2.txt" 2>nul
for /F "usebackq delims=" %%I in ("File1.txt") do (
    set "Line=%%I"
    set "Line=!Line:"= !"
    echo !Line!>>"File2.txt"
)
endlocal

Note: The command FOR as used here skips empty lines and lines starting with a semicolon.

I would replace the double quotes by nothing which means deleting the space character after equal sign.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

del /?

echo /?

endlocal /?

for /?

goto /?

if /?

set /?

setlocal /?

Read also the Microsoft article about Using Command Redirection Operators.


问:
WOPI Host OfficeOnline Word Error: Session expired
Implementing office online in my application (php)...
Excel & powerpoint working like a charme!
If I want to edit a Word Document, I'll get "Session expired" in the editor view.

I've created a log file on my server...

date - request type - missmatch or "ok" - current lock string - request wopi-lock - old wopi lock

```<code>2017-06-08 14:35:00 - CheckFileInfo -- Current Lock:  || X-Wopi-Lock:  || X-Wopi-OldLock:
2017-06-08 14:35:01 - Lock - OK -- Current Lock:  || X-Wopi-Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":4} || X-Wopi-OldLock:
2017-06-08 14:35:01 - GetFile -- Current Lock:  || X-Wopi-Lock:  || X-Wopi-OldLock:
2017-06-08 14:35:01 - Lock - Missmatch -- Current Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":4} || X-Wopi-Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":6,"E":2,"M":"2e113d2cc5e0457f94543c383961bd37","P":"3823A714-066D-4B80-9D32-439DA70147B0"} || X-Wopi-OldLock:
2017-06-08 14:35:01 - Lock - Missmatch -- Current Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":4} || X-Wopi-Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":6,"E":2,"M":"2e113d2cc5e0457f94543c383961bd37","P":"3823A714-066D-4B80-9D32-439DA70147B0"} || X-Wopi-OldLock:
2017-06-08 14:35:01 - Lock - Missmatch -- Current Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":4} || X-Wopi-Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":6,"E":2,"M":"2e113d2cc5e0457f94543c383961bd37","P":"3823A714-066D-4B80-9D32-439DA70147B0"} || X-Wopi-OldLock:
2017-06-08 14:35:05 - Unlock - Missmatch -- Current Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":4} || X-Wopi-Lock: GetCurrentLock-00000000-0000-0000-0000-000000000000 || X-Wopi-OldLock:
</code>```

If I "haked" a 200 response in the "missmatch", the session expired is gone :P
But then, I've no Co-Authoring.

答:
Okay, figured it out! I didn't get the OldLock header as espected beacause it is case sensetive in the header array..

changed $headers['X-Wopi-OldLock'] to $headers['X-Wopi-Oldlock'] and now I'm back in business!

thanks

Body:
Implementing office online in my application (php)...
Excel & powerpoint working like a charme!
If I want to edit a Word Document, I'll get "Session expired" in the editor view.

I've created a log file on my server...

date - request type - missmatch or "ok" - current lock string - request wopi-lock - old wopi lock

2017-06-08 14:35:00 - CheckFileInfo -- Current Lock:  || X-Wopi-Lock:  || X-Wopi-OldLock:
2017-06-08 14:35:01 - Lock - OK -- Current Lock:  || X-Wopi-Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":4} || X-Wopi-OldLock:
2017-06-08 14:35:01 - GetFile -- Current Lock:  || X-Wopi-Lock:  || X-Wopi-OldLock:
2017-06-08 14:35:01 - Lock - Missmatch -- Current Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":4} || X-Wopi-Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":6,"E":2,"M":"2e113d2cc5e0457f94543c383961bd37","P":"3823A714-066D-4B80-9D32-439DA70147B0"} || X-Wopi-OldLock:
2017-06-08 14:35:01 - Lock - Missmatch -- Current Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":4} || X-Wopi-Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":6,"E":2,"M":"2e113d2cc5e0457f94543c383961bd37","P":"3823A714-066D-4B80-9D32-439DA70147B0"} || X-Wopi-OldLock:
2017-06-08 14:35:01 - Lock - Missmatch -- Current Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":4} || X-Wopi-Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":6,"E":2,"M":"2e113d2cc5e0457f94543c383961bd37","P":"3823A714-066D-4B80-9D32-439DA70147B0"} || X-Wopi-OldLock:
2017-06-08 14:35:05 - Unlock - Missmatch -- Current Lock: {"S":"fdcc8cdd-1173-4935-b94b-aca35228a332","F":4} || X-Wopi-Lock: GetCurrentLock-00000000-0000-0000-0000-000000000000 || X-Wopi-OldLock:

If I "haked" a 200 response in the "missmatch", the session expired is gone :P
But then, I've no Co-Authoring.


问:
AWS lambda function retrieving dynamodb data as a error message
I have written simple Lambda function to scan data from dynamodb, but data is getting retrieved with error message tag and lambda function shows message as execution failed

```<code>    var AWS = require('aws-sdk');
    var DOC = require("dynamodb-doc");
    var dynamo = new DOC.DynamoDB();
    exports.handler = function (event, context, callback) {

     var params = {
        TableName: "Movies",
       // ProjectionExpression: "#yr, Movie",
        FilterExpression: "#yr = :thisyear",
        ExpressionAttributeNames: {
        "#yr": "year",
    },
    ExpressionAttributeValues: {
         ":thisyear" : 2009
    }
};

  dynamo.scan(params, function(err, data){
          if (err){
        callback("error occoured");
          }
          else{
        callback(JSON.stringify(data.Items));
          }
  });
  };
</code>```

Result

```<code>{
  "errorMessage": "[{\"year\":2009,\"Movie\":\"Jab tak hai jaan\"}]"
}
</code>```

答:
nodejs callback are typically error-first callbacks. It means that the first parameter is the error message and the second parameter is the result. So when returning the result you need to pass null as the first argument.
eg: callback(null, JSON.stringify(data.Items));

Please refer this article

Body:
I have written simple Lambda function to scan data from dynamodb, but data is getting retrieved with error message tag and lambda function shows message as execution failed

    var AWS = require('aws-sdk');
    var DOC = require("dynamodb-doc");
    var dynamo = new DOC.DynamoDB();
    exports.handler = function (event, context, callback) {

     var params = {
        TableName: "Movies",
       // ProjectionExpression: "#yr, Movie",
        FilterExpression: "#yr = :thisyear",
        ExpressionAttributeNames: {
        "#yr": "year",
    },
    ExpressionAttributeValues: {
         ":thisyear" : 2009
    }
};

  dynamo.scan(params, function(err, data){
          if (err){
        callback("error occoured");
          }
          else{
        callback(JSON.stringify(data.Items));
          }
  });
  };

Result

{
  "errorMessage": "[{\"year\":2009,\"Movie\":\"Jab tak hai jaan\"}]"
}


问:
Show a message when checking a checkbox and show another message when unchecking it
I'm fairly new in Javascript/AngularJS and want to play around with it to learn/understand these languages. On the Angular website there's a little basic to do list script I want to change a little. I've changed it into a checklist of things I need to learn. When i check the checkbox I got a little msg like, 'well done!'. But when I uncheck it, the same msg pops up and that I want to change in something like, 'you sure?'.

I've spent several hours on looking for the answer but couldn't find the answer so I hope someone can help me figuring out how to do this. This is my code:

HTML:

```<code>      <div ng-controller="TodoListController as todoList">
        <span>Nog {{todoList.remaining()}} van de {{todoList.todos.length}} te gaan!</span>
        <!--[ <a href="" ng-click="todoList.archive()">archive</a> ]-->
        <ul class="unstyled">
          <li ng-repeat="todo in todoList.todos">
            <label class="checkbox">
              <input type="checkbox" onclick="alert('Well done!')" ng-model="todo.done">
              <span class="done-{{todo.done}}">{{todo.text}}</span>
            </label>
          </li>
        </ul>
      </div> <!--einde ng-controller -->
</code>```

AngularJS code:

```<code>todoList.remaining = function() {
  var count = 0;
  angular.forEach(todoList.todos, function(todo) {
    count += todo.done ? 0 : 1;
  });
  return count;
};

todoList.archive = function() {
  var oldTodos = todoList.todos;
  todoList.todos = [];
  angular.forEach(oldTodos, function(todo) {
    if (!todo.done) todoList.todos.push(todo);
  });
};
</code>```

If there's missing something, let me know!
Thanks in advance!

答:
Here's the updated code for you:

```<code><div ng-controller="TodoListController as todoList">
        <span>Nog {{todoList.remaining()}} van de {{todoList.todos.length}} te gaan!</span>
        <!--[ <a href="" ng-click="todoList.archive()">archive</a> ]-->
        <ul class="unstyled">
          <li ng-repeat="todo in todoList.todos">
            <label class="checkbox">
              <input type="checkbox" onclick="showAlert(todo.done)" ng-model="todo.done">
              <span class="done-{{todo.done}}">{{todo.text}}</span>
            </label>
          </li>
        </ul>
      </div> <!--einde ng-controller -->
</code>```

AngularJs Code:

```<code>todoList.remaining = function() {
  var count = 0;
  angular.forEach(todoList.todos, function(todo) {
    count += todo.done ? 0 : 1;
  });
  return count;
};

  $scope.showAlert = function(isSuccess){
               if(isSuccess)
                  alert('Well done!')
               else
                 alert('Unchecked')
                };
todoList.archive = function() {
  var oldTodos = todoList.todos;
  todoList.todos = [];
  angular.forEach(oldTodos, function(todo) {
    if (!todo.done) todoList.todos.push(todo);
  });
};
</code>```

Body:
I'm fairly new in Javascript/AngularJS and want to play around with it to learn/understand these languages. On the Angular website there's a little basic to do list script I want to change a little. I've changed it into a checklist of things I need to learn. When i check the checkbox I got a little msg like, 'well done!'. But when I uncheck it, the same msg pops up and that I want to change in something like, 'you sure?'.

I've spent several hours on looking for the answer but couldn't find the answer so I hope someone can help me figuring out how to do this. This is my code:

HTML:

        Nog {{todoList.remaining()}} van de {{todoList.todos.length}} te gaan!

              <input type="checkbox" onclick="alert('Well done!')" ng-model="todo.done">
              {{todo.text}}

AngularJS code:

todoList.remaining = function() {
  var count = 0;
  angular.forEach(todoList.todos, function(todo) {
    count += todo.done ? 0 : 1;
  });
  return count;
};

todoList.archive = function() {
  var oldTodos = todoList.todos;
  todoList.todos = [];
  angular.forEach(oldTodos, function(todo) {
    if (!todo.done) todoList.todos.push(todo);
  });
};

If there's missing something, let me know!
Thanks in advance!

Body:
Here's the updated code for you:

<div ng-controller="TodoListController as todoList">
        <span>Nog {{todoList.remaining()}} van de {{todoList.todos.length}} te gaan!</span>
        <!--[ <a href="" ng-click="todoList.archive()">archive</a> ]-->
        <ul class="unstyled">
          <li ng-repeat="todo in todoList.todos">
            <label class="checkbox">
              <input type="checkbox" onclick="showAlert(todo.done)" ng-model="todo.done">
              <span class="done-{{todo.done}}">{{todo.text}}</span>
            </label>
          </li>
        </ul>
      </div> <!--einde ng-controller -->

AngularJs Code:

todoList.remaining = function() {
  var count = 0;
  angular.forEach(todoList.todos, function(todo) {
    count += todo.done ? 0 : 1;
  });
  return count;
};

  $scope.showAlert = function(isSuccess){
               if(isSuccess)
                  alert('Well done!')
               else
                 alert('Unchecked')
                };
todoList.archive = function() {
  var oldTodos = todoList.todos;
  todoList.todos = [];
  angular.forEach(oldTodos, function(todo) {
    if (!todo.done) todoList.todos.push(todo);
  });
};


问:
Upper diagonal of a 2D numpy array
This seems simple (and is trivial to write a three-line loop for), but how can I use numpy slicing make a list of the index locations of the upper diagonal of a numpy array? I.e.

Given a 4x4 array, I'd like the index locations at the X's:

```<code>[ X X X X ]
[ 0 X X X ]
[ 0 0 X X ]
[ 0 0 0 X ]
</code>```

Giving:

```<code>[ (0,0), (0,1), (0,2), (0,3), (1,1), (1,2), (1,3), (2,2), (2,3), (3,3) ]
</code>```

答: Though the format of index locations is different, it seems like you want the function numpy.triu_indices.

Title: Upper diagonal of a 2D numpy array

Body:
This seems simple (and is trivial to write a three-line loop for), but how can I use numpy slicing make a list of the index locations of the upper diagonal of a numpy array? I.e.

Given a 4x4 array, I'd like the index locations at the X's:

[ X X X X ]
[ 0 X X X ]
[ 0 0 X X ]
[ 0 0 0 X ]

Giving:

[ (0,0), (0,1), (0,2), (0,3), (1,1), (1,2), (1,3), (2,2), (2,3), (3,3) ]


问:
Dotnet test on .NET Core 1.1 in VSTS: No Test Discoverer is Registered
I'm using VS 2017 with the new csproj in a .NET Standard class library, trying to test the library with a .NET Core 1.1 test project using MSTest testing framework with the dotnet test command. Running locally works perfectly fine; when I send the build to continuous integration, I get the error:

No test discoverer is registered to perform discovery of test cases.

How do I get this discoverer registered, and my tests running, in VSTS?

答:
This is my build process on VSTS (detailed on my blog here)

Add a dotnet restore task.

Then a dotnet build task.

Add a dotnet test task with the arguments --no-build --logger "trx;LogFileName=tests-log.trx

Add a Publish test results task with the following settings

Test Result Format = VSTest

Test Result Files = **/tests-log.trx

Merge Test Results = (checked)

In Control Options set Run this task to run even if a previous task has failed


问:
How can I make a variable inside a function global?
I currently have the following function called saveRun()

```<code>func saveRun() {

    let startLoc = locations[0]
    let endLoc = locations[locations.count - 1]
    let startLat = startLoc.coordinate.latitude
    let startLong =  startLoc.coordinate.longitude
    let endLat = endLoc.coordinate.latitude
    let endLong = endLoc.coordinate.longitude

    //1. Create the alert controller
    let alert = UIAlertController(title: "Save the Run", message: "Choose a name: ", preferredStyle: .alert)

    //2. Add the text field
    alert.addTextField { (textField) in
        textField.text = ""
    }

    // 3. Grab the value from the text field, and print it when the user clicks OK
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
        let textField = alert?.textFields![0] // Force unwrapping because we know it exists.

        // Create name for run
        let runName = textField?.text
        let run = self.databaseRef.child(runName!)
        let user = FIRAuth.auth()?.currentUser?.uid

        // Enter run info into db
        run.child("startLat").setValue(startLat)
        run.child("startLong").setValue(startLong)
        run.child("endLat").setValue(endLat)
        run.child("endLong").setValue(endLong)
        run.child("distance").setValue(self.distance)
        run.child("time").setValue(self.seconds)
        run.child("user").setValue(user)

        // Enter locations into db

        var i = 0
        for location in self.locations {

            run.child("locations").child("\(i)").child("lat").setValue(location.coordinate.latitude)
            run.child("locations").child("\(i)").child("long").setValue(location.coordinate.longitude)
            i = i + 1

        self.performSegue(withIdentifier: DetailSegueName, sender: nil)

        }

    }))

    // 4. Present the alert
    self.present(alert, animated: true, completion: nil)

}
</code>```

My problem is that I am trying to extract 'runName' from the action that I am adding when the user clicks 'Ok' on the alert controller and using it in the following function:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let detailViewController = segue.destination as? DetailViewController {
        detailViewController.runName = self.runName
    }
}
</code>```

When I try to print 'runName' in DetailViewController, the value of runName is nil. The issue I think is that I cannot set a global variable inside the action I have added as it is in a function. Is there any other way I can obtain this variable's value and use it outside of the function?

答:
I solved this thanks to @DSDharma pointing out that even if 'runName' was set as a global variable, using it as a global variable inside of an alert function block required the 'self' keyword.

For example, before I had the following inside of the alert function block:

```<code>let runName = textField?.text
</code>```

This needed to be changed to:

```<code>self.runName = textField?.text
</code>```

Body:
I currently have the following function called saveRun()

func saveRun() {

    let startLoc = locations[0]
    let endLoc = locations[locations.count - 1]
    let startLat = startLoc.coordinate.latitude
    let startLong =  startLoc.coordinate.longitude
    let endLat = endLoc.coordinate.latitude
    let endLong = endLoc.coordinate.longitude

    //1. Create the alert controller
    let alert = UIAlertController(title: "Save the Run", message: "Choose a name: ", preferredStyle: .alert)

    //2. Add the text field
    alert.addTextField { (textField) in
        textField.text = ""
    }

    // 3. Grab the value from the text field, and print it when the user clicks OK
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
        let textField = alert?.textFields![0] // Force unwrapping because we know it exists.

        // Create name for run
        let runName = textField?.text
        let run = self.databaseRef.child(runName!)
        let user = FIRAuth.auth()?.currentUser?.uid

        // Enter run info into db
        run.child("startLat").setValue(startLat)
        run.child("startLong").setValue(startLong)
        run.child("endLat").setValue(endLat)
        run.child("endLong").setValue(endLong)
        run.child("distance").setValue(self.distance)
        run.child("time").setValue(self.seconds)
        run.child("user").setValue(user)

        // Enter locations into db

        var i = 0
        for location in self.locations {

            run.child("locations").child("\(i)").child("lat").setValue(location.coordinate.latitude)
            run.child("locations").child("\(i)").child("long").setValue(location.coordinate.longitude)
            i = i + 1

        self.performSegue(withIdentifier: DetailSegueName, sender: nil)

        }

    }))

    // 4. Present the alert
    self.present(alert, animated: true, completion: nil)

}

My problem is that I am trying to extract 'runName' from the action that I am adding when the user clicks 'Ok' on the alert controller and using it in the following function:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let detailViewController = segue.destination as? DetailViewController {
        detailViewController.runName = self.runName
    }
}

When I try to print 'runName' in DetailViewController, the value of runName is nil. The issue I think is that I cannot set a global variable inside the action I have added as it is in a function. Is there any other way I can obtain this variable's value and use it outside of the function?

Body:
I solved this thanks to @DSDharma pointing out that even if 'runName' was set as a global variable, using it as a global variable inside of an alert function block required the 'self' keyword.

For example, before I had the following inside of the alert function block:

let runName = textField?.text

This needed to be changed to:

self.runName = textField?.text


答:
You could use stem.

```<code>% ... your code
%
[maxy, idx] = max(y); % Get maximum y and its index
hold on               % use hold on to plot again on same axes
% vertical stem plot, various marker options available: see docs
stem(x(idx), maxy, 'marker', 'none', 'linewidth', 1.8)
</code>```

Output:

This code plots a vertical line at the first maximum. If there is a chance that you will have more than one equal maximum value, then you should use something like this:

```<code>idx = (y == max(y));  % Get *all* logical indices of max values
hold on
% Plot vertical lines at all max points
stem(x(idx), y(idx), 'marker', 'none', 'linewidth', 1.8);
</code>```

Title: A vertical line in the plot

Body:
I want to draw a vertical line for the max Value of y(hier for x near 20), how to do that? (i mean downwards from this value (x=20, ymax) to (x=20, y=0))

x = logspace(0,5);
y=[0;0;0;0;0;0;0;0.15;0.34;0.51;0.71;0.84;0.88;0.856;0.75;0.63;0.47;0.36;0.32;0.33;0.37;0.45;0.5;0.51;0.48;0.4;0.33;0.22;0.14;0.07;0.02;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0];
y=y';

figure(5)
plot(x,y,'-o','LineWidth',2);
%ax(1) = axes('Position',[0.35 0.13 0.3 0.8]);
xlim([0,10000]);
ylim([0,1]);
set(gca, 'XScale', 'log')

grid on
grid minor
set(gca,'FontSize', 20);
set(gca,'Linewidth',1.8);

title('\rm Verteilung der Porengrößen');
xlabel('Porengröße [{\fontsize{24}\mu}{\fontsize{20}m}]');
ylabel('Amplitude des NMR-Signals [V]');

Body:
You could use stem.

% ... your code
%
[maxy, idx] = max(y); % Get maximum y and its index
hold on               % use hold on to plot again on same axes
% vertical stem plot, various marker options available: see docs
stem(x(idx), maxy, 'marker', 'none', 'linewidth', 1.8)

Output:

This code plots a vertical line at the first maximum. If there is a chance that you will have more than one equal maximum value, then you should use something like this:

idx = (y == max(y));  % Get *all* logical indices of max values
hold on
% Plot vertical lines at all max points
stem(x(idx), y(idx), 'marker', 'none', 'linewidth', 1.8);


问:
Disable @click event Vuejs 2
I have a custom table that serves as a progress bar and added @click events on each td that will redirect to a specific page. Now, the behavior should be like this:

User can't skip forward so the @click event to the right items should be disabled.

Only @click event functions when going back.

Template:

```<code><tr>
     <td class="circle col-xs-2 col-xs-offset-1"
             @click="goRelationship">Relationship</td>
     <td class="circle col-xs-2"
             @click="goSkills">Skills</td>
     <td class="circle col-xs-2"
             @click="goPurpose">Purpose</td>
     <td class="circle col-xs-2"
             @click="goFit">Fit</td>
     <td class="circle col-xs-2">Submit</td>
 </tr>
</code>```

Script:

```<code>methods: {
            goRelationship: function () {
                window.location.href = "/v2/review/relationship"
            },
            goSkills: function () {
                window.location.href = "/v2/review/skills"
            },
            goFit: function () {
                window.location.href = "/v2/review/fit"
            },
            goPurpose: function () {
                window.location.href = "/v2/review/purpose"
            }
        }
</code>```

答:
You will need to implement some logic to check if navigation steps are active or not. Here is a suggestion:

List of steps:

```<code>data() {
    return {
        steps: {
            relationship: {
                dependancies: [],
                completed: false,
            },
            skills: {
                dependancies: ['relationship'],
                completed: false,
            },
            fit: {
                dependancies: ['relationship', 'skills'],
                completed: false,
            },
            purpose: {
                dependancies: ['relationship', 'skills', 'fit'],
                completed: false,
            }
        }
    }
}
</code>```

A generic go to next step function:

```<code>goToStep(stepName) {
    if (checkDependanciesCompletion(this.steps[stepName].dependancies)) {
        window.location.href = `/v2/review/${stepName}`
    }
}
</code>```

And a function to check if step that you want to go to is active:

```<code>function checkDependanciesCompletion(dependencies) {
    let isCompleted = true;

    dependencies.forEach((dep) => {
        if (!this.steps[dep].completed) {
            isCompleted = false;
        }
    });

    return isCompleted;
}
</code>```

Title: Disable @click event Vuejs 2

Body:
I have a custom table that serves as a progress bar and added @click events on each td that will redirect to a specific page. Now, the behavior should be like this:

User can't skip forward so the @click event to the right items should be disabled.

Only @click event functions when going back.

Template:

     Relationship
     Skills
     Purpose
     Fit
     Submit

Script:

methods: {
            goRelationship: function () {
                window.location.href = "/v2/review/relationship"
            },
            goSkills: function () {
                window.location.href = "/v2/review/skills"
            },
            goFit: function () {
                window.location.href = "/v2/review/fit"
            },
            goPurpose: function () {
                window.location.href = "/v2/review/purpose"
            }
        }

Body:
You will need to implement some logic to check if navigation steps are active or not. Here is a suggestion:

List of steps:

data() {
    return {
        steps: {
            relationship: {
                dependancies: [],
                completed: false,
            },
            skills: {
                dependancies: ['relationship'],
                completed: false,
            },
            fit: {
                dependancies: ['relationship', 'skills'],
                completed: false,
            },
            purpose: {
                dependancies: ['relationship', 'skills', 'fit'],
                completed: false,
            }
        }
    }
}

A generic go to next step function:

goToStep(stepName) {
    if (checkDependanciesCompletion(this.steps[stepName].dependancies)) {
        window.location.href = `/v2/review/${stepName}`
    }
}

And a function to check if step that you want to go to is active:

function checkDependanciesCompletion(dependencies) {
    let isCompleted = true;

    dependencies.forEach((dep) => {
        if (!this.steps[dep].completed) {
            isCompleted = false;
        }
    });

    return isCompleted;
}


问:
Retrieving more then one object with values from Db in asp.net webapi
I am learning asp.net webapi and trying to get values for different object.I have a function called

SELECT * FROM test.get_accounts_info('CS-01')

which returns 5 columns.

account_number [value- CS-001]

account_name   [Sam]

product        [Test]

interest_rate  [1]

balance        [1000]

Now in my controller i am passing an object of AccountInfo Class.

```<code>[HttpPost]
[ActionName("info")]
public IHttpActionResult GetAccountInfo([FromBody]AccountInfo
     accountinfo)
{
    accountinfo.accountNumber = BusinessLayer.Api.AccountHolderApi.GetAccountInfo(accountinfo.accountNumber);
    return Ok(accountinfo);
}
</code>```

The AccountInfo Class

```<code>    public class AccountInfo
      {
        public string accountNumber { get; set; }
        public string balance { get; set; }
        public int interestRate { get; set; }
        public string accountName { get; set; }
        public string accountType { get; set; }
      }
</code>```

My Route

config.Routes.MapHttpRoute("test", "v1/{controller}/{action}");

And the Db Layer code from where i am calling the function

```<code>      ` public static string
        GetAccountInfo(string accountNumber)
        {
            var sql = "SELECT * FROM
            test.get_accounts_info(@AccountNumber);";
            using (var command = new NpgsqlCommand(sql))
            {
               command.Parameters.AddWithValue("@AccountNumber",
               accountNumber);
               return Common.Conversion.TryCastString(DBOperations.GetScalarValue(command));
            }
        }`
</code>```

Now in postman when i pass the value from the body like this

{"accountNumber": "CS-001"}

In my response i get this

{
    "accountNumber": "CS-0000001",
    "balance": null,
    "interestRate": 0,
    "accountName": null,
    "accountType": null
  }

Where i am wrong?Any Help Please.

UPDATED

My DBOperation.cs has these classes

```<code>  public static NpgsqlDataReader GetDataReader(NpgsqlCommand command)
    {
        if (command != null)
        {
            if (ValidateCommand(command))
            {
                command.Connection = Connection;
                var reader = command.ExecuteReader();
                command.Connection.Close();
                command.Connection.Dispose();
                return reader;

            }
        }

        return null;
    }

  public static object GetScalarValue(NpgsqlCommand command)
    {
        if (command != null)
        {

            if (ValidateCommand(command))
            {
                command.Connection = Connection;
                var val = command.ExecuteScalar();
                command.Connection.Close();
                command.Connection.Dispose();
                return val;

            }
        }

        return null;
    }

  public static bool ExecuteNonQuery(NpgsqlCommand command)
    {
        if (command != null)
        {
            if (ValidateCommand(command))
            {
                command.Connection = Connection;
                command.ExecuteNonQuery();
                command.Connection.Close();
                command.Connection.Dispose();
                return true;
            }
        }

        return false;
    }
</code>```

答:
Look at this example from:
http://www.sqlines.com/postgresql/npgsql_cs_result_sets

```<code>   using System;
   using Npgsql;

   class Sample
   {
     static void Main(string[] args)
     {
         // Connect to a PostgreSQL database
         NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres; " +
             "Password=pwd;Database=postgres;");
         conn.Open();

         // Define a query
         NpgsqlCommand command = new NpgsqlCommand("SELECT city, state FROM cities", conn);

         // Execute the query and obtain a result set
         NpgsqlDataReader dr = command.ExecuteReader();

         // Output rows
         while (dr.Read())
           Console.Write("{0}\t{1} \n", dr[0], dr[1]);

         conn.Close();
     }
   }
</code>```

Keep the using and stuff you already have. Just update it to command.ExecuteReader, as this method reads all rows and columns. Execute Scalar is only returning the first column from the first row

Body:
I am learning asp.net webapi and trying to get values for different object.I have a function called

SELECT * FROM test.get_accounts_info('CS-01')

which returns 5 columns.

account_number [value- CS-001]

account_name   [Sam]

product        [Test]

interest_rate  [1]

balance        [1000]

Now in my controller i am passing an object of AccountInfo Class.

[HttpPost]
[ActionName("info")]
public IHttpActionResult GetAccountInfo([FromBody]AccountInfo
     accountinfo)
{
    accountinfo.accountNumber = BusinessLayer.Api.AccountHolderApi.GetAccountInfo(accountinfo.accountNumber);
    return Ok(accountinfo);
}

The AccountInfo Class

    public class AccountInfo
      {
        public string accountNumber { get; set; }
        public string balance { get; set; }
        public int interestRate { get; set; }
        public string accountName { get; set; }
        public string accountType { get; set; }
      }

My Route

config.Routes.MapHttpRoute("test", "v1/{controller}/{action}");

And the Db Layer code from where i am calling the function

      ` public static string
        GetAccountInfo(string accountNumber)
        {
            var sql = "SELECT * FROM
            test.get_accounts_info(@AccountNumber);";
            using (var command = new NpgsqlCommand(sql))
            {
               command.Parameters.AddWithValue("@AccountNumber",
               accountNumber);
               return Common.Conversion.TryCastString(DBOperations.GetScalarValue(command));
            }
        }`

Now in postman when i pass the value from the body like this

{"accountNumber": "CS-001"}

In my response i get this

{
    "accountNumber": "CS-0000001",
    "balance": null,
    "interestRate": 0,
    "accountName": null,
    "accountType": null
  }

Where i am wrong?Any Help Please.

UPDATED

My DBOperation.cs has these classes

  public static NpgsqlDataReader GetDataReader(NpgsqlCommand command)
    {
        if (command != null)
        {
            if (ValidateCommand(command))
            {
                command.Connection = Connection;
                var reader = command.ExecuteReader();
                command.Connection.Close();
                command.Connection.Dispose();
                return reader;

            }
        }

        return null;
    }

  public static object GetScalarValue(NpgsqlCommand command)
    {
        if (command != null)
        {

            if (ValidateCommand(command))
            {
                command.Connection = Connection;
                var val = command.ExecuteScalar();
                command.Connection.Close();
                command.Connection.Dispose();
                return val;

            }
        }

        return null;
    }

  public static bool ExecuteNonQuery(NpgsqlCommand command)
    {
        if (command != null)
        {
            if (ValidateCommand(command))
            {
                command.Connection = Connection;
                command.ExecuteNonQuery();
                command.Connection.Close();
                command.Connection.Dispose();
                return true;
            }
        }

        return false;
    }

Body:
Look at this example from:
http://www.sqlines.com/postgresql/npgsql_cs_result_sets

   using System;
   using Npgsql;

   class Sample
   {
     static void Main(string[] args)
     {
         // Connect to a PostgreSQL database
         NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;User Id=postgres; " +
             "Password=pwd;Database=postgres;");
         conn.Open();

         // Define a query
         NpgsqlCommand command = new NpgsqlCommand("SELECT city, state FROM cities", conn);

         // Execute the query and obtain a result set
         NpgsqlDataReader dr = command.ExecuteReader();

         // Output rows
         while (dr.Read())
           Console.Write("{0}\t{1} \n", dr[0], dr[1]);

         conn.Close();
     }
   }

Keep the using and stuff you already have. Just update it to command.ExecuteReader, as this method reads all rows and columns. Execute Scalar is only returning the first column from the first row


问:
Verify submitted Django form in view
I have a view, which expects a POST request. The post request should contain data submitted through a Django form.

The Django form looks something like this:

```<code>class SubmitForm(forms.Form):
    title = forms.CharField(max_length=100)
    comment = forms.CharField(max_length=255)
</code>```

I know I have access to the submitted data with request.POST["title"] and  request.POST["comment"]. So I can theoretically check if they're set and valid manually.

But is there a way to use .is_valid() (Link to Django documentation), to validate the submitted form?

One possibility would be to create a form in the view, fill it with the submitted data and then check it for validity.

```<code>data = {'title': request.POST["title"],
        'comment': request.POST["comment"]}
f = SubmitForm(data)
f.is_valid()
# True/False
</code>```

Is there a direct way to use is_valid() on a submitted Django form?

答:
You can write view as below:</p>

```<code>def verify_view(request):
    if request.method == "POST":
        form = SubmitForm(request.POST)
        if form.is_valid():
          # code here if form is valid
    else:
        form = SubmitForm() # returns empty form to be fill if not post request
    return render(request, 'template_form.html', {'form': form})
</code>```

Title: Verify submitted Django form in view

Body:
I have a view, which expects a POST request. The post request should contain data submitted through a Django form.

The Django form looks something like this:

class SubmitForm(forms.Form):
    title = forms.CharField(max_length=100)
    comment = forms.CharField(max_length=255)

I know I have access to the submitted data with request.POST["title"] and  request.POST["comment"]. So I can theoretically check if they're set and valid manually.

But is there a way to use .is_valid() (Link to Django documentation), to validate the submitted form?

One possibility would be to create a form in the view, fill it with the submitted data and then check it for validity.

data = {'title': request.POST["title"],
        'comment': request.POST["comment"]}
f = SubmitForm(data)
f.is_valid()
# True/False

Is there a direct way to use is_valid() on a submitted Django form?

Body:
You can write view as below:

def verify_view(request):
    if request.method == "POST":
        form = SubmitForm(request.POST)
        if form.is_valid():
          # code here if form is valid
    else:
        form = SubmitForm() # returns empty form to be fill if not post request
    return render(request, 'template_form.html', {'form': form})


问:
How can I convert unsigned char to unsigned short using sse
I am just a beginner of sse, the question is that how to convert unsigned char array to unsigned short array by using sse</p>

答: The function you're looking for is _mm_cvtepu8_epi16.


答:
```<code>Class YourClassName:UIViewController {

  var  runName:String = "" // This will be global for your class

  //Remove local decalration of runName variable
  func saveRun() { // your function

    alert.addAction(

      //.....
      self.runName = textfield?.text
    )

  }

}
</code>```

Now you can use in whole class.

Title: How can I make a variable inside a function global?

Body:
Class YourClassName:UIViewController {

  var  runName:String = "" // This will be global for your class

  //Remove local decalration of runName variable
  func saveRun() { // your function

    alert.addAction(

      //.....
      self.runName = textfield?.text
    )

  }

}

Now you can use in whole class.


答:
Compare it with "===", but I would suggest another approach for better readability: Use the switch statement. This is especially useful when you get more comparisons in the future.:</p>

```<code>switch ($rooms) {
    case '0':
        echo "0";
        break;
    case '1':
        echo "1";
        break;
    case '10':
        echo "10";
        break;
}
</code>```

Title: How could I check if string is only match into an other string

Body:
I'm actually a beginner into web developpment.

I have a problem with my actual condition.

Exemple :

$rooms = 10;

In my code, I check if $rooms is equal to 1,0 or 10 so :

if(strpos($rooms, '1')){echo 1;}
if(strpos($rooms, '0')){echo 0};
if(strpos($rooms, '10')){echo 10;}

My result :

1
0
10

My condition match for 1, 0 and 10, where I only need to match the number 10

How can I only pass into my third condition ?

Thx

Body:
Compare it with "===", but I would suggest another approach for better readability: Use the switch statement. This is especially useful when you get more comparisons in the future.:

switch ($rooms) {
    case '0':
        echo "0";
        break;
    case '1':
        echo "1";
        break;
    case '10':
        echo "10";
        break;
}


问:
Output GitLog with Java Processbuilder to File
I create a Programm in Java which should automatic create a log file with gitlog and analyze this file.
But i have a Problem with Gitlog.
I created a Method who start git log in cmd and print this in a file out.

The programm start gitlog an show this in cmd, but the new file is empty.

How can i output this log in a file ?

My Method :

```<code>Path LogPath = Paths.get("C:/Users/User/Code/code1");

List<String> cmds = Arrays.asList("cmd.exe", "/C", "start", "git", "log");
ProcessBuilder builder = new ProcessBuilder(cmds);
builder.directory(new File("C:/Users/User/Code/code1/git"));

builder.redirectOutput(ProcessBuilder.Redirect.to( LogPath.resolve("gitlog.txt").toFile() ) );

Process process = builder.start();
</code>```

答:
Solution

This works for me :

```<code>List<String> cmds = Arrays.asList("git", "log");
</code>```

Body:
I create a Programm in Java which should automatic create a log file with gitlog and analyze this file.
But i have a Problem with Gitlog.
I created a Method who start git log in cmd and print this in a file out.

The programm start gitlog an show this in cmd, but the new file is empty.

How can i output this log in a file ?

My Method :

Path LogPath = Paths.get("C:/Users/User/Code/code1");

List<String> cmds = Arrays.asList("cmd.exe", "/C", "start", "git", "log");
ProcessBuilder builder = new ProcessBuilder(cmds);
builder.directory(new File("C:/Users/User/Code/code1/git"));

builder.redirectOutput(ProcessBuilder.Redirect.to( LogPath.resolve("gitlog.txt").toFile() ) );

Process process = builder.start();

Body:
Solution

This works for me :

List<String> cmds = Arrays.asList("git", "log");


问:
Date Range Formula
Page1:

From Date: TXTBOX1   To Date: TXTBOX2

BTNSUBMIT-CLICK
{
server.transfer("page2.aspx");
}

Page 2:

if (PreviousPage != null)
        {
            TextBox txt1 = PreviousPage.FindControl("TXTBOX1") as TextBox;
            TextBox txt2 = PreviousPage.FindControl("TXTBOX2") as TextBox;

```<code>        if (txt1.Text.Length != 0 && txt2.Text.Length != 0)
        {

         ReportDocument cryRpt = new ReportDocument();
         cryRpt.Load("MyReport.rpt");

            ParameterFieldDefinitions crParameterFieldDefinitions;
            ParameterFieldDefinition crParameterFieldDefinition;
            ParameterValues crParameterValues = new ParameterValues();
            ParameterDiscreteValue crParameterDiscreteValue = new
            ParameterDiscreteValue();

            crParameterDiscreteValue.Value = txt1.Text + txt2.Text;
            crParameterFieldDefinitions =
            cryRpt.DataDefinition.ParameterFields;
            crParameterFieldDefinition =
            crParameterFieldDefinitions["MyParameter"];
            crParameterValues = crParameterFieldDefinition.CurrentValues;

            crParameterValues.Clear();
            crParameterValues.Add(crParameterDiscreteValue);
            crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

            CrystalReportViewer1.ReportSource = cryRpt;

        }

     }
</code>```

Formula In Formula Editor:

{Command.Date} >= {?MyParameter} and {Command.Date} <= {?MyParameter}

It works fine If report is displayed for single date. Not for Date Range.

Any Suggestions? Where i am wrong in formula / code ???

答:
Use a ParameterRangeValue instead of a ParameterDiscreteValue, and set the StartValue and EndValue properties to your start and end dates.

Update:
Here's some sample code that worked on a test report:

```<code>     ParameterFieldDefinitions paramDefinitions =  report.DataDefinition.ParameterFields;

     ParameterFieldDefinition paramDefinition = paramDefinitions["DateRange"];
     ParameterValues paramValues = paramDefinition.CurrentValues;

     ParameterRangeValue rangeValue = new ParameterRangeValue();
     rangeValue.StartValue = new DateTime(2010, 10, 31);
     rangeValue.EndValue = new DateTime(2010, 12, 15);

     paramValues.Add(rangeValue); ;

     paramDefinition.ApplyCurrentValues(paramValues);
</code>```

Make sure that your MyParameter is a range value, and that the select statement in Crystal is dateField = {?MyParameter}

Title: Date Range Formula

Body:
Page1:

From Date: TXTBOX1   To Date: TXTBOX2

BTNSUBMIT-CLICK
{
server.transfer("page2.aspx");
}

Page 2:

if (PreviousPage != null)
        {
            TextBox txt1 = PreviousPage.FindControl("TXTBOX1") as TextBox;
            TextBox txt2 = PreviousPage.FindControl("TXTBOX2") as TextBox;

        if (txt1.Text.Length != 0 && txt2.Text.Length != 0)
        {

         ReportDocument cryRpt = new ReportDocument();
         cryRpt.Load("MyReport.rpt");

            ParameterFieldDefinitions crParameterFieldDefinitions;
            ParameterFieldDefinition crParameterFieldDefinition;
            ParameterValues crParameterValues = new ParameterValues();
            ParameterDiscreteValue crParameterDiscreteValue = new
            ParameterDiscreteValue();

            crParameterDiscreteValue.Value = txt1.Text + txt2.Text;
            crParameterFieldDefinitions =
            cryRpt.DataDefinition.ParameterFields;
            crParameterFieldDefinition =
            crParameterFieldDefinitions["MyParameter"];
            crParameterValues = crParameterFieldDefinition.CurrentValues;

            crParameterValues.Clear();
            crParameterValues.Add(crParameterDiscreteValue);
            crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

            CrystalReportViewer1.ReportSource = cryRpt;

        }

     }

Formula In Formula Editor:

{Command.Date} >= {?MyParameter} and {Command.Date} <= {?MyParameter}

It works fine If report is displayed for single date. Not for Date Range.

Any Suggestions? Where i am wrong in formula / code ???

Body:
Use a ParameterRangeValue instead of a ParameterDiscreteValue, and set the StartValue and EndValue properties to your start and end dates.

Update:
Here's some sample code that worked on a test report:

     ParameterFieldDefinitions paramDefinitions =  report.DataDefinition.ParameterFields;

     ParameterFieldDefinition paramDefinition = paramDefinitions["DateRange"];
     ParameterValues paramValues = paramDefinition.CurrentValues;

     ParameterRangeValue rangeValue = new ParameterRangeValue();
     rangeValue.StartValue = new DateTime(2010, 10, 31);
     rangeValue.EndValue = new DateTime(2010, 12, 15);

     paramValues.Add(rangeValue); ;

     paramDefinition.ApplyCurrentValues(paramValues);

Make sure that your MyParameter is a range value, and that the select statement in Crystal is dateField = {?MyParameter}


问:
Customize "Update google play services" dialog
Im trying to customise the Dialog where it displays errors based on a status code coming from the method

googleApiAvailability.isGooglePlayServicesAvailable(activity);

This method returns a status code that then gets passed into a method

googleApiAvailability.getErrorDialog(activity, status, 2404).show();

Which then shows a dialog to the user asking them whether they need to update Google Play Services or enable them etc based on the error code ("status" in this case). From what i can tell is they set the dialog text based on the status, but I want to customise it a bit because I am using it for notifications so I want to say in the dialog that the user wont be able to use notifications without this feature installed/enabled/updated on the app?

Also I want to be able to add a Cancel button with custom text like "It's Ok" or something along those lines?

I've seen something similar in another app and thought it was a great idea.

EDIT:

```<code>   public static boolean checkGooglePlayServices(Activity activity) {
    GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
    int status = googleApiAvailability.isGooglePlayServicesAvailable(activity);
    if (status != ConnectionResult.SUCCESS) {
      if (googleApiAvailability.isUserResolvableError(status)) {
        Dialog dialog = googleApiAvailability.getErrorDialog(activity, status, 1);
        dialog.setTitle("This is a test title");
        dialog.show();
      }
      return false;
    }
    return true;
  }
</code>```

答:
resultCode can have below values.

```<code>public static final int SUCCESS = 0;
public static final int SERVICE_MISSING = 1;
public static final int SERVICE_VERSION_UPDATE_REQUIRED = 2;
public static final int SERVICE_DISABLED = 3;
public static final int SIGN_IN_REQUIRED = 4;
public static final int INVALID_ACCOUNT = 5;
public static final int RESOLUTION_REQUIRED = 6;
public static final int NETWORK_ERROR = 7;
public static final int INTERNAL_ERROR = 8;
public static final int SERVICE_INVALID = 9;
public static final int DEVELOPER_ERROR = 10;
public static final int LICENSE_CHECK_FAILED = 11;
public static final int CANCELED = 13;
public static final int TIMEOUT = 14;
public static final int INTERRUPTED = 15;
public static final int API_UNAVAILABLE = 16;
public static final int SIGN_IN_FAILED = 17;
public static final int SERVICE_UPDATING = 18;
public static final int SERVICE_MISSING_PERMISSION = 19;
public static final int RESTRICTED_PROFILE = 20;
</code>```

do not call getErrorDialog instead call your owndialog and take action accordingly..

```<code> static String getStatusString(int var0) {
        switch(var0) {
        case -1:
            return "UNKNOWN";
        case 0:
            return "SUCCESS";
        case 1:
            return "SERVICE_MISSING";
        case 2:
            return "SERVICE_VERSION_UPDATE_REQUIRED";
        case 3:
            return "SERVICE_DISABLED";
        case 4:
            return "SIGN_IN_REQUIRED";
        case 5:
            return "INVALID_ACCOUNT";
        case 6:
            return "RESOLUTION_REQUIRED";
        case 7:
            return "NETWORK_ERROR";
        case 8:
            return "INTERNAL_ERROR";
        case 9:
            return "SERVICE_INVALID";
        case 10:
            return "DEVELOPER_ERROR";
        case 11:
            return "LICENSE_CHECK_FAILED";
        case 13:
            return "CANCELED";
        case 14:
            return "TIMEOUT";
        case 15:
            return "INTERRUPTED";
        case 16:
            return "API_UNAVAILABLE";
        case 17:
            return "SIGN_IN_FAILED";
        case 18:
            return "SERVICE_UPDATING";
        case 19:
            return "SERVICE_MISSING_PERMISSION";
        case 20:
            return "RESTRICTED_PROFILE";
        case 21:
            return "API_VERSION_UPDATE_REQUIRED";
        case 42:
            return "UPDATE_ANDROID_WEAR";
        case 99:
            return "UNFINISHED";
        case 1500:
            return "DRIVE_EXTERNAL_STORAGE_REQUIRED";
        default:
            return (new StringBuilder(31)).append("UNKNOWN_ERROR_CODE(").append(var0).append(")").toString();
        }
    }
</code>```

PS: See ConnectionResult.java class for more info.

Body:
Im trying to customise the Dialog where it displays errors based on a status code coming from the method

googleApiAvailability.isGooglePlayServicesAvailable(activity);

This method returns a status code that then gets passed into a method

googleApiAvailability.getErrorDialog(activity, status, 2404).show();

Which then shows a dialog to the user asking them whether they need to update Google Play Services or enable them etc based on the error code ("status" in this case). From what i can tell is they set the dialog text based on the status, but I want to customise it a bit because I am using it for notifications so I want to say in the dialog that the user wont be able to use notifications without this feature installed/enabled/updated on the app?

Also I want to be able to add a Cancel button with custom text like "It's Ok" or something along those lines?

I've seen something similar in another app and thought it was a great idea.

EDIT:

   public static boolean checkGooglePlayServices(Activity activity) {
    GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
    int status = googleApiAvailability.isGooglePlayServicesAvailable(activity);
    if (status != ConnectionResult.SUCCESS) {
      if (googleApiAvailability.isUserResolvableError(status)) {
        Dialog dialog = googleApiAvailability.getErrorDialog(activity, status, 1);
        dialog.setTitle("This is a test title");
        dialog.show();
      }
      return false;
    }
    return true;
  }

Body:
resultCode can have below values.

public static final int SUCCESS = 0;
public static final int SERVICE_MISSING = 1;
public static final int SERVICE_VERSION_UPDATE_REQUIRED = 2;
public static final int SERVICE_DISABLED = 3;
public static final int SIGN_IN_REQUIRED = 4;
public static final int INVALID_ACCOUNT = 5;
public static final int RESOLUTION_REQUIRED = 6;
public static final int NETWORK_ERROR = 7;
public static final int INTERNAL_ERROR = 8;
public static final int SERVICE_INVALID = 9;
public static final int DEVELOPER_ERROR = 10;
public static final int LICENSE_CHECK_FAILED = 11;
public static final int CANCELED = 13;
public static final int TIMEOUT = 14;
public static final int INTERRUPTED = 15;
public static final int API_UNAVAILABLE = 16;
public static final int SIGN_IN_FAILED = 17;
public static final int SERVICE_UPDATING = 18;
public static final int SERVICE_MISSING_PERMISSION = 19;
public static final int RESTRICTED_PROFILE = 20;

do not call getErrorDialog instead call your owndialog and take action accordingly..

 static String getStatusString(int var0) {
        switch(var0) {
        case -1:
            return "UNKNOWN";
        case 0:
            return "SUCCESS";
        case 1:
            return "SERVICE_MISSING";
        case 2:
            return "SERVICE_VERSION_UPDATE_REQUIRED";
        case 3:
            return "SERVICE_DISABLED";
        case 4:
            return "SIGN_IN_REQUIRED";
        case 5:
            return "INVALID_ACCOUNT";
        case 6:
            return "RESOLUTION_REQUIRED";
        case 7:
            return "NETWORK_ERROR";
        case 8:
            return "INTERNAL_ERROR";
        case 9:
            return "SERVICE_INVALID";
        case 10:
            return "DEVELOPER_ERROR";
        case 11:
            return "LICENSE_CHECK_FAILED";
        case 13:
            return "CANCELED";
        case 14:
            return "TIMEOUT";
        case 15:
            return "INTERRUPTED";
        case 16:
            return "API_UNAVAILABLE";
        case 17:
            return "SIGN_IN_FAILED";
        case 18:
            return "SERVICE_UPDATING";
        case 19:
            return "SERVICE_MISSING_PERMISSION";
        case 20:
            return "RESTRICTED_PROFILE";
        case 21:
            return "API_VERSION_UPDATE_REQUIRED";
        case 42:
            return "UPDATE_ANDROID_WEAR";
        case 99:
            return "UNFINISHED";
        case 1500:
            return "DRIVE_EXTERNAL_STORAGE_REQUIRED";
        default:
            return (new StringBuilder(31)).append("UNKNOWN_ERROR_CODE(").append(var0).append(")").toString();
        }
    }

PS: See ConnectionResult.java class for more info.


问:
Qt TabWidget corner widget size
Have some problem with corner widget due using non-standard font size in app, screenshot to be clear:

code:

```<code>QToolButton* m_exit = new QToolButton(m_tab);
m_exit->setIcon(QIcon(":/Resources/exit.png"));
m_exit->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
m_tab->setCornerWidget(m_exit, Qt::TopRightCorner);
</code>```

font changing via

```<code>QApplication::setFont(...);
</code>```

How can i do corner button same size as tab-buttons size?

P.S. using setStyleSheet( "QTabBar::tab { min-height: 120px; }" ); not allowed

答:
You can use the ::right-corner sub-control in your stylesheet. There you can set the height of the corner button (you'd probably have to adjust the bottom too). Set both heights (corner button and tab) to the same value.

```<code>QTabWidget::right-corner {
    height: 30px;
    bottom: 10px;
}

QTabBar::tab {
    height: 30px;
}
</code>```

Title: Qt TabWidget corner widget size

Body:
Have some problem with corner widget due using non-standard font size in app, screenshot to be clear:

code:

QToolButton* m_exit = new QToolButton(m_tab);
m_exit->setIcon(QIcon(":/Resources/exit.png"));
m_exit->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
m_tab->setCornerWidget(m_exit, Qt::TopRightCorner);

font changing via

QApplication::setFont(...);

How can i do corner button same size as tab-buttons size?

P.S. using setStyleSheet( "QTabBar::tab { min-height: 120px; }" ); not allowed

Body:
You can use the ::right-corner sub-control in your stylesheet. There you can set the height of the corner button (you'd probably have to adjust the bottom too). Set both heights (corner button and tab) to the same value.

QTabWidget::right-corner {
    height: 30px;
    bottom: 10px;
}

QTabBar::tab {
    height: 30px;
}


问:
Difference between cordova geolocation.watchposition and background geolocation?
I am aware that the Cordova geolocation.watchposition retrieves periodic updates about the current geographic location of the device.

But it seems that 'background geolocation' that comes with Ionic does the same thing.

Can anyone please clarify the difference between the two?

答:
You would normally use the "plain" geolocation watch position in an app where you wish to (probably) show the persons position on a map, and keep it updated if/when they move. Typically only when someone is actually using your app. The will normally use the most accurate form of geolocation enabled (GPS).

The background geolocation plugin is meant for when you want to have your application log or react to location events so you would usually use this for a lower power usage "always on" type scenario, which would normally use less accurate methods for geolocation or even vary it a bit depending on the situation. This also supports the OS native detection of when the phone is moving, still, stopped, started moving, etc.


问:
Cant build project with Android Studio 2.3 and Gradle
I've cloned project https://github.com/mpcjanssen/simpletask-android.git but when I try to open it on Android Studio 2.3 (recently updated) it just wont buid the project.

I'll try to eaplain in steps:

1) Deleted everything in folder "..../simpletask-android" from my hard drive.

2) Started Android Studio and selected New Project from Github

3) After downloading the source code from Github Android Studio showed me the following screen and I adopted a Next-Next-Finish behavior, without changing anything.

4) Next, AS started building the project according to settings.gradle found in the project's root folder. There is a small dialog on the picture showing this.

5) Suddenly AS requested me to choose a gradle project data to import (?!) as shown in the image

6) Next message I got was this in the image below.  Project 'simpletask-android' is not a Gradle-based project

7) Next point is gradle breaking and telling me

  "Error:A problem occurred configuring project ':app'."  and

"22:22 Gradle sync failed: A problem occurred configuring project ':app'.
            Consult IDE log for more details (Help | Show Log)"

I tried to update Kotlin's version as it says in the Event Log but nothing happened...

I also tried to check the Log as it says and this is what I had:

2017-03-21 22:22:54,418 [1045087]   WARN - nal.AbstractExternalSystemTask - A problem occurred configuring project ':app'.
com.intellij.openapi.externalSystem.model.ExternalSystemException: A problem occurred configuring project ':app'.

...

Caused by: org.gradle.api.ProjectConfigurationException: A problem occurred configuring project ':app'.

...

Caused by: kotlin.KotlinNullPointerException

... 64 more

2017-03-21 22:22:54,423 [1045092]   WARN - ect.sync.idea.ProjectSetUpTask -

2017-03-21 22:22:54,423 [1045092]   INFO - ect.sync.idea.ProjectSetUpTask - A problem occurred configuring project ':app'.

How can I fix this?

UPDATE: I uninstalled AS 2.3 and installed 2.2
Everything worked just fine. Then I thought it was solved and updated AS again into 2.3... So silly... I'm back to the start of this problem, guys...

答:
open prjectdir/gradle/gradle-wrapper.properties

and set

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
</code>```

open the project gradle (not gradle inside the module) and set

```<code>    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0+'
}
</code>```

And also check the docs.

Hope it helps

Body:
open prjectdir/gradle/gradle-wrapper.properties

and set

distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip

open the project gradle (not gradle inside the module) and set

    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0+'
}

And also check the docs.

Hope it helps


答:
```<code>if request.method == 'POST':
   form = PostForm(request.POST or None)
   if form.is_valid():
      // do your save work
</code>```

Title: Verify submitted Django form in view


问:
Mesos/Marathon - reserved resources for role are not offered for Marathon app
I have assigned slave resources to the particular role ("app-role") by set --default_role="app-role" parameter to ExecStart for slave service ( /etc/systemd/system/dcos-mesos-slave.service). Next I have restarted slave agent:

```<code>sudo systemctl daemon-reload
sudo systemctl stop dcos-mesos-slave.service
sudo rm -f /var/lib/mesos/slave/meta/slaves/latest
sudo systemctl start dcos-mesos-slave.service
</code>```

and verified by: curl master.mesos/mesos/slaves.

After that I expect marathon app with acceptedResourceRoles attribute  will receive only these particular resource offers, but it does not happen (the app is still in waiting state).

Why does marathon didn't receive it? How should this be done to make it work?

```<code>{
  "id": "/basic-4",
  "cmd": "python3 -m http.server 8080",
  "cpus": 0.5,
  "mem": 32,
  "disk": 0,
  "instances": 1,
  "acceptedResourceRoles": [
    "app-role"
  ],
  "container": {
    "type": "DOCKER",
    "volumes": [],
    "docker": {
      "image": "python:3",
      "network": "BRIDGE",
      "portMappings": [
        {
          "containerPort": 8080,
          "hostPort": 0,
          "servicePort": 10000,
          "protocol": "tcp",
          "name": "my-vip",
          "labels": {
            "VIP_0": "/my-service:5555"
          }
        }
      ],
      "privileged": false,
      "parameters": [],
      "forcePullImage": false
    }
  },
  "portDefinitions": [
    {
      "port": 10000,
      "protocol": "tcp",
      "name": "default",
      "labels": {}
    }
  ]
}
</code>```

答:
This works only if marathon is started with --mesos_role set.
In the context of the question this should be: --mesos_role 'app-role'.

If you set --mesos_role other, Marathon will register with Mesos for this role – it will receive offers for resources that are reserved
  for this role, in addition to unreserved resources.

If you set default_accepted_resource_roles *, Marathon will apply this default to all AppDefinitions that do not explicitly
  define acceptedResourceRoles. Since your AppDefinition defines that
  option, the default will not be applied (both are equal anyways).

If you set "acceptedResourceRoles": [""] in an AppDefinition (or the AppDefinition inherits a default of ""), Marathon will only
  consider unreserved resources for launching of this app.

More: https://mesosphere.github.io/marathon/docs/recipes.html

Body:
I have assigned slave resources to the particular role ("app-role") by set --default_role="app-role" parameter to ExecStart for slave service ( /etc/systemd/system/dcos-mesos-slave.service). Next I have restarted slave agent:

sudo systemctl daemon-reload
sudo systemctl stop dcos-mesos-slave.service
sudo rm -f /var/lib/mesos/slave/meta/slaves/latest
sudo systemctl start dcos-mesos-slave.service

and verified by: curl master.mesos/mesos/slaves.

After that I expect marathon app with acceptedResourceRoles attribute  will receive only these particular resource offers, but it does not happen (the app is still in waiting state).

Why does marathon didn't receive it? How should this be done to make it work?

{
  "id": "/basic-4",
  "cmd": "python3 -m http.server 8080",
  "cpus": 0.5,
  "mem": 32,
  "disk": 0,
  "instances": 1,
  "acceptedResourceRoles": [
    "app-role"
  ],
  "container": {
    "type": "DOCKER",
    "volumes": [],
    "docker": {
      "image": "python:3",
      "network": "BRIDGE",
      "portMappings": [
        {
          "containerPort": 8080,
          "hostPort": 0,
          "servicePort": 10000,
          "protocol": "tcp",
          "name": "my-vip",
          "labels": {
            "VIP_0": "/my-service:5555"
          }
        }
      ],
      "privileged": false,
      "parameters": [],
      "forcePullImage": false
    }
  },
  "portDefinitions": [
    {
      "port": 10000,
      "protocol": "tcp",
      "name": "default",
      "labels": {}
    }
  ]
}


问:
How can I get all rows with keys provided in a list using SQLalchemy?
I have sequence of IDs I want to retrieve. It's simple:

```<code>session.query(Record).filter(Record.id.in_(seq)).all()
</code>```

Is there a better way to do it?

答:
I'd recommend to take a look at the SQL it produces. You can just print str(query) to see it.

I'm not aware of an ideal way of doing it with standard SQL.

OwnerDisplayName: Cheery

ContentLicense: CC BY-SA 4.0

Body:
I have sequence of IDs I want to retrieve. It's simple:

session.query(Record).filter(Record.id.in_(seq)).all()

Is there a better way to do it?

OwnerDisplayName: iny


问:
CSS - Line height property, how it works (simple)
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

```<code>line-height:100px;
</code>```

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!

答:
Already been answered, but I thought I might add that the formula is usually is:

The difference between line-height and font-size is called Leading.
Then divide this Leading by 2 to get half-leading, which is put above and below your text causing it to be vertically centered.

The following set of slides will explain a lot about line-height. You can start at slide 72 for what I explained above, but I would recommend going through the whole set.

Body:
So in this simple example I have as final result:

This is a very simple question but I simply can't get my head around it.

To achieve the vertical centering of the numbers I used:

line-height:100px;

Which works great and have been doing it trial and error basis.

My question is specifically why the line-height:50px; just gets if half of the way.

If the small div has a height of 100px and I an positioning relative to it, shouldn't the half of it center it to the half.

This specially puzzles me since, when I center a div:

I would use: margin:50px 0 0 50px; to get this:

I realize this question might be an overkill since the answer might be (probably will be very simple), so sorry! but I guess it is better the "why doesn't this work" questions ;)

Thanks in advance!!