问:
Best practice for storing DateTime values in Firebase with Unity3d
I'm building a Unity3d 2D game where I'm using Firebase as the database. I need to store quite a lot of DateTime values (as UTC) in the database and I'm wondering what the best practice is for doing this.

The DateTime fields will mainly be used for sorting/filtering.

According to the Firebase documentation, I should make use of the Firebase.Database.ServerValues.TIMESTAMP which is just an object

Thing is, I'm using strongly typed models for my Unity game, like so:

```<code>[Serializable]
public class Profile {

    [NonSerialized]
    public string ProfileKey;

    // Serializable attributes
    public string userId;
    public string name;
    public int age;
    public string gender; // "M" or "F"
    public DateTime utcCreated; // UTC
    public DateTime utcUpdated; // UTC
}
</code>```

and when I save/update a Profile I'm using Unitys JsonUtility.ToJson() method, like this:

```<code>var profiles = db.Child ("profiles");

Profile profile = new Profile {
    userId = GameManager.Instance.User.UserId,
    name = "My new profile",
    age = 23,
    gender = "M",
    utcCreated = ?? // Should somehow use Firebase.Database.ServerValues.TIMESTAMP here, I guess?
};

string json = JsonUtility.ToJson (profile);

var profileKey = profiles.Push ().Key;

profiles.Child (profileKey).SetRawJsonValueAsync (json, 1).ContinueWith (t => {
    // .. handle response here
});
</code>```

I'm not sure what exactly I should set the utcCreated field to on my model. Tried to simply make the field an object, but no value was inserted into Firebase. Also tried to make it a string with a .ToString() to the Firebase.Database.ServerValues.TIMESTAMPobject, but no value was inserted in Firebase.

Does anyone have an idea how to do this? ;-) Or just any help/hint on best practices for storing dates and timestamps in Firebase?

Thanks in advance.

答:
Alright, for anyone else with this question who don't want to spend hours of hair-pulling frustration, the answer is: you cannot (and maybe should not, guess there's a reason for it) set the ServerValue.Timestamp object on your models/objects.

The ServerValue.Timestamp is something your specifically set on your Firebase documents by calling either SetValueAsync() or UpdateChildrenAsync()

So what I did, was adding two fields to my Profileclass: one which represents the unix timestamp server value and one, which represents the unix timestamp server value as a C# DateTime object:

```<code>using System;
using System.Collections.Generic;
using System.Linq;

[Serializable]
public class Profile
{

    [NonSerialized]
    public string profileKey;

    [NonSerialized]
    public long utcCreatedTimestamp;

    [NonSerialized]
    public DateTime utcCreated;

    // Serializable attributes
    public string userId;
    public string name;
    public int age;
    public string gender; // "M" or "F"

    public Profile() { }

    public Profile(Dictionary<string, object> fromFirebaseResult)
    {
        userId = fromFirebaseResult.ContainsKey("userId") ? fromFirebaseResult.First(x => x.Key == "userId").Value.ToString() : string.Empty;
        name = fromFirebaseResult.ContainsKey("name") ? fromFirebaseResult.First(x => x.Key == "name").Value.ToString() : string.Empty;
        age = fromFirebaseResult.ContainsKey("age") ? int.Parse(fromFirebaseResult.First(x => x.Key == "age").Value.ToString()) : 0;
        gender = fromFirebaseResult.ContainsKey("gender") ? fromFirebaseResult.First(x => x.Key == "gender").Value.ToString() : string.Empty;

        if (fromFirebaseResult.ContainsKey("utcCreatedUnix")) {
            long milliseconds;
            if(long.TryParse(fromFirebaseResult.First(x => x.Key == "utcCreatedUnix").Value.ToString(), out milliseconds)) {
                utcCreatedTimestamp = milliseconds;

                DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                utcCreated = epoch.AddMilliseconds(milliseconds);
            }
        }
    }
}
</code>```

The Profile class has a default constructor and a constructor, which takes a Dictionary<string, object> since that's what we get from Firebase when querying it from Unity.

When saving a new Profile to Firebase, I create a new Profile object without setting anything related to the date and time. Save it in Firebase and then call UpdateChildrenAsync which sets the utcCreatedUnix field in Firebase. Like so:

```<code>DatabaseReference db = FirebaseDatabase.DefaultInstance.RootReference;

// Get the user id
string userId = GameManager.Instance.User.UserId;

// Get a reference to the profiles
var profiles = db.Child("profiles");

// Create a new serializable profile
Profile profile = new Profile {
    userId = userId,
    name = "Bo Mortensen",
    age = 34,
    gender = "M"
};

// Serialize profile to JSON
string json = JsonUtility.ToJson (profile);

// Push a new document to the database
var profileKey = profiles.Push ().Key;

// Set JSON for this document
profiles.Child (profileKey).SetRawJsonValueAsync (json, 1).ContinueWith (t => {
    if (t.IsCompleted) {
        // Assign the profile key (unique key generated by Firebase) to the profile
        profile.profileKey = profileKey;

        // Set the Firebase server timestamp on the datetime object
        profiles.Child(profileKey).UpdateChildrenAsync(new Dictionary<string, object> { { "utcCreatedUnix", ServerValue.Timestamp } });
    }
});
</code>```

And when getting a Profile document from Firebase, I can now do:

```<code>var db = FirebaseDatabase.DefaultInstance.RootReference;

var profileRef = db.Child("profiles/MyProfileKey");

profileRef.GetValueAsync().ContinueWith(t =>
{
    var values = t.Result.Value as System.Collections.Generic.Dictionary<string, object>;

    // Let the constructor populate the fields
    Profile profile = new Profile(values)
    {
        profileKey = profileRef.Key
    };

    DateTime createdDate = profile.utcCreated;
});
</code>```

You might be asking why I'm not just storing  a DateTime.UtcNow.ToString() I could do that, but I don't want to rely on the clients clock settings. By using Firebases ServerValue.Timestamp, Firebase determines the correct time instead of the individual client using the app.

Hope this can be helpful to anyone else out there :-)

Body:
I'm building a Unity3d 2D game where I'm using Firebase as the database. I need to store quite a lot of DateTime values (as UTC) in the database and I'm wondering what the best practice is for doing this.

The DateTime fields will mainly be used for sorting/filtering.

According to the Firebase documentation, I should make use of the Firebase.Database.ServerValues.TIMESTAMP which is just an object

Thing is, I'm using strongly typed models for my Unity game, like so:

[Serializable]
public class Profile {

    [NonSerialized]
    public string ProfileKey;

    // Serializable attributes
    public string userId;
    public string name;
    public int age;
    public string gender; // "M" or "F"
    public DateTime utcCreated; // UTC
    public DateTime utcUpdated; // UTC
}

and when I save/update a Profile I'm using Unitys JsonUtility.ToJson() method, like this:

var profiles = db.Child ("profiles");

Profile profile = new Profile {
    userId = GameManager.Instance.User.UserId,
    name = "My new profile",
    age = 23,
    gender = "M",
    utcCreated = ?? // Should somehow use Firebase.Database.ServerValues.TIMESTAMP here, I guess?
};

string json = JsonUtility.ToJson (profile);

var profileKey = profiles.Push ().Key;

profiles.Child (profileKey).SetRawJsonValueAsync (json, 1).ContinueWith (t => {
    // .. handle response here
});

I'm not sure what exactly I should set the utcCreated field to on my model. Tried to simply make the field an object, but no value was inserted into Firebase. Also tried to make it a string with a .ToString() to the Firebase.Database.ServerValues.TIMESTAMPobject, but no value was inserted in Firebase.

Does anyone have an idea how to do this? ;-) Or just any help/hint on best practices for storing dates and timestamps in Firebase?

Thanks in advance.

Body:
Alright, for anyone else with this question who don't want to spend hours of hair-pulling frustration, the answer is: you cannot (and maybe should not, guess there's a reason for it) set the ServerValue.Timestamp object on your models/objects.

The ServerValue.Timestamp is something your specifically set on your Firebase documents by calling either SetValueAsync() or UpdateChildrenAsync()

So what I did, was adding two fields to my Profileclass: one which represents the unix timestamp server value and one, which represents the unix timestamp server value as a C# DateTime object:

using System;
using System.Collections.Generic;
using System.Linq;

[Serializable]
public class Profile
{

    [NonSerialized]
    public string profileKey;

    [NonSerialized]
    public long utcCreatedTimestamp;

    [NonSerialized]
    public DateTime utcCreated;

    // Serializable attributes
    public string userId;
    public string name;
    public int age;
    public string gender; // "M" or "F"

    public Profile() { }

    public Profile(Dictionary<string, object> fromFirebaseResult)
    {
        userId = fromFirebaseResult.ContainsKey("userId") ? fromFirebaseResult.First(x => x.Key == "userId").Value.ToString() : string.Empty;
        name = fromFirebaseResult.ContainsKey("name") ? fromFirebaseResult.First(x => x.Key == "name").Value.ToString() : string.Empty;
        age = fromFirebaseResult.ContainsKey("age") ? int.Parse(fromFirebaseResult.First(x => x.Key == "age").Value.ToString()) : 0;
        gender = fromFirebaseResult.ContainsKey("gender") ? fromFirebaseResult.First(x => x.Key == "gender").Value.ToString() : string.Empty;

        if (fromFirebaseResult.ContainsKey("utcCreatedUnix")) {
            long milliseconds;
            if(long.TryParse(fromFirebaseResult.First(x => x.Key == "utcCreatedUnix").Value.ToString(), out milliseconds)) {
                utcCreatedTimestamp = milliseconds;

                DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                utcCreated = epoch.AddMilliseconds(milliseconds);
            }
        }
    }
}

The Profile class has a default constructor and a constructor, which takes a Dictionary<string, object> since that's what we get from Firebase when querying it from Unity.

When saving a new Profile to Firebase, I create a new Profile object without setting anything related to the date and time. Save it in Firebase and then call UpdateChildrenAsync which sets the utcCreatedUnix field in Firebase. Like so:

DatabaseReference db = FirebaseDatabase.DefaultInstance.RootReference;

// Get the user id
string userId = GameManager.Instance.User.UserId;

// Get a reference to the profiles
var profiles = db.Child("profiles");

// Create a new serializable profile
Profile profile = new Profile {
    userId = userId,
    name = "Bo Mortensen",
    age = 34,
    gender = "M"
};

// Serialize profile to JSON
string json = JsonUtility.ToJson (profile);

// Push a new document to the database
var profileKey = profiles.Push ().Key;

// Set JSON for this document
profiles.Child (profileKey).SetRawJsonValueAsync (json, 1).ContinueWith (t => {
    if (t.IsCompleted) {
        // Assign the profile key (unique key generated by Firebase) to the profile
        profile.profileKey = profileKey;

        // Set the Firebase server timestamp on the datetime object
        profiles.Child(profileKey).UpdateChildrenAsync(new Dictionary<string, object> { { "utcCreatedUnix", ServerValue.Timestamp } });
    }
});

And when getting a Profile document from Firebase, I can now do:

var db = FirebaseDatabase.DefaultInstance.RootReference;

var profileRef = db.Child("profiles/MyProfileKey");

profileRef.GetValueAsync().ContinueWith(t =>
{
    var values = t.Result.Value as System.Collections.Generic.Dictionary<string, object>;

    // Let the constructor populate the fields
    Profile profile = new Profile(values)
    {
        profileKey = profileRef.Key
    };

    DateTime createdDate = profile.utcCreated;
});

You might be asking why I'm not just storing  a DateTime.UtcNow.ToString() I could do that, but I don't want to rely on the clients clock settings. By using Firebases ServerValue.Timestamp, Firebase determines the correct time instead of the individual client using the app.

Hope this can be helpful to anyone else out there :-)


来源: stackexchange

问:
Disable UnitOfWork project wide in ASP.NET Boilerplate
In ASP.NET Boilerplate we can disable UnitOfWork on method a level with attribute [UnitOfWork(IsDisabled = true)].

Is there a way to completely disable UoW interceptor throughout all the application and just rely on IUnitOfWorkManager?

答:
You can disable transaction in your module.</p>

```<code>Configuration.UnitOfWork.Scope = TransactionScopeOption.Suppress;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can disable transaction in your module.

Configuration.UnitOfWork.Scope = TransactionScopeOption.Suppress;


问:
How to have this kind of JSON Response formatting?
Good day. I have json response and I want to have this json format below so that I can parse it and stored it into a database. My current json response is invalid. hope you can correct my code so that I can have this kind of json response.

Expected JSON response

```<code>  {
      "login": {
          "error": false,
          "user": {
              "br_code": 12,
              "mem_id": 13,
              "username": "novalyn",
              "email": "gsac_tabaco@yahoo.com",
              "created_at": "2016-07-22 09:05:21"
          }
      },
      "accounts": {
          "error": false,
          "sl_summ": [{
                  "sl_desc": "PA : Savings Account",
                  "tr_date": "2015-08-17",
                  "actual_balance": "483.67",
                  "available_balance": "483.67"
              },
              {
                  "sl_desc": "PA : Savings - Cash Bond",
                  "tr_date": "2015-08-28",
                  "actual_balance": "10129.43",
                  "available_balance": "10129.43"
              }
          ]
      }
  }
</code>```

My current JSON format

```<code>{
    "error": false,
    "user": {
        "br_code": 12,
        "mem_id": 13,
        "username": "novalyn",
        "email": "gsac_tabaco@yahoo.com",
        "created_at": "2016-07-22 09:05:21"
    }
} {
    "error": false,
    "sl_summ": [{
        "sl_desc": "PA : Savings Account",
        "tr_date": "2015-08-17",
        "actual_balance": "483.67",
        "available_balance": "483.67"
    }, {
        "sl_desc": "PA : Savings - Cash Bond",
        "tr_date": "2015-08-28",
        "actual_balance": "10129.43",
        "available_balance": "10129.43"
    }]
}
</code>```

PHP code

```<code>$response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();
$user = $db->getUserByUsernameAndPassword($username, $password);

if ($user != null) {
    // user is found
    $response["error"] = FALSE;
    $response["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
    $response["user"]["mem_id"] = $user["MEMBER_ID"];
    $response["user"]["username"] = $user["USERNAME"];
    $response["user"]["email"] = $user["EMAIL"];
    $response["user"]["created_at"] = $user["REG_DATE"];
    json_encode($response, true);
    //Displaying json value
    echo json_encode($response, true);

     // FOR SL SUMM
     $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

        If($user_sldtl != null) {
             for($i = 0; $i < count($user_sldtl); $i++){
                $item = array();
                    $item["sl_desc"] = $user_sldtl[$i][7];
                    $item["tr_date"] = $user_sldtl[$i][10];
                    $item["actual_balance"] = $user_sldtl[$i][14];
                    $item["available_balance"] = $user_sldtl[$i][14];

                    $response = array("error" => FALSE);
                    $sl_response["sl_summ"][] = $item;
                }
                json_encode($sl_response);
                echo json_encode($sl_response, true);
         }
         else {
             $sl_response["error"] = TRUE;
             $sl_response["error_msg"] = "NO SL Details found!";
             echo json_encode($sl_response);
         }
}
else {
    // user is not found with the credentials
    $response["error"] = TRUE;
    $response["error_msg"] = "Login credentials are wrong. Please try again!";
    json_encode($response);
    echo json_encode($response);
    // echo "<br />" .$username. "<br />";
    // echo $password;
}
</code>```

答:
Construct one big multi-dimensional array containing all the results, then call echo json_encode() at the very end.

Also,  I'm not sure why you put json_encode($variable); before each echo json_encode($variable); line -- json_encode() doesn't have any side effects, it just returns the encoded string.

```<code><?php
$login_response = array();

$user = $db->getUserByUsernameAndPassword($username, $password);

if ($user != null) {
    // user is found
    $login_response["error"] = FALSE;
    $login_response["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
    $login_response["user"]["mem_id"] = $user["MEMBER_ID"];
    $login_response["user"]["username"] = $user["USERNAME"];
    $login_response["user"]["email"] = $user["EMAIL"];
    $login_response["user"]["created_at"] = $user["REG_DATE"];

    // FOR SL SUMM
    $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

    $sl_response = array();
    If($user_sldtl != null) {
        $sl_response["error"] = FALSE;
        $sl_response["sl_summ"] = array();
        foreach ($user_sldtl as $dtl)){
            $item = array();
            $item["sl_desc"] = $dtl[7];
            $item["tr_date"] = $dtl[10];
            $item["actual_balance"] = $dtl[14];
            $item["available_balance"] = $dtl[14];

            $sl_response["sl_summ"][] = $item;
        }
    }
    else {
        $sl_response["error"] = TRUE;
        $sl_response["error_msg"] = "NO SL Details found!";
    }
    $response = array("login" => $login_response, "accounts" => $sl_response);
}
else {
    // user is not found with the credentials
    $login_response["error"] = TRUE;
    $login_response["error_msg"] = "Login credentials are wrong. Please try again!";
    $response = array("login" => $login_response);
}

echo json_encode($response);
</code>```

Body:
Good day. I have json response and I want to have this json format below so that I can parse it and stored it into a database. My current json response is invalid. hope you can correct my code so that I can have this kind of json response.

Expected JSON response

  {
      "login": {
          "error": false,
          "user": {
              "br_code": 12,
              "mem_id": 13,
              "username": "novalyn",
              "email": "gsac_tabaco@yahoo.com",
              "created_at": "2016-07-22 09:05:21"
          }
      },
      "accounts": {
          "error": false,
          "sl_summ": [{
                  "sl_desc": "PA : Savings Account",
                  "tr_date": "2015-08-17",
                  "actual_balance": "483.67",
                  "available_balance": "483.67"
              },
              {
                  "sl_desc": "PA : Savings - Cash Bond",
                  "tr_date": "2015-08-28",
                  "actual_balance": "10129.43",
                  "available_balance": "10129.43"
              }
          ]
      }
  }

My current JSON format

{
    "error": false,
    "user": {
        "br_code": 12,
        "mem_id": 13,
        "username": "novalyn",
        "email": "gsac_tabaco@yahoo.com",
        "created_at": "2016-07-22 09:05:21"
    }
} {
    "error": false,
    "sl_summ": [{
        "sl_desc": "PA : Savings Account",
        "tr_date": "2015-08-17",
        "actual_balance": "483.67",
        "available_balance": "483.67"
    }, {
        "sl_desc": "PA : Savings - Cash Bond",
        "tr_date": "2015-08-28",
        "actual_balance": "10129.43",
        "available_balance": "10129.43"
    }]
}

PHP code

$response = array("error" => FALSE);
$sl_response["error"] = FALSE;
$sl_response["sl_summ"] = array();
$user = $db->getUserByUsernameAndPassword($username, $password);

if ($user != null) {
    // user is found
    $response["error"] = FALSE;
    $response["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
    $response["user"]["mem_id"] = $user["MEMBER_ID"];
    $response["user"]["username"] = $user["USERNAME"];
    $response["user"]["email"] = $user["EMAIL"];
    $response["user"]["created_at"] = $user["REG_DATE"];
    json_encode($response, true);
    //Displaying json value
    echo json_encode($response, true);

     // FOR SL SUMM
     $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

        If($user_sldtl != null) {
             for($i = 0; $i < count($user_sldtl); $i++){
                $item = array();
                    $item["sl_desc"] = $user_sldtl[$i][7];
                    $item["tr_date"] = $user_sldtl[$i][10];
                    $item["actual_balance"] = $user_sldtl[$i][14];
                    $item["available_balance"] = $user_sldtl[$i][14];

                    $response = array("error" => FALSE);
                    $sl_response["sl_summ"][] = $item;
                }
                json_encode($sl_response);
                echo json_encode($sl_response, true);
         }
         else {
             $sl_response["error"] = TRUE;
             $sl_response["error_msg"] = "NO SL Details found!";
             echo json_encode($sl_response);
         }
}
else {
    // user is not found with the credentials
    $response["error"] = TRUE;
    $response["error_msg"] = "Login credentials are wrong. Please try again!";
    json_encode($response);
    echo json_encode($response);
    // echo "
" .$username. "
";
    // echo $password;
}

Body:
Construct one big multi-dimensional array containing all the results, then call echo json_encode() at the very end.

Also,  I'm not sure why you put json_encode($variable); before each echo json_encode($variable); line -- json_encode() doesn't have any side effects, it just returns the encoded string.

<?php
$login_response = array();

$user = $db->getUserByUsernameAndPassword($username, $password);

if ($user != null) {
    // user is found
    $login_response["error"] = FALSE;
    $login_response["user"]["br_code"] = $user["MEMBER_ID_BRCODE"];
    $login_response["user"]["mem_id"] = $user["MEMBER_ID"];
    $login_response["user"]["username"] = $user["USERNAME"];
    $login_response["user"]["email"] = $user["EMAIL"];
    $login_response["user"]["created_at"] = $user["REG_DATE"];

    // FOR SL SUMM
    $user_sldtl = $db->getUserSLsummary($arclass, $loanclass, $accintreceivable, $date, $year, $month, $br_code, $clientid);

    $sl_response = array();
    If($user_sldtl != null) {
        $sl_response["error"] = FALSE;
        $sl_response["sl_summ"] = array();
        foreach ($user_sldtl as $dtl)){
            $item = array();
            $item["sl_desc"] = $dtl[7];
            $item["tr_date"] = $dtl[10];
            $item["actual_balance"] = $dtl[14];
            $item["available_balance"] = $dtl[14];

            $sl_response["sl_summ"][] = $item;
        }
    }
    else {
        $sl_response["error"] = TRUE;
        $sl_response["error_msg"] = "NO SL Details found!";
    }
    $response = array("login" => $login_response, "accounts" => $sl_response);
}
else {
    // user is not found with the credentials
    $login_response["error"] = TRUE;
    $login_response["error_msg"] = "Login credentials are wrong. Please try again!";
    $response = array("login" => $login_response);
}

echo json_encode($response);


问:
Batch file that keeps the 7 latest files in a folder
Can anyone help me create a batch file? Basically, my goal is to create a batch file that will keep the LATEST 7 .txt files (in other words, the newest) in the folder and subsequently delete the rest. That's IF there are more than 7 files in the folder.

The problem I'm having right now is the fact that the batch file that I have created deletes most of the files because their date is from a month or two or so. I want to keep the latest 7 files at all times no matter how old they are.

So this is what I have -

```<code>@echo off

setlocal enableextensions

rem ********************************************************************************
rem *******************************  LOCAL VARIABLES  ******************************
rem ********************************************************************************

SET TargetDirectory="C:\TEMP\test"

SET No_of_fles_to_keep=7

SET count=0

set cnt=0

rem ********************************************************************************

cd /d %TargetDirectory%

REM timeout /T 500

 for %%x in (*) do set /a count+=1

 for %%A in (*.bat) do set /a cnt+=1

cd /d %TargetDirectory%

REM timeout /T 500

IF %count% gtr %No_of_fles_to_keep% forfiles -p %TargetDirectory% -s -m "*.txt" -d -%No_of_fles_to_keep% -c "cmd /c del @path"

echo %count%

echo File count = %cnt%
</code>```

Any help is appreciated.

答:
This will keep 7 latest .txt files and remove all other .txt files

Execute below command in same directory from which you want to delete files

On command prompt

```<code>for /f "skip=7 eol=: delims=" %F in ('dir /b /o-d /a-d *.txt') do @del "%F"
</code>```

Inside batch script

```<code>for /f "skip=7 eol=: delims=" %%F in ('dir /b /o-d /a-d *.txt') do @del "%%F"
</code>```

Body:
Can anyone help me create a batch file? Basically, my goal is to create a batch file that will keep the LATEST 7 .txt files (in other words, the newest) in the folder and subsequently delete the rest. That's IF there are more than 7 files in the folder.

The problem I'm having right now is the fact that the batch file that I have created deletes most of the files because their date is from a month or two or so. I want to keep the latest 7 files at all times no matter how old they are.

So this is what I have -

@echo off

setlocal enableextensions

rem ********************************************************************************
rem *******************************  LOCAL VARIABLES  ******************************
rem ********************************************************************************

SET TargetDirectory="C:\TEMP\test"

SET No_of_fles_to_keep=7

SET count=0

set cnt=0

rem ********************************************************************************

cd /d %TargetDirectory%

REM timeout /T 500

 for %%x in (*) do set /a count+=1

 for %%A in (*.bat) do set /a cnt+=1

cd /d %TargetDirectory%

REM timeout /T 500

IF %count% gtr %No_of_fles_to_keep% forfiles -p %TargetDirectory% -s -m "*.txt" -d -%No_of_fles_to_keep% -c "cmd /c del @path"

echo %count%

echo File count = %cnt%

Any help is appreciated.

Body:
This will keep 7 latest .txt files and remove all other .txt files

Execute below command in same directory from which you want to delete files

On command prompt

for /f "skip=7 eol=: delims=" %F in ('dir /b /o-d /a-d *.txt') do @del "%F"

Inside batch script

for /f "skip=7 eol=: delims=" %%F in ('dir /b /o-d /a-d *.txt') do @del "%%F"


问:
Calling a Web API action that has same signature as another
I have an ASP .Net Core 1.1 Web Api. In one of my controllers, I'd like two actions:

```<code>[HttpGet("{userId:int}")]
public async Task<IActionResult> GetUser([FromRoute] int id)
{
    return Ok(_context.User.Where(u.Id == id));
}

[HttpGet("{groupId:int}")]
public async Task<IActionResult> GetUsersInGroup([FromRoute] int groupId)
{
    return Ok(_context.User.Where(u.GroupId == groupId));
}
</code>```

Both actions have the same signature, except for the method name. How can I make it so that I can call upon the one or the other?

Thanks...

答:
Think about it from the routing component's point of view. What would you do if you receive a URL like /api/users/123 and you have the above actions in a controller?

You have to differentiate them, with e.g. attributes:

```<code>[Route("api/users")]
public class UsersController : Controller
{
    [HttpGet("{userId:int}")]
    public async Task<IActionResult> GetUser([FromRoute] int userId)
    {
        return Ok(_context.User.Where(u.Id == userId));
    }

    [HttpGet("group/{groupId:int}")]
    public async Task<IActionResult> GetUsersInGroup([FromRoute] int groupId)
    {
        return Ok(_context.User.Where(u.GroupId == groupId));
    }
}
</code>```

Now they can be accessed with:

/api/users/123

/api/users/group/123

The controller-level Route-attribute sets a common prefix for all routes so you don't need to specify it for all of them.

Then the HttpGet attribute specifies an additional prefix so they are fundamentally different routes.

Body:
I have an ASP .Net Core 1.1 Web Api. In one of my controllers, I'd like two actions:

[HttpGet("{userId:int}")]
public async Task<IActionResult> GetUser([FromRoute] int id)
{
    return Ok(_context.User.Where(u.Id == id));
}

[HttpGet("{groupId:int}")]
public async Task<IActionResult> GetUsersInGroup([FromRoute] int groupId)
{
    return Ok(_context.User.Where(u.GroupId == groupId));
}

Both actions have the same signature, except for the method name. How can I make it so that I can call upon the one or the other?

Thanks...

Body:
Think about it from the routing component's point of view. What would you do if you receive a URL like /api/users/123 and you have the above actions in a controller?

You have to differentiate them, with e.g. attributes:

[Route("api/users")]
public class UsersController : Controller
{
    [HttpGet("{userId:int}")]
    public async Task<IActionResult> GetUser([FromRoute] int userId)
    {
        return Ok(_context.User.Where(u.Id == userId));
    }

    [HttpGet("group/{groupId:int}")]
    public async Task<IActionResult> GetUsersInGroup([FromRoute] int groupId)
    {
        return Ok(_context.User.Where(u.GroupId == groupId));
    }
}

Now they can be accessed with:

/api/users/123

/api/users/group/123

The controller-level Route-attribute sets a common prefix for all routes so you don't need to specify it for all of them.

Then the HttpGet attribute specifies an additional prefix so they are fundamentally different routes.


问:
Add PTR record using dnspython
Im trying to add a PTR record with dnspython to bind9 using this code:

```<code>def send_query(query, server):
    update = dns.query
    update.tcp(query, server)

def add(name, rdtype, rdata, ttl=300, zone):
    server = dns.resolver.Resolver()
    server.nameservers = '<dns server>'
    keyring = dns.tsigkeyring.from_text({
            'key-name': 'key'
    })
    record = dns.update.Update(zone=zone, keyring=keyring)
    record.add(name, ttl, rdtype, rdata)
    send_query(record, server.nameservers)
</code>```

Im able to successfully add the record when passing:

```<code>name = last octet
rdtype = PTR
data = server-FQDN
zone = z.y.x.in-addr.arpa
</code>```

but when querying the dns server via nslookup I get:

```<code>~ nslookup X.Y.Z.6
Server:     NS server
Address:    NS server#53

6.Z.Y.X.in-addr.arpa        name = server-FQDN.Z.Y.X.in-addr.arpa.
</code>```

The problem is the "Z.Y.X.in-addr.arpa." part added to the query.
In the zone file the record is in the right syntax

Is there a better way to add PTR record with dnspython?

答: The reason this didn't work was that I forgot to add the ending "." at the end of the hostname FDQN and therefore the domain was completed automatically.</p>

Title: Add PTR record using dnspython

Body:
Im trying to add a PTR record with dnspython to bind9 using this code:

def send_query(query, server):
    update = dns.query
    update.tcp(query, server)

def add(name, rdtype, rdata, ttl=300, zone):
    server = dns.resolver.Resolver()
    server.nameservers = '<dns server>'
    keyring = dns.tsigkeyring.from_text({
            'key-name': 'key'
    })
    record = dns.update.Update(zone=zone, keyring=keyring)
    record.add(name, ttl, rdtype, rdata)
    send_query(record, server.nameservers)

Im able to successfully add the record when passing:

name = last octet
rdtype = PTR
data = server-FQDN
zone = z.y.x.in-addr.arpa

but when querying the dns server via nslookup I get:

~ nslookup X.Y.Z.6
Server:     NS server
Address:    NS server#53

6.Z.Y.X.in-addr.arpa        name = server-FQDN.Z.Y.X.in-addr.arpa.

The problem is the "Z.Y.X.in-addr.arpa." part added to the query.
In the zone file the record is in the right syntax

Is there a better way to add PTR record with dnspython?


问:
How to create tab url
This my tab. I want when page reload open second tab. How can I do that

HTML

```<code><li role="presentation" class="active">
 <a href="#details" aria-controls="details" role="tab" data-toggle="tab">Details</a>
</li>
 <li role="presentation">
<a href="#comments" aria-controls="comments" role="tab" data-toggle="tab">Comments: (<?php echo $comments_count[0]->total?>)</a>
</li>
</code>```

I am found this jQuery code but its not working:

```<code>// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
    $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
}

// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
})
</code>```

答:
You can use this bit of code

Html file

```<code><ul class="nav nav-tabs" id="myTab">
  <li class="active"><a href="#home">Home</a></li>
  <li><a href="#profile">Profile</a></li>
  <li><a href="#messages">Messages</a></li>
  <li><a href="#settings">Settings</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="home">home</div>
  <div class="tab-pane" id="profile">profile</div>
  <div class="tab-pane" id="messages">messages</div>
  <div class="tab-pane" id="settings">settings</div>
</div>
</code>```

Javascript part

```<code>$('#myTab a').click(function(e) {
  e.preventDefault();
  $(this).tab('show');
});

// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
  var id = $(e.target).attr("href").substr(1);
  window.location.hash = id;
});

// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#myTab a[href="' + hash + '"]').tab('show');
</code>```

Title: How to create tab url

Body:
This my tab. I want when page reload open second tab. How can I do that

HTML

 Details

Comments: (<?php echo $comments_count[0]->total?>)

I am found this jQuery code but its not working:

// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
    $('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
}

// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
})

Body:
You can use this bit of code

Html file

<ul class="nav nav-tabs" id="myTab">
  <li class="active"><a href="#home">Home</a></li>
  <li><a href="#profile">Profile</a></li>
  <li><a href="#messages">Messages</a></li>
  <li><a href="#settings">Settings</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="home">home</div>
  <div class="tab-pane" id="profile">profile</div>
  <div class="tab-pane" id="messages">messages</div>
  <div class="tab-pane" id="settings">settings</div>
</div>

Javascript part

$('#myTab a').click(function(e) {
  e.preventDefault();
  $(this).tab('show');
});

// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
  var id = $(e.target).attr("href").substr(1);
  window.location.hash = id;
});

// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#myTab a[href="' + hash + '"]').tab('show');


问:
Crashlytics.log not showing in Fabric Dashboard
I am using Crashlytics and fatal crashes get delivered.
However the data added with

```<code>Crashlytics.log(mytext);
</code>```

is not showing anywhere in Fabric Dashboard.

I couldnt find any hint on a necessary setup or configuration in the docs.
What am I missing?

答:
Mike from Fabric here. Custom logs, keys and user identifiers are included on a per crash basis. To view them, go from your  and click on a specific issue.

Then click on "View All Sessions"

and you'll see the most recent session and specific data:

One thing to note is that you need to set this on each launch of the app once you know the values. They are not persisted across multiple launches.

Body:
I am using Crashlytics and fatal crashes get delivered.
However the data added with

Crashlytics.log(mytext);

is not showing anywhere in Fabric Dashboard.

I couldnt find any hint on a necessary setup or configuration in the docs.
What am I missing?


问:
How to read a jasmine spec file config variable from the jasmine.json file
I am learning the node.js jasmine code testing framework and would like to set a variable that will be reused in several test spec files.  Is there a way to read a config variable from the jasmine.json file?

I have used the 'process.env.npm_variablename' for normal package.json node.js config variables, but that file is not loaded by the jasmine test runner.

答:
Part way through typing the question, I thought of a solution that seems to be working: load the file with the 'require' function.  It looks like this in the initialized current 2.6 jasmine structure:</p>

```<code>var jas_config = require('./support/jasmine.json');
if (jas_config.verbose_output) {
    console.log("loading test-spec.js");
}
</code>```

Body:
Part way through typing the question, I thought of a solution that seems to be working: load the file with the 'require' function.  It looks like this in the initialized current 2.6 jasmine structure:

var jas_config = require('./support/jasmine.json');
if (jas_config.verbose_output) {
    console.log("loading test-spec.js");
}


问:
insert into new table from existing table with an added new field
I need to insert (a monthly backup I'll be restoring into my source_database) into the dest_database, and add a new DATE field which would state which month is the data from. So in the end everything will be in the dest_database with the DATE field specifying to which month it belongs.

What'd I need to do?

```<code>INSERT INTO dest_table
(SELECT *
FROM source_table)
</code>```

答:
You need to specify the column names and add the extra column.

See the new_date_col1 in the below sql.

```<code>INSERT INTO dest_table ( old_col1, old_col2, new_date_col1)
SELECT old_col1, old_col2, getdate() FROM source_table
</code>```

Body:
I need to insert (a monthly backup I'll be restoring into my source_database) into the dest_database, and add a new DATE field which would state which month is the data from. So in the end everything will be in the dest_database with the DATE field specifying to which month it belongs.

What'd I need to do?

INSERT INTO dest_table
(SELECT *
FROM source_table)

Body:
You need to specify the column names and add the extra column.

See the new_date_col1 in the below sql.

INSERT INTO dest_table ( old_col1, old_col2, new_date_col1)
SELECT old_col1, old_col2, getdate() FROM source_table


答:
Assuming you have created the dest_table with the same fields and datatype as the source_table, you would just need to add a single column to that table prior to the insert.

```<code>create table dest_table
(column1 <datatype>,
...,
...,
LoadDate datetime);
GO

insert into dest_table (column1,...,LoadDate)
select
   column1,
   ...,
   getdate()
from source_table
</code>```

Or, simply

```<code>select
   column1,
   ...,
   getdate()
into dest_table
from source_table
</code>```

Title: insert into new table from existing table with an added new field

Body:
Assuming you have created the dest_table with the same fields and datatype as the source_table, you would just need to add a single column to that table prior to the insert.

create table dest_table
(column1 <datatype>,
...,
...,
LoadDate datetime);
GO

insert into dest_table (column1,...,LoadDate)
select
   column1,
   ...,
   getdate()
from source_table

Or, simply

select
   column1,
   ...,
   getdate()
into dest_table
from source_table


问:
XAML MVVM Multibinding
I have an MVVM WPF application, that has 'user settings' injected into the view. These settings contain things like last used search terms, or column widths on datagrids etc. This works nicely and the ViewModel is unaware of these settings as they are View Specific and a ViewModel may be shared by multiple views.

These values are bound to in the Xaml of the View.

However, some of the settings have a level of interference with properties on the ViewModel.

An example:

ViewModel has a property of public int MaxResults { get; set; } that is used to limit the number of results a query brings back.

When the user changes this value from, say, 100 to 50, ideally we want this saved in the View's settings; thus enabling the next time the View is used the value 50 is used rather than 100.

my first question:

How can I bind both the View Settings, and the ViewModel property to the same element? I am thinking a multi value converter, but am unsure of whether there are funkier ways of performing this operation. I need both the bindings to be 2 way, but also not get into any horrible update loops.

my second question:

Sometimes I'll want the ViewModel to take precedence over values supplied by the View Settings. I'm wondering if anyone has any suggestions as to allowing one bound value take precendence over another.

Any comments / answers / questions greatly appreciated.

答:
I don't see the point in having the ViewModel ignorant of these settings. I'd have your VM in control of these user preferences and have the view pick them up via binding.

This has the advantage of you having control of these prefs from your view model AND you can test that your user preferences are being loaded correctly in the VM via your unit tests.

Remember, your VM is a View on your Model so having your user preferences loaded via your VM makes perfect sense here and much less likely to have edge-cases like these.

ContentLicense: CC BY-SA 2.5

Title: XAML MVVM Multibinding


问:
How to return Json rather than a string in Web Api
I tried to look through some links but didn't work for me but this is what I have:

```<code>[HttpGet]
public string GetTimes()
{
    var varCheck = checkUser();

    if (varCheck.Item1)
    {
        using (SqlConnection sc = new SqlConnection(connectionTest))
        {
            try
            {
                sc.Open();

                using (SqlDataAdapter sda = new SqlDataAdapter("GetTheTimes", sc))
                {
                    sda.SelectCommand.CommandType = CommandType.StoredProcedure;
                    sda.Fill(ds);

                    foreach (DataTable table in ds.Tables)
                    {
                        foreach (DataRow row in table.Rows)
                        {
                            listItems.Add(new DataCheck
                            {
                                var1 = row["var1"].ToString(),
                                var2 = row["var2"].ToString()
                            });
                        }
                    }
                }
            }
            catch (SqlException sqe)
            {
                return "There was an error with retrieving the data, please try again later";
            }
            finally
            {
                sc.Close();
            }
        }

        var jsonSerialier = new JavaScriptSerializer();
        var json = jsonSerialier.Serialize(listItems);

        return json;
    }
    else
    {
        return "Failed";
    }
}
</code>```

When the API is called it is returned with escape double quotes. How can I modify so it returns a pure Json Object.

答:
Try this:</p>

```<code>[HttpGet]
//to prevent conflict with HttpGet use inline namespacing
public System.Web.Mvc.JsonResult GetTimes()
{
    return new System.Web.Mvc.JsonResult { Data = result };
}
</code>```

Body:
I tried to look through some links but didn't work for me but this is what I have:

[HttpGet]
public string GetTimes()
{
    var varCheck = checkUser();

    if (varCheck.Item1)
    {
        using (SqlConnection sc = new SqlConnection(connectionTest))
        {
            try
            {
                sc.Open();

                using (SqlDataAdapter sda = new SqlDataAdapter("GetTheTimes", sc))
                {
                    sda.SelectCommand.CommandType = CommandType.StoredProcedure;
                    sda.Fill(ds);

                    foreach (DataTable table in ds.Tables)
                    {
                        foreach (DataRow row in table.Rows)
                        {
                            listItems.Add(new DataCheck
                            {
                                var1 = row["var1"].ToString(),
                                var2 = row["var2"].ToString()
                            });
                        }
                    }
                }
            }
            catch (SqlException sqe)
            {
                return "There was an error with retrieving the data, please try again later";
            }
            finally
            {
                sc.Close();
            }
        }

        var jsonSerialier = new JavaScriptSerializer();
        var json = jsonSerialier.Serialize(listItems);

        return json;
    }
    else
    {
        return "Failed";
    }
}

When the API is called it is returned with escape double quotes. How can I modify so it returns a pure Json Object.

Body:
Try this:

[HttpGet]
//to prevent conflict with HttpGet use inline namespacing
public System.Web.Mvc.JsonResult GetTimes()
{
    return new System.Web.Mvc.JsonResult { Data = result };
}


问:
Bad Access on [UICollectionView setCollectionViewLayout:animated:]
I'm getting a strange crash in my UICollectionView.
The crashing UICollectionView is embedded in an UICollectionView cell of another UICollectionView.

I can't reproduce the issue, it seems to happen sometimes if the inner UICollectionView get's newly initialized because the outer CollectionView is reloading it's cells.

```

com.apple.main-thread Crashed
0   libobjc.A.dylib     objc_msgSend + 9
1   UIKit   -[UICollectionViewData _setLayoutAttributes:atGlobalItemIndex:] + 60
2   UIKit   __45-[UICollectionViewData validateLayoutInRect:]_block_invoke_0 + 668
3   UIKit   -[UICollectionViewData validateLayoutInRect:] + 1408
4   UIKit   -[UICollectionViewData layoutAttributesForElementsInRect:] + 82
5   UIKit   -[UICollectionView setCollectionViewLayout:animated:] + 1644
6   MyApp   BSCTopnewsCollectionView.m line 52 -[BSCTopnewsCollectionView setupBSCTopnewsCollectionView]
7   MyApp   BSCTopnewsCollectionView.m line 27 -[BSCTopnewsCollectionView setWeakDelegatePointer:]
8   Myapp   BSCFrontPageViewController.m line 550 -[BSCFrontPageViewController collectionView:cellForItemAtIndexPath:]
9   UIKit   -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:] + 252
10  UIKit   -[UICollectionView _updateVisibleCellsNow:] + 2672
11  UIKit   -[UICollectionView layoutSubviews] + 214
12  UIKit   -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 258
13  QuartzCore  -[CALayer layoutSublayers] + 214
14  QuartzCore  CA::Layer::layout_if_needed(CA::Transaction*) + 460
15  QuartzCore  CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 16
16  QuartzCore  CA::Context::commit_transaction(CA::Transaction*) + 238
17  QuartzCore  CA::Transaction::commit() + 316
18  QuartzCore  CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 60
19  CoreFoundation  __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 20
25  UIKit   UIApplicationMain + 1120
26  MyApp   main.m line 16 main

Exception Type:
    EXC_BAD_ACCESS
Code:
    KERN_INVALID_ADDRESS at 0x158848
```

What I'm doing in line 52 in setupBSCTopnewsCollectionView is

```
BSCInfiniteLayout *infiniteLayout = [[BSCInfiniteLayout alloc] init];

(line 52) self.collectionView.collectionViewLayout = infiniteLayout;
```

Edit: -[BSCFrontPageViewController collectionView:cellForItemAtIndexPath:]

```<code>- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if([collectionView isEqual:self.collectionView])
    {
        if(indexPath.row == 0) // Header Cell
        {
            BSCTopnewsCollectionView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:BSCHeaderReuseIdentifier forIndexPath:indexPath];
            cell.dataSource = self;
            cell.weakDelegatePointer = self;

            self.topNewsCollectionView = cell;

            return cell;
        }
        else
        {
            //create normal cells
        }
    }
    else if ([collectionView isEqual:self.topNewsCollectionView.collectionView])
    {
        BSCTopNewsHeaderCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:BSCTopNewsCellReuseIdentifier forIndexPath:indexPath];
        BSCNews *topnews = [self.topNews objectAtIndex:indexPath.row];

        [cell setEntity:topnews];

        return cell;
    }
}
</code>```

A few clarifications for the method calls there:

```<code>- (void)setWeakDelegatePointer:(BSCFrontPageViewController *)weakDelegatePointer
{
    _weakDelegatePointer = weakDelegatePointer;

    [self setupBSCTopnewsCollectionView];
    [self.collectionView reloadData];
}

- (void)setupBSCTopnewsCollectionView
{
    self.collectionView.delegate = self.weakDelegatePointer;
    self.collectionView.dataSource = self.weakDelegatePointer;

    BSCInfiniteLayout *infiniteLayout = [[BSCInfiniteLayout alloc] init];

    infiniteLayout.delegate = self;

    // Setup Layout
    self.collectionView.collectionViewLayout = infiniteLayout;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.pagingEnabled = YES;

    // Register Cells
    [self.collectionView registerNib:[UINib nibWithNibName:@"BSCTopNewsHeaderCell" bundle:nil] forCellWithReuseIdentifier:BSCTopNewsCellReuseIdentifier];
}
</code>```

Edit3: The crash only seems to occur in special occasions.
If the app was in the background, but still in memory and the user opens it up again. It then checks our API for new data, and if it found something will load them and reload the whole outer collectionView. Thats when the crash occurs.

If the CollectionView is reloaded while the app is running without being in the background in the beginning everything is fine.

To make the setup a bit more clear.

答:
Pulling our "Answer" out of the comments.

Sadly none of the answers helped. I ended up refactoring the whole thing and then the problem disappeared. I even had an pretty detailed talk with an apple DTS engineer who also didn't knew what to do. So we just refactored. Sorry :/

Body:
I'm getting a strange crash in my UICollectionView.
The crashing UICollectionView is embedded in an UICollectionView cell of another UICollectionView.

I can't reproduce the issue, it seems to happen sometimes if the inner UICollectionView get's newly initialized because the outer CollectionView is reloading it's cells.

com.apple.main-thread Crashed
0   libobjc.A.dylib     objc_msgSend + 9
1   UIKit   -[UICollectionViewData _setLayoutAttributes:atGlobalItemIndex:] + 60
2   UIKit   __45-[UICollectionViewData validateLayoutInRect:]_block_invoke_0 + 668
3   UIKit   -[UICollectionViewData validateLayoutInRect:] + 1408
4   UIKit   -[UICollectionViewData layoutAttributesForElementsInRect:] + 82
5   UIKit   -[UICollectionView setCollectionViewLayout:animated:] + 1644
6   MyApp   BSCTopnewsCollectionView.m line 52 -[BSCTopnewsCollectionView setupBSCTopnewsCollectionView]
7   MyApp   BSCTopnewsCollectionView.m line 27 -[BSCTopnewsCollectionView setWeakDelegatePointer:]
8   Myapp   BSCFrontPageViewController.m line 550 -[BSCFrontPageViewController collectionView:cellForItemAtIndexPath:]
9   UIKit   -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:] + 252
10  UIKit   -[UICollectionView _updateVisibleCellsNow:] + 2672
11  UIKit   -[UICollectionView layoutSubviews] + 214
12  UIKit   -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 258
13  QuartzCore  -[CALayer layoutSublayers] + 214
14  QuartzCore  CA::Layer::layout_if_needed(CA::Transaction*) + 460
15  QuartzCore  CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 16
16  QuartzCore  CA::Context::commit_transaction(CA::Transaction*) + 238
17  QuartzCore  CA::Transaction::commit() + 316
18  QuartzCore  CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 60
19  CoreFoundation  __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 20
25  UIKit   UIApplicationMain + 1120
26  MyApp   main.m line 16 main

Exception Type:
    EXC_BAD_ACCESS
Code:
    KERN_INVALID_ADDRESS at 0x158848

What I'm doing in line 52 in setupBSCTopnewsCollectionView is

BSCInfiniteLayout *infiniteLayout = [[BSCInfiniteLayout alloc] init];

(line 52) self.collectionView.collectionViewLayout = infiniteLayout;

Edit: -[BSCFrontPageViewController collectionView:cellForItemAtIndexPath:]

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if([collectionView isEqual:self.collectionView])
    {
        if(indexPath.row == 0) // Header Cell
        {
            BSCTopnewsCollectionView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:BSCHeaderReuseIdentifier forIndexPath:indexPath];
            cell.dataSource = self;
            cell.weakDelegatePointer = self;

            self.topNewsCollectionView = cell;

            return cell;
        }
        else
        {
            //create normal cells
        }
    }
    else if ([collectionView isEqual:self.topNewsCollectionView.collectionView])
    {
        BSCTopNewsHeaderCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:BSCTopNewsCellReuseIdentifier forIndexPath:indexPath];
        BSCNews *topnews = [self.topNews objectAtIndex:indexPath.row];

        [cell setEntity:topnews];

        return cell;
    }
}

A few clarifications for the method calls there:

- (void)setWeakDelegatePointer:(BSCFrontPageViewController *)weakDelegatePointer
{
    _weakDelegatePointer = weakDelegatePointer;

    [self setupBSCTopnewsCollectionView];
    [self.collectionView reloadData];
}

- (void)setupBSCTopnewsCollectionView
{
    self.collectionView.delegate = self.weakDelegatePointer;
    self.collectionView.dataSource = self.weakDelegatePointer;

    BSCInfiniteLayout *infiniteLayout = [[BSCInfiniteLayout alloc] init];

    infiniteLayout.delegate = self;

    // Setup Layout
    self.collectionView.collectionViewLayout = infiniteLayout;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.pagingEnabled = YES;

    // Register Cells
    [self.collectionView registerNib:[UINib nibWithNibName:@"BSCTopNewsHeaderCell" bundle:nil] forCellWithReuseIdentifier:BSCTopNewsCellReuseIdentifier];
}

Edit3: The crash only seems to occur in special occasions.
If the app was in the background, but still in memory and the user opens it up again. It then checks our API for new data, and if it found something will load them and reload the whole outer collectionView. Thats when the crash occurs.

If the CollectionView is reloaded while the app is running without being in the background in the beginning everything is fine.

To make the setup a bit more clear.


问:
Need to include a variable in a function of a query in Laravel
I have something like this:

```<code>$configurations = Configs:all();

foreach($configs as $config){

$documents = document::whereHas('user', function ($q) {
$q->where("portal_id", $config->id),})->get()

...
}
</code>```

This does not work because $config is not defined in the query function.

How do I put the $config->id object there?

答:
You can extend the scope of variable with use()

```<code> $documents = document::whereHas('user', function ($q) use($config->id) {
    $q->where("portal_id", $config->id),})->get()

    ...
    }
</code>```

Body:
I have something like this:

$configurations = Configs:all();

foreach($configs as $config){

$documents = document::whereHas('user', function ($q) {
$q->where("portal_id", $config->id),})->get()

...
}

This does not work because $config is not defined in the query function.

How do I put the $config->id object there?

Body:
You can extend the scope of variable with use()

 $documents = document::whereHas('user', function ($q) use($config->id) {
    $q->where("portal_id", $config->id),})->get()

    ...
    }


问:
Microsoft Excel Macro to run Java program
I have learnt to read and write an Excel file using a Java program with the help of Jxl and POI API. Is it possible to run a Java program with the help of macros? </p>

答:
i've used it.. Attention, use javaw otherwise a black window is popping up</p>

```<code>Dim result As String
Dim commandstr As String

commandstr = "javaw -jar somejar someparameter"

' try with or without cast to string
result = CStr( shellRun(commandstr) )

'somewhere from SO but forget.. sorry for missing credits

Public Function ShellRun(sCmd As String) As String

    'Run a shell command, returning the output as a string'

    Dim oShell As Object
    Set oShell = CreateObject("WScript.Shell")

    'run command'
    Dim oExec As Object
    Dim oOutput As Object
    Set oExec = oShell.exec(sCmd)
    Set oOutput = oExec.StdOut

    'handle the results as they are written to and read from the StdOut object'
    Dim s As String
    Dim sLine As String
    While Not oOutput.AtEndOfStream
        sLine = oOutput.ReadLine
        If sLine <> "" Then s = s & sLine & vbCrLf
    Wend

    ShellRun = s

End Function
</code>```

Body:
i've used it.. Attention, use javaw otherwise a black window is popping up

Dim result As String
Dim commandstr As String

commandstr = "javaw -jar somejar someparameter"

' try with or without cast to string
result = CStr( shellRun(commandstr) )

'somewhere from SO but forget.. sorry for missing credits

Public Function ShellRun(sCmd As String) As String

    'Run a shell command, returning the output as a string'

    Dim oShell As Object
    Set oShell = CreateObject("WScript.Shell")

    'run command'
    Dim oExec As Object
    Dim oOutput As Object
    Set oExec = oShell.exec(sCmd)
    Set oOutput = oExec.StdOut

    'handle the results as they are written to and read from the StdOut object'
    Dim s As String
    Dim sLine As String
    While Not oOutput.AtEndOfStream
        sLine = oOutput.ReadLine
        If sLine <> "" Then s = s & sLine & vbCrLf
    Wend

    ShellRun = s

End Function


答:
You can do this as shown below</p>

```<code>INSERT INTO newTable (col1, col2, col3, DATE_Field)
SELECT column1, column2, column3, GETDATE()
FROM oldTable
</code>```

Body:
You can do this as shown below

INSERT INTO newTable (col1, col2, col3, DATE_Field)
SELECT column1, column2, column3, GETDATE()
FROM oldTable


问:
Return value instead of a promise [to stop nested deferred promise]
I've a bunch of functions which are nested due to top level function is a ajax request.
So i want to return a value instead of a promise in nested child function.

Parent

```<code>let getUserPermissions = function(id) {
      let deferred = $q.defer();
      let promise = accessRequestService.getPermissions(id);
      promise.then(function(data) {
        deferred.resolve(data);
      }, function(err) {
        deferred.reject(err);
      })
      return deferred.promise;
    }
</code>```

Child 1

```<code>$rootScope.userInit = function() {
        return getUserPermissions(vzid)
          .then(function(data) {

            //Some code here

            return data;
          })

    }
</code>```

Child 2

```<code>let checkAuthorize = function(toState) {
  return $rootScope.userInit().then(
    function(data) {
//some code here
      return data;
    });
}
</code>```

Level 3

```<code>checkAuthorize(toState).then( function(val){
 $rootScope.isAuthorized = val;
  if ($rootScope.isAuthorized == true) {
        $log.info('is Authorized')
      } else {
        $log.info('is not Authorized');
        throw new AuthorizationError()
      }
  })
</code>```

At Level 3 we are still working with a promise. Can child 2 return a value instead of promise.

Expectation @ Level 3

```<code>$rootScope.isAuthorized = checkAuthorize(toState);

  if ($rootScope.isAuthorized == true) {
      $log.info('is Authorized')
      } else {
      $log.info('is not Authorized');
      throw new AuthorizationError()
     }
</code>```

答:
I'm using $state.transitionTo Method to be called before $stateChangeStart.

```<code>var transitionTo = $state.transitionTo;
$state.transitionTo = function(to, toParams, options) {
  var from = $state.$current,
    fromParams = $state.params;

  to = to.name ? to : $state.get(to);

    $rootScope.state = {
      to: to.self,
      toParams: toParams,
      from: from.self,
      fromParams: fromParams,
      options: options
    }

  if (options.notify && options.notify !== false) {
    return $q.reject(new AuthorizationError('Rejecting $state.transitionTo', 'Transition Rejected'));
  } else {
    return checkAuthorize(to).then(function(auth) {
      $rootScope.isAuthorized = auth;
        return transitionTo(to, toParams, options)
    })
  }
}
</code>```

StateChangeStart

```<code>$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
  $log.info("Route change start from", fromState.url, "to", toState.url);
  //event.preventDefault();

  if ($rootScope.isAuthorized == true) {
    $log.info('is Authorized')
    //$state.go($rootScope.toState.name);
  } else {
    event.preventDefault();
    $log.info('is not Authorized');
    throw new AuthorizationError('User is not Authorized.', 'NOT_AUTHENTICATED')
  }

});
</code>```

Body:
I've a bunch of functions which are nested due to top level function is a ajax request.
So i want to return a value instead of a promise in nested child function.

Parent

let getUserPermissions = function(id) {
      let deferred = $q.defer();
      let promise = accessRequestService.getPermissions(id);
      promise.then(function(data) {
        deferred.resolve(data);
      }, function(err) {
        deferred.reject(err);
      })
      return deferred.promise;
    }

Child 1

$rootScope.userInit = function() {
        return getUserPermissions(vzid)
          .then(function(data) {

            //Some code here

            return data;
          })

    }

Child 2

let checkAuthorize = function(toState) {
  return $rootScope.userInit().then(
    function(data) {
//some code here
      return data;
    });
}

Level 3

checkAuthorize(toState).then( function(val){
 $rootScope.isAuthorized = val;
  if ($rootScope.isAuthorized == true) {
        $log.info('is Authorized')
      } else {
        $log.info('is not Authorized');
        throw new AuthorizationError()
      }
  })

At Level 3 we are still working with a promise. Can child 2 return a value instead of promise.

Expectation @ Level 3

$rootScope.isAuthorized = checkAuthorize(toState);

  if ($rootScope.isAuthorized == true) {
      $log.info('is Authorized')
      } else {
      $log.info('is not Authorized');
      throw new AuthorizationError()
     }

Body:
I'm using $state.transitionTo Method to be called before $stateChangeStart.

var transitionTo = $state.transitionTo;
$state.transitionTo = function(to, toParams, options) {
  var from = $state.$current,
    fromParams = $state.params;

  to = to.name ? to : $state.get(to);

    $rootScope.state = {
      to: to.self,
      toParams: toParams,
      from: from.self,
      fromParams: fromParams,
      options: options
    }

  if (options.notify && options.notify !== false) {
    return $q.reject(new AuthorizationError('Rejecting $state.transitionTo', 'Transition Rejected'));
  } else {
    return checkAuthorize(to).then(function(auth) {
      $rootScope.isAuthorized = auth;
        return transitionTo(to, toParams, options)
    })
  }
}

StateChangeStart

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
  $log.info("Route change start from", fromState.url, "to", toState.url);
  //event.preventDefault();

  if ($rootScope.isAuthorized == true) {
    $log.info('is Authorized')
    //$state.go($rootScope.toState.name);
  } else {
    event.preventDefault();
    $log.info('is not Authorized');
    throw new AuthorizationError('User is not Authorized.', 'NOT_AUTHENTICATED')
  }

});


问:
API call every day at a specific time in java?
I want to create a scheduler in java which makes an API calls every day at a specific time and saves the content in a text file. One option would be to do something like this. https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/. But then is there any other way to do that in java? I am looking for the most efficient approach. Any suggestions.</p>

```<code>@Component
    class WelcomeService {

        public String retrieveWelcomeMessage() {
            //Complex Method
             String msgType="Hello World";
             RestTemplate restTemplate = new RestTemplate();
           String consumeJSONString = restTemplate.getForObject("https://ubasocials.ubagroup.com/geo-locationservice/odata/ATMs", String.class);
           writetexttofile(consumeJSONString);

          /* Gson gson = new GsonBuilder().create();
            Quote r = gson.fromJson(consumeJSONString, Quote.class);
            msgType=r.getValue().getQuote();*/
            return msgType;
        }
}
</code>```

答:
Have a look at ScheduledExecutorService

Make your WelcomeService runnable, then pass it into an instance of the ScheduledExecutorService.

```<code>private final ScheduledExecutorService sheduledExecutorService = Executors.newScheduledThreadPool(1);
sheduledExecutorService.scheduleAtFixedRate(runnableWelcomeService, 0, 1, TimeUnit.DAYS);
</code>```

Body:
I want to create a scheduler in java which makes an API calls every day at a specific time and saves the content in a text file. One option would be to do something like this. https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/. But then is there any other way to do that in java? I am looking for the most efficient approach. Any suggestions.

@Component
    class WelcomeService {

        public String retrieveWelcomeMessage() {
            //Complex Method
             String msgType="Hello World";
             RestTemplate restTemplate = new RestTemplate();
           String consumeJSONString = restTemplate.getForObject("https://ubasocials.ubagroup.com/geo-locationservice/odata/ATMs", String.class);
           writetexttofile(consumeJSONString);

          /* Gson gson = new GsonBuilder().create();
            Quote r = gson.fromJson(consumeJSONString, Quote.class);
            msgType=r.getValue().getQuote();*/
            return msgType;
        }
}

Body:
Have a look at ScheduledExecutorService

Make your WelcomeService runnable, then pass it into an instance of the ScheduledExecutorService.

private final ScheduledExecutorService sheduledExecutorService = Executors.newScheduledThreadPool(1);
sheduledExecutorService.scheduleAtFixedRate(runnableWelcomeService, 0, 1, TimeUnit.DAYS);


问:
How can I reference a variable in a variable? (powershell)
My subject is probably not worded correctly.

I am working on some scripts and using the "Send-MailMessage" command. I need to have some variables in the body of the message.... How can I do this? These variables are directories, log file locations, IP addresses, etc from the script. When the script finishes or fails I need to send an email with pertinent info about the job..

$bod = "this is message please see log file at $logfilelocation"

Send-MailMessage -To user@user.com -Subject subject -From user@user.com -body $bod -SmtpServer server

答:
You've already got the right idea.  You just need to build up your $bod string using the variables.  A 'here' string would probably work well.  Something like:

```<code>$bod=@"
directory: $directory
log file location: $logfileLocation
ip address: $ipAddress
"@
</code>```

Or are you asking how to get those values into variables?

Body:
You've already got the right idea.  You just need to build up your $bod string using the variables.  A 'here' string would probably work well.  Something like:

$bod=@"
directory: $directory
log file location: $logfileLocation
ip address: $ipAddress
"@

Or are you asking how to get those values into variables?


问:
How to avoid this bogus "dirname() expects exactly 1 parameter" warning?
On PHP V5.6.13,

```<code>dirname("",1);
</code>```

gives

```<code>Warning: dirname() expects exactly 1 parameter, 2 given
</code>```

despite http://php.net/manual/en/function.dirname.php

```<code>string dirname ( string $path [, int $levels = 1 ] )
</code>```

How can I avoid this bogus warning appearing?

答:
If you don't have PHP 7, use the function below to have a recursive dirname with levels:</p>

```<code>function dirname_r($path, $count=1){
    if ($count > 1){
       return dirname(dirname_r($path, --$count));
    }else{
       return dirname($path);
    }
}
echo dirname_r(__FILE__, 2);
</code>```

Body:
On PHP V5.6.13,

dirname("",1);

gives

Warning: dirname() expects exactly 1 parameter, 2 given

despite http://php.net/manual/en/function.dirname.php

string dirname ( string $path [, int $levels = 1 ] )

How can I avoid this bogus warning appearing?

Body:
If you don't have PHP 7, use the function below to have a recursive dirname with levels:

function dirname_r($path, $count=1){
    if ($count > 1){
       return dirname(dirname_r($path, --$count));
    }else{
       return dirname($path);
    }
}
echo dirname_r(__FILE__, 2);


问:
How to change theme background color and text color on selection
Is there any way to change the style of the web page on by user selection using CSS in angular js.

I tried in google but nothing is working for me.

I have a CSS file which will have style. I need to rewrite the style in all divs wherever needed by changing the background colour, text colour, font style.

```<code>    $scope.model.webPageSkin = 'Default';

    // create the list of themes
    $scope.bootstraps = [
        { name: 'Plain', url: 'Plain' },
        { name: 'Blue', url: 'Blue' },
        { name: 'Green', url: 'Green' } ,
        { name: 'Default', url: 'default' } ,
    ];

**Plain.css**

ChangeColor
{
    font-family: "Source Sans Pro",Calibri,Candara,Arial,sans-serif;
    font-size: 15px;
    line-height: 1.42857143;
    color: #333333;
    background-color: #ddd;
}

**default.css**

.ChangeColor
{
    font-family: "Source Sans Pro",Calibri,Candara,Arial,sans-serif;
    font-size: 15px;
    line-height: 1.42857143;
    color: #333333;
    background-color: #3c8dbc;
}

<div class="wrapper>
     <header class="main-header">
          <nav class="navbar navbar-static-top" ng-class="{ChangeColor:
           model.webPageSkin !important;}">
          </nav>
     </header>

<div class="row">
<select  ng-model="model.webPageSkin" ng-options="bootstrap.url as bootstrap.name for bootstrap in bootstraps">
                </select>
</div>
</div>
</code>```

Can anyone suggest me how to do this.

答:
/*----Plain.css---*/

body{
 background-color:grey;
}

/*----Blue.css-----*/

body{
 background-color:blue;
}

/*------Default.css------*/

body{
 background-color:cyan;
}

/*-----Green.css----*/

body{
 background-color:green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!DOCTYPE html>
<html >
    <head>

        <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
        <script >
            var app=angular.module('mainApp',[]);
            app.controller('myctrl',function($scope){
                 $scope.webPageSkin="Default";
          console.log($scope.webPageSkin);

    $scope.bootstraps = [
        { name: 'Plain', url: 'Plain.css' },
        { name: 'Blue', url: 'Blue.css' },
        { name: 'Green', url: 'Green.css' } ,
        { name: 'Default', url: 'Default.css' } ,
    ];

            });
        </script>

    </head>
    <body ng-app="mainApp" ng-controller="myctrl">
        <div class="wrapper">

     <header class="main-header" ng-class="webPageSkin.name">
          <nav  class="navbar navbar-static-top">
          </nav>
     </header>

<div class="row">
<select ng-model="webPageSkin" ng-options="bootstrap.name for bootstrap in bootstraps" ng-init="webPageSkin = bootstraps[0]">
                </select>
</div>
</div>

<link rel="stylesheet" type="text/css" ng-href="{{webPageSkin.url}}">
    </body>
</html></code>```

Create four css file by the same name and also can edit as per the requirement.Now it is completed.

Body:
Is there any way to change the style of the web page on by user selection using CSS in angular js.

I tried in google but nothing is working for me.

I have a CSS file which will have style. I need to rewrite the style in all divs wherever needed by changing the background colour, text colour, font style.

    $scope.model.webPageSkin = 'Default';

    // create the list of themes
    $scope.bootstraps = [
        { name: 'Plain', url: 'Plain' },
        { name: 'Blue', url: 'Blue' },
        { name: 'Green', url: 'Green' } ,
        { name: 'Default', url: 'default' } ,
    ];

**Plain.css**

ChangeColor
{
    font-family: "Source Sans Pro",Calibri,Candara,Arial,sans-serif;
    font-size: 15px;
    line-height: 1.42857143;
    color: #333333;
    background-color: #ddd;
}

**default.css**

.ChangeColor
{
    font-family: "Source Sans Pro",Calibri,Candara,Arial,sans-serif;
    font-size: 15px;
    line-height: 1.42857143;
    color: #333333;
    background-color: #3c8dbc;
}

<select  ng-model="model.webPageSkin" ng-options="bootstrap.url as bootstrap.name for bootstrap in bootstraps">
                </select>

Can anyone suggest me how to do this.

Body:
/*----Plain.css---*/

body{
 background-color:grey;
}

/*----Blue.css-----*/

body{
 background-color:blue;
}

/*------Default.css------*/

body{
 background-color:cyan;
}

/*-----Green.css----*/

body{
 background-color:green;
}

 <!DOCTYPE html>
<html >
    <head>

        <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
        <script >
            var app=angular.module('mainApp',[]);
            app.controller('myctrl',function($scope){
                 $scope.webPageSkin="Default";
          console.log($scope.webPageSkin);

    $scope.bootstraps = [
        { name: 'Plain', url: 'Plain.css' },
        { name: 'Blue', url: 'Blue.css' },
        { name: 'Green', url: 'Green.css' } ,
        { name: 'Default', url: 'Default.css' } ,
    ];

            });
        </script>

    </head>
    <body ng-app="mainApp" ng-controller="myctrl">
        <div class="wrapper">

     <header class="main-header" ng-class="webPageSkin.name">
          <nav  class="navbar navbar-static-top">
          </nav>
     </header>

<div class="row">
<select ng-model="webPageSkin" ng-options="bootstrap.name for bootstrap in bootstraps" ng-init="webPageSkin = bootstraps[0]">
                </select>
</div>
</div>

<link rel="stylesheet" type="text/css" ng-href="{{webPageSkin.url}}">
    </body>
</html>

Create four css file by the same name and also can edit as per the requirement.Now it is completed.


答:
If you dont want to use any frameworks like spring. You can use windows task scheduler to schedule your java code. <p>
Step1: Package your java code as a runnable jar.<p>
Step2: Create a batch file that runs the jar.<p>
Step3: Use batch file in windows tash scheduler.</p>

Title: API call every day at a specific time in java?

Body:
If you dont want to use any frameworks like spring. You can use windows task scheduler to schedule your java code.

Step1: Package your java code as a runnable jar.

Step2: Create a batch file that runs the jar.

Step3: Use batch file in windows tash scheduler.


问:
how to take all tweets in a hashtag with tweepy?
I'm trying to take every open tweets in a hashtag but my code does not go further than 299 tweets.

I also trying to take tweets from a specific time line like tweets only in May 2015 and July 2016. Are there any way to do it in the main process or should I write a little code for it?

Here is my code:

```<code># if this is the first time, creates a new array which
# will store max id of the tweets for each keyword
if not os.path.isfile("max_ids.npy"):
    max_ids = np.empty(len(keywords))
    # every value is initialized as -1 in order to start from the beginning the first time program run
    max_ids.fill(-1)
else:
    max_ids = np.load("max_ids.npy")  # loads the previous max ids

# if there is any new keywords added, extends the max_ids array in order to correspond every keyword
if len(keywords) > len(max_ids):
    new_indexes = np.empty(len(keywords) - len(max_ids))
    new_indexes.fill(-1)
    max_ids = np.append(arr=max_ids, values=new_indexes)

count = 0
for i in range(len(keywords)):
    since_date="2015-01-01"
    sinceId = None
    tweetCount = 0
    maxTweets = 5000000000000000000000  # maximum tweets to find per keyword
    tweetsPerQry = 100
    searchQuery = "#{0}".format(keywords[i])
    while tweetCount < maxTweets:
        if max_ids[i] < 0:
                if (not sinceId):
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry)
                else:
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            since_id=sinceId)
        else:
                if (not sinceId):
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            max_id=str(max_ids - 1))
                else:
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            max_id=str(max_ids - 1),
                                            since_id=sinceId)
        if not new_tweets:
            print("Keyword: {0}      No more tweets found".format(searchQuery))
            break
        for tweet in new_tweets:
            count += 1
            print(count)

            file_write.write(
                       .
                       .
                       .
                         )

            item = {
                .
                .
                .
                .
                .
            }

            # instead of using mongo's id for _id, using tweet's id
            raw_data = tweet._json
            raw_data["_id"] = tweet.id
            raw_data.pop("id", None)

            try:
                db["Tweets"].insert_one(item)
            except pymongo.errors.DuplicateKeyError as e:
                print("Already exists in 'Tweets' collection.")
            try:
                db["RawTweets"].insert_one(raw_data)
            except pymongo.errors.DuplicateKeyError as e:
                print("Already exists in 'RawTweets' collection.")

        tweetCount += len(new_tweets)
        print("Downloaded {0} tweets".format(tweetCount))
        max_ids[i] = new_tweets[-1].id

np.save(arr=max_ids, file="max_ids.npy")  # saving in order to continue mining from where left next time program run
</code>```

答:
Sorry, I can't answer in comment, too long. :)

Sure :) Check this example:
Advanced searched for #data keyword 2015 may - 2016 july
Got this url: https://twitter.com/search?l=&q=%23data%20since%3A2015-05-01%20until%3A2016-07-31&src=typd

```<code>session = requests.session()
keyword = 'data'
date1 = '2015-05-01'
date2 = '2016-07-31'
session.get('https://twitter.com/search?l=&q=%23+keyword+%20since%3A+date1+%20until%3A+date2&src=typd', streaming = True)
</code>```

Now we have all the requested tweets,
Probably you could have problems with 'pagination'
Pagination url ->

https://twitter.com/i/search/timeline?vertical=news&q=%23data%20since%3A2015-05-01%20until%3A2016-07-31&src=typd&include_available_features=1&include_entities=1&max_position=TWEET-759522481271078912-759538448860581892-BD1UO2FFu9QAAAAAAAAETAAAAAcAAAASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&reset_error_state=false

Probably you could put a random tweet id, or you can parse first, or requests some data from twitter. It can be done.

Use Chrome's networking tab to find all the requested information :)

Body:
I'm trying to take every open tweets in a hashtag but my code does not go further than 299 tweets.

I also trying to take tweets from a specific time line like tweets only in May 2015 and July 2016. Are there any way to do it in the main process or should I write a little code for it?

Here is my code:

# if this is the first time, creates a new array which
# will store max id of the tweets for each keyword
if not os.path.isfile("max_ids.npy"):
    max_ids = np.empty(len(keywords))
    # every value is initialized as -1 in order to start from the beginning the first time program run
    max_ids.fill(-1)
else:
    max_ids = np.load("max_ids.npy")  # loads the previous max ids

# if there is any new keywords added, extends the max_ids array in order to correspond every keyword
if len(keywords) > len(max_ids):
    new_indexes = np.empty(len(keywords) - len(max_ids))
    new_indexes.fill(-1)
    max_ids = np.append(arr=max_ids, values=new_indexes)

count = 0
for i in range(len(keywords)):
    since_date="2015-01-01"
    sinceId = None
    tweetCount = 0
    maxTweets = 5000000000000000000000  # maximum tweets to find per keyword
    tweetsPerQry = 100
    searchQuery = "#{0}".format(keywords[i])
    while tweetCount < maxTweets:
        if max_ids[i] < 0:
                if (not sinceId):
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry)
                else:
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            since_id=sinceId)
        else:
                if (not sinceId):
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            max_id=str(max_ids - 1))
                else:
                    new_tweets = api.search(q=searchQuery, count=tweetsPerQry,
                                            max_id=str(max_ids - 1),
                                            since_id=sinceId)
        if not new_tweets:
            print("Keyword: {0}      No more tweets found".format(searchQuery))
            break
        for tweet in new_tweets:
            count += 1
            print(count)

            file_write.write(
                       .
                       .
                       .
                         )

            item = {
                .
                .
                .
                .
                .
            }

            # instead of using mongo's id for _id, using tweet's id
            raw_data = tweet._json
            raw_data["_id"] = tweet.id
            raw_data.pop("id", None)

            try:
                db["Tweets"].insert_one(item)
            except pymongo.errors.DuplicateKeyError as e:
                print("Already exists in 'Tweets' collection.")
            try:
                db["RawTweets"].insert_one(raw_data)
            except pymongo.errors.DuplicateKeyError as e:
                print("Already exists in 'RawTweets' collection.")

        tweetCount += len(new_tweets)
        print("Downloaded {0} tweets".format(tweetCount))
        max_ids[i] = new_tweets[-1].id

np.save(arr=max_ids, file="max_ids.npy")  # saving in order to continue mining from where left next time program run

Body:
Sorry, I can't answer in comment, too long. :)

Sure :) Check this example:
Advanced searched for #data keyword 2015 may - 2016 july
Got this url: https://twitter.com/search?l=&q=%23data%20since%3A2015-05-01%20until%3A2016-07-31&src=typd

session = requests.session()
keyword = 'data'
date1 = '2015-05-01'
date2 = '2016-07-31'
session.get('https://twitter.com/search?l=&q=%23+keyword+%20since%3A+date1+%20until%3A+date2&src=typd', streaming = True)

Now we have all the requested tweets,
Probably you could have problems with 'pagination'
Pagination url ->

<a href="https://twitter.com/i/search/timeline?vertical=news&q=%23data%20since%3A2015-05-01%20until%3A2016-07-31&src=typd&include_available_features=1&include_entities=1&max_position=TWEET-759522481271078912-759538448860581892-BD1UO2FFu9QAAAAAAAAETAAAAAcAAAASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&reset_error_state=false" rel="nofollow noreferrer">https://twitter.com/i/search/timeline?vertical=news&q=%23data%20since%3A2015-05-01%20until%3A2016-07-31&src=typd&include_available_features=1&include_entities=1&max_position=TWEET-759522481271078912-759538448860581892-BD1UO2FFu9QAAAAAAAAETAAAAAcAAAASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&reset_error_state=false

Probably you could put a random tweet id, or you can parse first, or requests some data from twitter. It can be done.

Use Chrome's networking tab to find all the requested information :)

ContentLicense: CC BY-SA 4.0


问:
Convert an ArrayMap to ArrayList - Kotlin
I have an ArrayMap and I want a list of Chat to create and recyclerview.

```<code>val chats : ArrayMap<String,Chat>? = ArrayMap()
</code>```

RecyclerView.Adapter

```<code>class ChatAdapter(var chats : ArrayList<Chat>){
   .
   .
   .
}
</code>```

I get this ArrayMap from firebase. What is the best way to get an ArrayList?

答:
If you don't need an ArrayList explicitly, you can use the ArrayMap.map() function like this:

```<code>val chats : ArrayMap<String,Chat>? = ArrayMap()
val list : List<Chat> = chats.map { it.value }
</code>```

Body:
I have an ArrayMap and I want a list of Chat to create and recyclerview.

val chats : ArrayMap<String,Chat>? = ArrayMap()

RecyclerView.Adapter

class ChatAdapter(var chats : ArrayList<Chat>){
   .
   .
   .
}

I get this ArrayMap from firebase. What is the best way to get an ArrayList?

Body:
If you don't need an ArrayList explicitly, you can use the ArrayMap.map() function like this:

val chats : ArrayMap<String,Chat>? = ArrayMap()
val list : List<Chat> = chats.map { it.value }


问:
Caret: undefined columns selected
I have been trying to get the below code to run in caret but get the error. Can anyone tell me how to trouble shoot it.

Error in [.data.frame(data, , lvls[1]) : undefined columns selected

```<code>library(tidyverse)
library(caret)

mydf <- iris

mydf <- mydf %>%
  mutate(tgt = as.factor(ifelse(Species == 'setosa','Y','N'))) %>%
  select(everything(), -Species)

trainIndex <- createDataPartition(mydf$tgt, p = 0.75, times = 1, list = FALSE)
train <- mydf[trainIndex,]
test <- mydf[-trainIndex,]

fitControl <- trainControl(method = 'repeatedcv',
                       number = 10,
                       repeats = 10,
                       allowParallel = TRUE,
                       summaryFunction = twoClassSummary)

fit_log <- train(tgt~.,
             data = train,
             method = "glm",
             trControl = fitControl,
             family = "binomial")
</code>```

答: You need to used classProbs = TRUE in your control function. The ROC curve is based on the class probabilities and the error is the summary function not finding those columns.

Title: Caret: undefined columns selected

Body:
I have been trying to get the below code to run in caret but get the error. Can anyone tell me how to trouble shoot it.

Error in [.data.frame(data, , lvls[1]) : undefined columns selected

library(tidyverse)
library(caret)

mydf <- iris

mydf <- mydf %>%
  mutate(tgt = as.factor(ifelse(Species == 'setosa','Y','N'))) %>%
  select(everything(), -Species)

trainIndex <- createDataPartition(mydf$tgt, p = 0.75, times = 1, list = FALSE)
train <- mydf[trainIndex,]
test <- mydf[-trainIndex,]

fitControl <- trainControl(method = 'repeatedcv',
                       number = 10,
                       repeats = 10,
                       allowParallel = TRUE,
                       summaryFunction = twoClassSummary)

fit_log <- train(tgt~.,
             data = train,
             method = "glm",
             trControl = fitControl,
             family = "binomial")


问:
How to get next cucumber step after passed if it is failed
I have AfterStep hook which can give me a step name. But it gives only name of passed step.

```<code>AfterStep do |result, step|
  puts step.name
end
</code>```

How to get next cucumber step after passed if next is failed?
Or how to get name of failed step?

Maybe somehow to calculate step position and take another one?

Any ideas?
I am sure that it is possible because we can see failed step name in error log.

答:
The reason AfterStep is not called at all is simple: it is treated as a simple step and is just appended to the list of steps. Hence, as soon as any of steps fails, scenario is stopped and AfterStep never gets called. I would consider it being a bug in cucumber-ruby.

As a workaround, one might use After hook:

```<code>After do |scenario|
  if scenario.failed?
    puts "Failed: " << scenario.marshal_dump[2].first.source.inspect
  end
end
</code>```

Body:
I have AfterStep hook which can give me a step name. But it gives only name of passed step.

AfterStep do |result, step|
  puts step.name
end

How to get next cucumber step after passed if next is failed?
Or how to get name of failed step?

Maybe somehow to calculate step position and take another one?

Any ideas?
I am sure that it is possible because we can see failed step name in error log.

Body:
The reason AfterStep is not called at all is simple: it is treated as a simple step and is just appended to the list of steps. Hence, as soon as any of steps fails, scenario is stopped and AfterStep never gets called. I would consider it being a bug in cucumber-ruby.

As a workaround, one might use After hook:

After do |scenario|
  if scenario.failed?
    puts "Failed: " << scenario.marshal_dump[2].first.source.inspect
  end
end


问:
Tomcat sessions expiring unexpectedly
We are running tomcat application server that handle over 100 concurrent sessions.
In the last 2 months the most active users noticed that sometimes they are getting kicked off from the system.

As I understood from the log tomcat sessions are getting expired without any reason.

I see no problems from the web application side.
Is there any problem from the tomcat side?

Tomcat 6.0.18.

答:
I have seen similar problems when the following prerequisites exist:

multiple instances of the tomcat app are installed across multiple JVMs

load balancing (between the web server and the Tomcat JVMs) is not configured correctly.

Tomcat's session replication feature is not enabled

Due to the incorrect load balancing config, the web server may randomly decide to break session affinity and send an incoming request to a Tomcat JVM that has never seen the session before.  The Tomcat JVM will issue a new session and the user will lose all of their previouS session data and effectively start over.

Title: Tomcat sessions expiring unexpectedly


答:
If the table definition of source_table and dest_table are the same except for the extra TimeStamp column, you could do this:

```<code>INSERT INTO dest_table
SELECT *,MONTH(GETDATE())
FROM source_table
</code>```

Otherwise, you need to specify the mapping relation, for example:

```<code>INSERT INTO dest_table (col1,col2...,Date_Column)
SELECT col3,col4...,MONTH(GETDATE())
FROM source_table
</code>```

Body:
I need to insert (a monthly backup I'll be restoring into my source_database) into the dest_database, and add a new DATE field which would state which month is the data from. So in the end everything will be in the dest_database with the DATE field specifying to which month it belongs.

What'd I need to do?

INSERT INTO dest_table
(SELECT *
FROM source_table)

Body:
If the table definition of source_table and dest_table are the same except for the extra TimeStamp column, you could do this:

INSERT INTO dest_table
SELECT *,MONTH(GETDATE())
FROM source_table

Otherwise, you need to specify the mapping relation, for example:

INSERT INTO dest_table (col1,col2...,Date_Column)
SELECT col3,col4...,MONTH(GETDATE())
FROM source_table


问:
How do i filter an array inside of a array of objects?
I'm trying to filter a list by tags:

```<code>const initialState = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'outdoor']},
     {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'camping', 'snow']},
     {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
   ]
</code>```

I can filter the list by name using map and filter, my problem is when i try to list the products by tags. Do i have to use foreach inside of my products filter? There's another way of doing it?

答:
Like that?</p>

```<code>const filter = 'nature';
const filteredResult = initialState.filter((item) => {
    return (item.tags.indexOf(filter) >= 0);
});
</code>```

Body:
I'm trying to filter a list by tags:

const initialState = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'outdoor']},
     {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'camping', 'snow']},
     {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
   ]

I can filter the list by name using map and filter, my problem is when i try to list the products by tags. Do i have to use foreach inside of my products filter? There's another way of doing it?

Body:
Like that?

const filter = 'nature';
const filteredResult = initialState.filter((item) => {
    return (item.tags.indexOf(filter) >= 0);
});