问:
Saving vbscript output as ansi error
I'm trying to save the output text file from this vbscript as ANSI instead of Unicode.

This is the simplified script:

```<code>Option Explicit

dim fso, obs, fol, spl, files, objFile, arr, file, ext, ex
Set fso = CreateObject("scripting.filesystemobject")
Set obs = CreateObject("shell.application")
Set fol = fso.GetFolder(".")
Set spl = obs.NameSpace(fol.Path)
Set files = fol.Files
set objFile = fso.openTextFile("test.txt" ,2 , true, false)
arr = Array("mp4")

For Each file In files
    ext = fso.GetExtensionName(file.Name)
    For Each ex In arr
        If StrComp(ext,ex,1)=0 Then
            objFile.writeline fol.Path & "\" & spl.GetDetailsOf(spl.ParseName(file.Name),0) & vbcrlf & spl.GetDetailsOf(spl.ParseName(file.Name),27) & vbcrlf & spl.GetDetailsOf(spl.ParseName(file.Name),28)
        End If
    Next
Next
objFile.Close
</code>```

If I change:

```<code>set objFile = fso.openTextFile("test.txt" ,2 , true, false)
</code>```

To:

```<code>set objFile = fso.openTextFile("test.txt" ,2 , true, true)
</code>```

the script works, but saves the output as Unicode. If I keep the false the script gives me Invalid procedure call or argument.
This is the part that is causing the error:

```<code>spl.GetDetailsOf(spl.ParseName(file.Name),28)
</code>```

I have tried loads of other extended properties and they all work fine as ANSI. It just seems to be this one that is giving me problems. I have tried loads of different files and the result is the same. I don't know enough to fix this unfortunately, so I would be very greatful for any help.

答:
The probable reason for your problem is explained here. The 28/Bitrate detail/property may contain a Left-To-Right-Mark. The remedy is to .WriteLine Mid(spl.GetDetailsOf(spl.ParseName(file.Name),28), 2) to the file.

Of course, if other data contain non-ANSI characters, you need to sanitize it accordingly.

Title: Saving vbscript output as ansi error

Body:
I'm trying to save the output text file from this vbscript as ANSI instead of Unicode.

This is the simplified script:

Option Explicit

dim fso, obs, fol, spl, files, objFile, arr, file, ext, ex
Set fso = CreateObject("scripting.filesystemobject")
Set obs = CreateObject("shell.application")
Set fol = fso.GetFolder(".")
Set spl = obs.NameSpace(fol.Path)
Set files = fol.Files
set objFile = fso.openTextFile("test.txt" ,2 , true, false)
arr = Array("mp4")

For Each file In files
    ext = fso.GetExtensionName(file.Name)
    For Each ex In arr
        If StrComp(ext,ex,1)=0 Then
            objFile.writeline fol.Path & "\" & spl.GetDetailsOf(spl.ParseName(file.Name),0) & vbcrlf & spl.GetDetailsOf(spl.ParseName(file.Name),27) & vbcrlf & spl.GetDetailsOf(spl.ParseName(file.Name),28)
        End If
    Next
Next
objFile.Close

If I change:

set objFile = fso.openTextFile("test.txt" ,2 , true, false)

To:

set objFile = fso.openTextFile("test.txt" ,2 , true, true)

the script works, but saves the output as Unicode. If I keep the false the script gives me Invalid procedure call or argument.
This is the part that is causing the error:

spl.GetDetailsOf(spl.ParseName(file.Name),28)

I have tried loads of other extended properties and they all work fine as ANSI. It just seems to be this one that is giving me problems. I have tried loads of different files and the result is the same. I don't know enough to fix this unfortunately, so I would be very greatful for any help.


来源: stackexchange

问:
How to add a value after being logged in?
I am working in an android studio project and I have a login activity,I created database using SharedPreferences and SQLite;I have created a table which has columns id,email,password,check_in,check_out.

I made it possible to login after I register a user;but I do not know how to insert a data in check_in cell of logged user.

So my problem is that how to make possible to add the time of check_in in table in database after logged in?

And how I can the see the table created using SQLite?

答:
```<code>SQLiteDatabase db = this.getWritableDatabase();

ContentValues contentValues = new ContentValues();
contentValues.put("check_in", value);
contentValues.put("check_out", value);

// this will insert if record is new, update otherwise
db.insertWithOnConflict(TABLE, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
</code>```

ContentLicense: CC BY-SA 3.0


问:
How to use différents JS functions at the exact same time
I wish to launch multiples functions at the same time when clicking in a button.

The thing is sensitive since that's launch timers, and if they aren't synchronised the little difference is immediatly visible ...

Actually I use this code :

```<code><button class="btn btn-success startTimer" id="gobutton">Start</button>

    <script type="text/javascript">
        $(".startTimer").click(function() {
            var timeseconds = $("#MoneyTimer").TimeCircles().getTime();
            $("#timeseconds").val(timeseconds);
            $("#MoneyTimer").TimeCircles().start();
            $('#totaleuro.compteur1').timer1('start');
            $('#totaleuro.compteur2').timer2('start');
        });
    </script>
</code>```

答:
You can use setTimeout function. Its callback is executed asynchronously.</p>

```<code><script type="text/javascript">
    $(".startTimer").click(function() {
        var timeseconds = $("#MoneyTimer").TimeCircles().getTime();
        setTimeout(function() {$("#timeseconds").val(timeseconds);}, 0);
        setTimeout(function() {$('#totaleuro.compteur1').timer1('start');}, 0);
        setTimeout(function() {$('#totaleuro.compteur2').timer2('start');}, 0);
    });
</script>
</code>```

Body:
I wish to launch multiples functions at the same time when clicking in a button.

The thing is sensitive since that's launch timers, and if they aren't synchronised the little difference is immediatly visible ...

Actually I use this code :

<button class="btn btn-success startTimer" id="gobutton">Start</button>

Body:
You can use setTimeout function. Its callback is executed asynchronously.

<script type="text/javascript">
    $(".startTimer").click(function() {
        var timeseconds = $("#MoneyTimer").TimeCircles().getTime();
        setTimeout(function() {$("#timeseconds").val(timeseconds);}, 0);
        setTimeout(function() {$('#totaleuro.compteur1').timer1('start');}, 0);
        setTimeout(function() {$('#totaleuro.compteur2').timer2('start');}, 0);
    });
</script>


问:
How do you upload a chunked video to twitter using node
How would you upload a video to twitter using the POST media/upload (chunked) endpoint with node?</p>

答:
Please try this</p>
```<code>const splitFile = require('split-file')
const Twitter = require('twitter')
const fs = require('fs-extra')
const Promise = require('bluebird')

const pathToMovie = __dirname + '/test/152.mp4';
const mediaType = 'video/mp4' // `'video/mp4'` is also supported
let Names
const mediaSize = require('fs').statSync(pathToMovie).size
/* Twitter support Maximum  15MB video files. So we need to split this
file in to three files */
splitFile.splitFile(pathToMovie, 3)
.then((names) => {
  Names = names
  return init()
})
.catch((err) => {
console.log('Error: ', err)
})

const client = new Twitter({
  consumer_key: '<your consumer_key >',
  consumer_secret: '<your consumer_secret >',
  access_token_key: '<your access_token_key >',
  access_token_secret: '<access_token_secret>'
});

const init = () => {
  initTweetUpload(mediaSize, mediaType) // Declare that you wish to upload some media
  .then(appendTweetUpload) // Send the data for the media
  .then(appendTweetUpload) // Send the data for the media
  .then(appendTweetUpload) // Send the data for the media
  .then(finalizeTweetUpload) // Declare that you are done uploading chunks
 // eslint-disable-next-line promise/always-return
  .then((data) => {
    const status = {
      media_ids: data,
      status: 'NodeJS Media Upload',
  }

  client.post('statuses/update', status, (error, tweet, response) => {
    console.log(error)
    console.log(tweet)
  })
 }).catch((err) => {
  console.log('Error: ', err)
  })
 }

const initTweetUpload = (mediaSize, mediaType) => makePost('media/upload',
{
 command: 'INIT',
 total_bytes: mediaSize,
 media_type: mediaType,
}).then((data) => data.media_id_string)

let i = 0

const appendTweetUpload = (mediaId) => {
 const p = Names.shift()
 /* mediaData is the  raw binary file content being uploaded ,It must be
<= 5 MB */
const mediaData = fs.readFileSync(p)
return makePost('media/upload', {
  command: 'APPEND',
  media_id: mediaId,
  media: mediaData,
  segment_index: i++,
}).then((data) => mediaId)
}

const finalizeTweetUpload = (mediaId) => makePost('media/upload', {
command: 'FINALIZE',
media_id: mediaId,
}).then((data) => mediaId)

const makePost = (endpoint, params) =>
// params.media_category = 'tweet_video';
new Promise((resolve, reject) => {
client.post(endpoint, params, (error, data, response) => {
  if (error) {
    reject(error)
  } else {
    resolve(data)
  }
 })
 })

dependencies

 1. https://www.npmjs.com/package/twitter
 2. https://www.npmjs.com/package/split-file
</code>```

Body:
Please try this

const splitFile = require('split-file')
const Twitter = require('twitter')
const fs = require('fs-extra')
const Promise = require('bluebird')

const pathToMovie = __dirname + '/test/152.mp4';
const mediaType = 'video/mp4' // `'video/mp4'` is also supported
let Names
const mediaSize = require('fs').statSync(pathToMovie).size
/* Twitter support Maximum  15MB video files. So we need to split this
file in to three files */
splitFile.splitFile(pathToMovie, 3)
.then((names) => {
  Names = names
  return init()
})
.catch((err) => {
console.log('Error: ', err)
})

const client = new Twitter({
  consumer_key: '<your consumer_key >',
  consumer_secret: '<your consumer_secret >',
  access_token_key: '<your access_token_key >',
  access_token_secret: '<access_token_secret>'
});

const init = () => {
  initTweetUpload(mediaSize, mediaType) // Declare that you wish to upload some media
  .then(appendTweetUpload) // Send the data for the media
  .then(appendTweetUpload) // Send the data for the media
  .then(appendTweetUpload) // Send the data for the media
  .then(finalizeTweetUpload) // Declare that you are done uploading chunks
 // eslint-disable-next-line promise/always-return
  .then((data) => {
    const status = {
      media_ids: data,
      status: 'NodeJS Media Upload',
  }

  client.post('statuses/update', status, (error, tweet, response) => {
    console.log(error)
    console.log(tweet)
  })
 }).catch((err) => {
  console.log('Error: ', err)
  })
 }

const initTweetUpload = (mediaSize, mediaType) => makePost('media/upload',
{
 command: 'INIT',
 total_bytes: mediaSize,
 media_type: mediaType,
}).then((data) => data.media_id_string)

let i = 0

const appendTweetUpload = (mediaId) => {
 const p = Names.shift()
 /* mediaData is the  raw binary file content being uploaded ,It must be
<= 5 MB */
const mediaData = fs.readFileSync(p)
return makePost('media/upload', {
  command: 'APPEND',
  media_id: mediaId,
  media: mediaData,
  segment_index: i++,
}).then((data) => mediaId)
}

const finalizeTweetUpload = (mediaId) => makePost('media/upload', {
command: 'FINALIZE',
media_id: mediaId,
}).then((data) => mediaId)

const makePost = (endpoint, params) =>
// params.media_category = 'tweet_video';
new Promise((resolve, reject) => {
client.post(endpoint, params, (error, data, response) => {
  if (error) {
    reject(error)
  } else {
    resolve(data)
  }
 })
 })

dependencies

 1. https://www.npmjs.com/package/twitter
 2. https://www.npmjs.com/package/split-file

ContentLicense: CC BY-SA 4.0


问:
Cannot invoke initializer for type 'Double' with an argument list of type '(Range<Double>)'
i'm getting this error here (Cannot invoke initializer for type 'Double' with an argument list of type '(Range)') here

```<code>for dista in Double(0..<(car.distance)) //error here {

        }
</code>```

where "distance" is of type Double.
How can i solve it?

UPDATE

var distance: Double?  is in a custom class "Car". I have a function that download for me different cars

```<code>    if let carsDownloaded = response.cars {
                    var number = cars / (models?.count)!
                    number = number == 0 ? 1 : number

                    let distanceC = carsDownloaded

         for car in distanceC {
                        for dista in car.distance! {
   }
 }
</code>```

cars are the cars that i can download, response chose if i really can download those cars and in the end response.cars are the cars that i will download. Now i would like to order in a filter those cars from nearest to the fairest but my problem is that i take the distance value from my position to a X car with external functions

```<code>func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance {
        let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
        let to = CLLocation(latitude: to.latitude, longitude: to.longitude)

        return from.distance(from: to)

    }

    func didSelectt(car:Car) {

        guard let coordinates = car.location  else {
            return
        }
        self.destination = coordinates

        // update distance
        if currentLocation != nil {
            let dist = distance(from: currentLocation!, to: coordinates)
        }
    }
</code>```

答:
The type of the in parameter in a loop must be a range of Int. Besides you cannot convert a range to a single type like Double

To iterate over a sequence != Int you need stride

```<code>let distance = 25.0

for dista in stride(from:0.0, to: distance, by: 1.0) {
    print(dista)
}
</code>```

Body:
i'm getting this error here (Cannot invoke initializer for type 'Double' with an argument list of type '(Range)') here

for dista in Double(0..<(car.distance)) //error here {

        }

where "distance" is of type Double.
How can i solve it?

UPDATE

var distance: Double?  is in a custom class "Car". I have a function that download for me different cars

    if let carsDownloaded = response.cars {
                    var number = cars / (models?.count)!
                    number = number == 0 ? 1 : number

                    let distanceC = carsDownloaded

         for car in distanceC {
                        for dista in car.distance! {
   }
 }

cars are the cars that i can download, response chose if i really can download those cars and in the end response.cars are the cars that i will download. Now i would like to order in a filter those cars from nearest to the fairest but my problem is that i take the distance value from my position to a X car with external functions

func distance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> CLLocationDistance {
        let from = CLLocation(latitude: from.latitude, longitude: from.longitude)
        let to = CLLocation(latitude: to.latitude, longitude: to.longitude)

        return from.distance(from: to)

    }

    func didSelectt(car:Car) {

        guard let coordinates = car.location  else {
            return
        }
        self.destination = coordinates

        // update distance
        if currentLocation != nil {
            let dist = distance(from: currentLocation!, to: coordinates)
        }
    }

Body:
The type of the in parameter in a loop must be a range of Int. Besides you cannot convert a range to a single type like Double

To iterate over a sequence != Int you need stride

let distance = 25.0

for dista in stride(from:0.0, to: distance, by: 1.0) {
    print(dista)
}


问:
How to dynamically compose an OR query filter in Django?
From an example you can see a multiple OR query filter:

```<code>Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
</code>```

For example, this results in:

```<code>[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
</code>```

However, I want to create this query filter from a list. How to do that?

e.g. [1, 2, 3] -> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))

答:
Solution which use reduce and or_ operators to filter by multiply fields.

```<code>from functools import reduce
from operator import or_
from django.db.models import Q

filters = {'field1': [1, 2], 'field2': ['value', 'other_value']}

qs = Article.objects.filter(
   reduce(or_, (Q(**{f'{k}__in': v}) for k, v in filters.items()))
)
</code>```

p.s. f is a new format strings literal. It was introduced in python 3.6

Body:
From an example you can see a multiple OR query filter:

Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))

For example, this results in:

[
,
,
]

However, I want to create this query filter from a list. How to do that?

e.g. [1, 2, 3] -> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))

Body:
Solution which use reduce and or_ operators to filter by multiply fields.

from functools import reduce
from operator import or_
from django.db.models import Q

filters = {'field1': [1, 2], 'field2': ['value', 'other_value']}

qs = Article.objects.filter(
   reduce(or_, (Q(**{f'{k}__in': v}) for k, v in filters.items()))
)

p.s. f is a new format strings literal. It was introduced in python 3.6


问:
Converting a number to s string in JavaScript using the + operator?
I know that if either one of my operands is a string, it should prefer string concatenation, but I get an integer.</p>

```<code>        var number = 134324;
        var num_str = number + "";
       console.log(num_str);
</code>```

答:
No it should not return string .. as you are printing it in console it looks like integer but try using </p>

```<code>var number = 134324;
        var num_str = number + "";
       console.log(num_str);
        typeof(num_str);
</code>```

<p>It will display that your answer is string ... :) hope you satisfied .. </p>

Body:
I know that if either one of my operands is a string, it should prefer string concatenation, but I get an integer.

        var number = 134324;
        var num_str = number + "";
       console.log(num_str);

Body:
No it should not return string .. as you are printing it in console it looks like integer but try using

var number = 134324;
        var num_str = number + "";
       console.log(num_str);
        typeof(num_str);

It will display that your answer is string ... :) hope you satisfied ..


问:
How to input a list of lists with different sizes in tf.data.Dataset
I have a long list of lists of integers (representing sentences, each one of different sizes) that I want to feed using the tf.data library. Each list (of the lists of list) has different length, and I get an error, which I can reproduce here:

```<code>t = [[4,2], [3,4,5]]
dataset = tf.data.Dataset.from_tensor_slices(t)
</code>```

The error I get is:

```<code>ValueError: Argument must be a dense tensor: [[4, 2], [3, 4, 5]] - got shape [2], but wanted [2, 2].
</code>```

Is there a way to do this?

EDIT 1: Just to be clear, I don't want to pad the input list of lists (it's a list of sentences containing over a million elements, with varying lengths) I want to use the tf.data library to feed, in a proper way, a list of lists with varying length.

答:
I don't think tensorflow supports tensors with varying numbers of elements along a given dimension.

However, a simple solution is to pad the nested lists with trailing zeros (where necessary):

```<code>t = [[4,2], [3,4,5]]
max_length = max(len(lst) for lst in t)
t_pad = [lst + [0] * (max_length - len(lst)) for lst in t]
print(t_pad)
dataset = tf.data.Dataset.from_tensor_slices(t_pad)
print(dataset)
</code>```

Outputs:

```<code>[[4, 2, 0], [3, 4, 5]]
<TensorSliceDataset shapes: (3,), types: tf.int32>
</code>```

The zeros shouldn't be a big problem for the model: semantically they're just extra sentences of size zero at the end of each list of actual sentences.

Body:
I have a long list of lists of integers (representing sentences, each one of different sizes) that I want to feed using the tf.data library. Each list (of the lists of list) has different length, and I get an error, which I can reproduce here:

t = [[4,2], [3,4,5]]
dataset = tf.data.Dataset.from_tensor_slices(t)

The error I get is:

ValueError: Argument must be a dense tensor: [[4, 2], [3, 4, 5]] - got shape [2], but wanted [2, 2].

Is there a way to do this?

EDIT 1: Just to be clear, I don't want to pad the input list of lists (it's a list of sentences containing over a million elements, with varying lengths) I want to use the tf.data library to feed, in a proper way, a list of lists with varying length.

Body:
I don't think tensorflow supports tensors with varying numbers of elements along a given dimension.

However, a simple solution is to pad the nested lists with trailing zeros (where necessary):

t = [[4,2], [3,4,5]]
max_length = max(len(lst) for lst in t)
t_pad = [lst + [0] * (max_length - len(lst)) for lst in t]
print(t_pad)
dataset = tf.data.Dataset.from_tensor_slices(t_pad)
print(dataset)

Outputs:

[[4, 2, 0], [3, 4, 5]]
<TensorSliceDataset shapes: (3,), types: tf.int32>

The zeros shouldn't be a big problem for the model: semantically they're just extra sentences of size zero at the end of each list of actual sentences.


问:
Return min/max number in nested list
I'm trying to find the min/max number within a nested list using Linq.

An example class would be:

```<code>public class ListA
{
    public HashSet<HashSet<int>> nestedList;

    public ListA()
    {
        nestedList = new HashSet<HashSet<int>>()
        {
            new HashSet<int> { 1, 3, 5, 7 },
            new HashSet<int> { 2, 12, 7, 19 },
            new HashSet<int> { 6, 9 , 3, 14 }
        };
    }

    public int MaxNumber
    {
        // return the highest number in list
    }
}
</code>```

In the example above, the minimum number would be 1 and the max number 19.

I'm struggling to get anything to get valid syntax. Anyone help?

答:
SelectMany and Max will likely produce the result you desire.

Also consider using DefaultIfEmpty (with whatever default makes sense for your context) - this will ensure that Max doesn't throw an exception if nestedList is empty.

```<code>public int MaxNumber
{
    get { return nestedList.SelectMany(z => z).DefaultIfEmpty(0).Max(); }
}
</code>```

Title: Return min/max number in nested list

Body:
I'm trying to find the min/max number within a nested list using Linq.

An example class would be:

public class ListA
{
    public HashSet<HashSet<int>> nestedList;

    public ListA()
    {
        nestedList = new HashSet<HashSet<int>>()
        {
            new HashSet<int> { 1, 3, 5, 7 },
            new HashSet<int> { 2, 12, 7, 19 },
            new HashSet<int> { 6, 9 , 3, 14 }
        };
    }

    public int MaxNumber
    {
        // return the highest number in list
    }
}

In the example above, the minimum number would be 1 and the max number 19.

I'm struggling to get anything to get valid syntax. Anyone help?

Body:
SelectMany and Max will likely produce the result you desire.

Also consider using DefaultIfEmpty (with whatever default makes sense for your context) - this will ensure that Max doesn't throw an exception if nestedList is empty.

public int MaxNumber
{
    get { return nestedList.SelectMany(z => z).DefaultIfEmpty(0).Max(); }
}


问:
How to set the output of the Asynchronous Task to the text view of the Main Activity
```<code>public class  CheckLoginCredentialsTask extends AsyncTask<Boolean, Integer,
EEmployeeHTTPResponse> {

MainActivity obj = new MainActivity();
private ProgressDialog ResponseProgress;
private Activity curActivity;
String employeeId,password;
String IMEI_Number = "";

public void setContextandActivity(Activity activity,String id,String pwd) {
    this.curActivity=activity;
    this.employeeId=id;
    this.password=pwd;
}

@SuppressLint("LongLogTag")
protected EEmployeeHTTPResponse doInBackground(Boolean... param) {
    try {
        HTTPCommunication loginHTTPRequest;
        if (employeeId != null) {
            Log.i("eEmp/CheckLoginTask", "doInBackg");
            loginHTTPRequest = new HTTPCommunication();
            EmployeeInfoDTO loginInfo = new EmployeeInfoDTO();
            Boolean Profile_Required_Status = param[0];
            loginHTTPRequest.setRequestType(EmpConstants.HTTPRequestType.NewUser);

            if (Profile_Required_Status) {  // Profile_Required_Status = Yes
                loginInfo.Profile_Required = EmpConstants.Profile_Required_Yes;
            }
            loginInfo.EMPID = employeeId;
            loginInfo.Password = password;
            return loginHTTPRequest.SendHTTPRequest(loginInfo);
        }
        return null;
    } catch (Exception e) {
        Log.d("eEmp/CheckLogin/Error", e.toString());
        return null;
    }
}

protected void onProgressUpdate(Integer... progress) {
    Log.d("eEmp/ChkLoginTskProg", "onProgress");
}

protected void onPostExecute(EEmployeeHTTPResponse result) {
    String toastStr = "";

    try {
        if (result != null) {
            if (result.HTTPStatusCode == 200) {
                if (result.Data != null) {
                    if (result.Data.ResponseCode == ActionStatus.Codes.UserFound) {
                        EmployeeInfoResponseDTO empDetails = (EmployeeInfoResponseDTO) result.Data.ActionResult;
                        if (empDetails != null) {
                            obj.tvEmpId.setText(empDetails.EmpID);
                            obj.tvType.setText(empDetails.EmpType);
                            obj.tvDept_code.setText(empDetails.DEPT_CODE);
                        }
                    }
                }
            }
        }
        Log.d("eEmp/CheckLoginTsk", "onPostExecute");
    } catch (Exception e) {
        Log.d("eEmp/PostExecute", e.toString());
    }
}
}
</code>```

My result that I got from server is in empDetails in onPostExecute method. In empDetails there are 3 fields EmpID, EmpType, EmpDept. Now I need to set these values to the textviews in the MainActivity.

I created object to the MainActivity then I called obj.textview But It is not accessing the textview from the MainActivity.

How can I access the textview here. Or if any other methods exists, please tell me.

Any help would be appreciated.

答:
```<code>Access onPostexecute method from your mainactivity as below:

    new CheckLoginCredentialsTask() {
                   @Override
                   protected void onPostExecute(EEmployeeHTTPResponse result) {
                       super.onPostExecute(result);
 try {
               if (result != null) {
                   if (result.HTTPStatusCode == 200) {
                       if (result.Data != null) {
                           if (result.Data.ResponseCode == ActionStatus.Codes.UserFound) {
                               EmployeeInfoResponseDTO empDetails = (EmployeeInfoResponseDTO) result.Data.ActionResult;
                               if (empDetails != null) {
                                   tvEmpId.setText(empDetails.EmpID);
                                   tvType.setText(empDetails.EmpType);
                                   tvDept_code.setText(empDetails.DEPT_CODE);
                               }
                           }
                       }
                   }
               }
               Log.d("eEmp/CheckLoginTsk", "onPostExecute");    } catch (Exception e) {
               Log.d("eEmp/PostExecute", e.toString());    }

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

Body:
public class  CheckLoginCredentialsTask extends AsyncTask<Boolean, Integer,
EEmployeeHTTPResponse> {

MainActivity obj = new MainActivity();
private ProgressDialog ResponseProgress;
private Activity curActivity;
String employeeId,password;
String IMEI_Number = "";

public void setContextandActivity(Activity activity,String id,String pwd) {
    this.curActivity=activity;
    this.employeeId=id;
    this.password=pwd;
}

@SuppressLint("LongLogTag")
protected EEmployeeHTTPResponse doInBackground(Boolean... param) {
    try {
        HTTPCommunication loginHTTPRequest;
        if (employeeId != null) {
            Log.i("eEmp/CheckLoginTask", "doInBackg");
            loginHTTPRequest = new HTTPCommunication();
            EmployeeInfoDTO loginInfo = new EmployeeInfoDTO();
            Boolean Profile_Required_Status = param[0];
            loginHTTPRequest.setRequestType(EmpConstants.HTTPRequestType.NewUser);

            if (Profile_Required_Status) {  // Profile_Required_Status = Yes
                loginInfo.Profile_Required = EmpConstants.Profile_Required_Yes;
            }
            loginInfo.EMPID = employeeId;
            loginInfo.Password = password;
            return loginHTTPRequest.SendHTTPRequest(loginInfo);
        }
        return null;
    } catch (Exception e) {
        Log.d("eEmp/CheckLogin/Error", e.toString());
        return null;
    }
}

protected void onProgressUpdate(Integer... progress) {
    Log.d("eEmp/ChkLoginTskProg", "onProgress");
}

protected void onPostExecute(EEmployeeHTTPResponse result) {
    String toastStr = "";

    try {
        if (result != null) {
            if (result.HTTPStatusCode == 200) {
                if (result.Data != null) {
                    if (result.Data.ResponseCode == ActionStatus.Codes.UserFound) {
                        EmployeeInfoResponseDTO empDetails = (EmployeeInfoResponseDTO) result.Data.ActionResult;
                        if (empDetails != null) {
                            obj.tvEmpId.setText(empDetails.EmpID);
                            obj.tvType.setText(empDetails.EmpType);
                            obj.tvDept_code.setText(empDetails.DEPT_CODE);
                        }
                    }
                }
            }
        }
        Log.d("eEmp/CheckLoginTsk", "onPostExecute");
    } catch (Exception e) {
        Log.d("eEmp/PostExecute", e.toString());
    }
}
}

My result that I got from server is in empDetails in onPostExecute method. In empDetails there are 3 fields EmpID, EmpType, EmpDept. Now I need to set these values to the textviews in the MainActivity.

I created object to the MainActivity then I called obj.textview But It is not accessing the textview from the MainActivity.

How can I access the textview here. Or if any other methods exists, please tell me.

Any help would be appreciated.


问:
CSS - Unable to center vertically
I am trying to center vertically 4 divs present in a Bootstrap row.
Here is my basic code :

```<code><div class="row">
     <div class="col-md-3"><button type="button" style="float:right; height: 40px;">Contact</button></div>
     <div class="col-md-3">Activity 1</div>
     <div class="col-md-3">Activity 2</div>
     <div class="col-md-3">Activity 3</div>
</div>
</code>```

So, I can't use Flexbox because I need to keep the button on the right of the row in medium screen and justify-self:flex-end is not enough to keep the button on the right of the row. I can't also move the row with the button at the end of the code, because I need to keep it in first for mobile devices.
I have also tried to use display:table and display:table-cell and it still not working.

Anyone has an idea ?

答:
You can use flexbox and take advantage of the order property to push the first button to the right of the row, then flexbox can center the contents of each div.

At mobile size, you can override the order property with a media query.

.row {
  display: flex;
}

.col-md-3 {
  display: flex;
  align-items:center; /* vertical center */

  }

.last {
  order:2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
     <div class="col-md-3 last"><button  type="button">Contact</button></div>
     <div class="col-md-3">Activity 1</div>
     <div class="col-md-3">Activity 2</div>
     <div class="col-md-3">Activity 3</div>
</div>
</div></code>```

Title: CSS - Unable to center vertically

Body:
I am trying to center vertically 4 divs present in a Bootstrap row.
Here is my basic code :

<button type="button" style="float:right; height: 40px;">Contact</button>

Activity 1

Activity 2

Activity 3

So, I can't use Flexbox because I need to keep the button on the right of the row in medium screen and justify-self:flex-end is not enough to keep the button on the right of the row. I can't also move the row with the button at the end of the code, because I need to keep it in first for mobile devices.
I have also tried to use display:table and display:table-cell and it still not working.

Anyone has an idea ?

Body:
You can use flexbox and take advantage of the order property to push the first button to the right of the row, then flexbox can center the contents of each div.

At mobile size, you can override the order property with a media query.

.row {
  display: flex;
}

.col-md-3 {
  display: flex;
  align-items:center; /* vertical center */

  }

.last {
  order:2;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
     <div class="col-md-3 last"><button  type="button">Contact</button></div>
     <div class="col-md-3">Activity 1</div>
     <div class="col-md-3">Activity 2</div>
     <div class="col-md-3">Activity 3</div>
</div>
</div>


问:
App unfortunately stopped Error when creating a splash screen
I am trying to create a splash screen using android studio. But I'm getting a error when it launches.It says unfortunately app_name has stopped.

splashscreen.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary" >

        <ImageView
            android:id="@+id/imgLogo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:src="@drawable/logo" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:textSize="12dp"
            android:textColor="#454545"
            android:gravity="center_horizontal"
            android:layout_alignParentBottom="true"
            android:text="OK Google" />

        </RelativeLayout>
</code>```

SplashScreen.java

```<code>public class SplashScreen extends Activity
    {

        // Splash screen timer
        private static int SPLASH_TIME_OUT = 8000;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.splashscreen);

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    // This method will be executed once the timer is over
                    // Start your app main activity
                    Intent i = new Intent(SplashScreen.this, MainActivity.class);
                    startActivity(i);

                    // close this activity
                    finish();
                }
            }, SPLASH_TIME_OUT);
        }

    }
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sloid.splashgun">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name="com.example.sloid.splashgun.SplashScreen"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/SplashTheme" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="com.example.sloid.splashgun.MainActivity"
            android:label="@string/app_name"/>

    </application>

</manifest>
</code>```

I want to create a splash screen and run it for 8s.In that i want to display my logo and some text

The error says Unfortunately app_name has stopped.And it closes.

Please help.

MainActivity.java

```<code>package com.example.sloid.splashgun;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

LogCat report

```<code>12-04 06:54:50.578 3399-3399/? I/art: Late-enabling -Xcheck:jni
12-04 06:54:50.581 3399-3399/? W/art: Unexpected CPU variant for X86 using defaults: x86
12-04 06:54:50.610 3399-3405/? E/art: Failed sending reply to debugger: Broken pipe
12-04 06:54:50.610 3399-3405/? I/art: Debugger is no longer active
12-04 06:54:50.610 3399-3405/? I/art: Starting a blocking GC Instrumentation
12-04 06:54:50.836 3399-3399/? W/System: ClassLoader referenced unknown path: /data/app/com.example.sloid.splashgun-1/lib/x86
12-04 06:54:50.844 3399-3399/? I/InstantRun: starting instant run server: is main process
12-04 06:54:50.878 3399-3399/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
12-04 06:54:51.018 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.018 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.023 3399-3399/? I/art: Alloc sticky concurrent mark sweep GC freed 5048(581KB) AllocSpace objects, 0(0B) LOS objects, 48% free, 4MB/8MB, paused 154us total 5.391ms
12-04 06:54:51.023 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.029 3399-3399/? I/art: Alloc partial concurrent mark sweep GC freed 101(4KB) AllocSpace objects, 0(0B) LOS objects, 39% free, 4MB/7MB, paused 130us total 5.689ms
12-04 06:54:51.029 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.042 3399-3399/? I/art: Alloc concurrent mark sweep GC freed 6(168B) AllocSpace objects, 0(0B) LOS objects, 39% free, 4MB/7MB, paused 137us total 12.522ms
12-04 06:54:51.042 3399-3399/? I/art: Forcing collection of SoftReferences for 105MB allocation
12-04 06:54:51.042 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.051 3399-3399/? I/art: Alloc concurrent mark sweep GC freed 3(72B) AllocSpace objects, 0(0B) LOS objects, 39% free, 4MB/7MB, paused 144us total 8.744ms
12-04 06:54:51.051 3399-3399/? W/art: Throwing OutOfMemoryError "Failed to allocate a 110250012 byte allocation with 2981850 free bytes and 91MB until OOM"
12-04 06:54:51.051 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.051 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.054 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.059 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.065 3399-3399/? I/art: Alloc concurrent mark sweep GC freed 3(72B) AllocSpace objects, 0(0B) LOS objects, 39% free, 4MB/7MB, paused 126us total 6.298ms
12-04 06:54:51.065 3399-3399/? I/art: Forcing collection of SoftReferences for 105MB allocation
12-04 06:54:51.065 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.072 3399-3399/? I/art: Alloc concurrent mark sweep GC freed 3(72B) AllocSpace objects, 0(0B) LOS objects, 39% free, 4MB/7MB, paused 116us total 6.824ms
12-04 06:54:51.072 3399-3399/? W/art: Throwing OutOfMemoryError "Failed to allocate a 110250012 byte allocation with 2981850 free bytes and 91MB until OOM"
12-04 06:54:51.072 3399-3399/? D/skia: --- allocation failed for scaled bitmap
12-04 06:54:51.073 3399-3399/? D/AndroidRuntime: Shutting down VM
12-04 06:54:51.075 3399-3399/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.sloid.splashgun, PID: 3399
                                                 java.lang.OutOfMemoryError: Failed to allocate a 110250012 byte allocation with 2981850 free bytes and 91MB until OOM
                                                     at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                     at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:620)
                                                     at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:455)
                                                     at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1155)
                                                     at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:720)
                                                     at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:571)
                                                     at android.content.res.Resources.loadDrawable(Resources.java:858)
                                                     at android.content.res.TypedArray.getDrawable(TypedArray.java:928)
                                                     at android.widget.ImageView.<init>(ImageView.java:162)
                                                     at android.widget.ImageView.<init>(ImageView.java:150)
                                                     at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
                                                     at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
                                                     at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                                     at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1024)
                                                     at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1081)
                                                     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:769)
                                                     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                     at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                     at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                     at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                                                     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                                                     at com.example.sloid.splashgun.SplashScreen.onCreate(SplashScreen.java:18)
                                                     at android.app.Activity.performCreate(Activity.java:6679)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                     at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:154)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

答:
Your code looks fine. The error is that the device is running out of memory. One of the reason could be that your logo file in drawable folder is too large.

You can also try to run this code on a device with more free memory just to confirm.

Body:
I am trying to create a splash screen using android studio. But I'm getting a error when it launches.It says unfortunately app_name has stopped.

splashscreen.xml

 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary" >

        <ImageView
            android:id="@+id/imgLogo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:src="@drawable/logo" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:textSize="12dp"
            android:textColor="#454545"
            android:gravity="center_horizontal"
            android:layout_alignParentBottom="true"
            android:text="OK Google" />

        </RelativeLayout>

SplashScreen.java

public class SplashScreen extends Activity
    {

        // Splash screen timer
        private static int SPLASH_TIME_OUT = 8000;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.splashscreen);

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    // This method will be executed once the timer is over
                    // Start your app main activity
                    Intent i = new Intent(SplashScreen.this, MainActivity.class);
                    startActivity(i);

                    // close this activity
                    finish();
                }
            }, SPLASH_TIME_OUT);
        }

    }

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sloid.splashgun">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:name="com.example.sloid.splashgun.SplashScreen"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/SplashTheme" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="com.example.sloid.splashgun.MainActivity"
            android:label="@string/app_name"/>

    </application>

</manifest>

I want to create a splash screen and run it for 8s.In that i want to display my logo and some text

The error says Unfortunately app_name has stopped.And it closes.

Please help.

MainActivity.java

package com.example.sloid.splashgun;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

LogCat report

12-04 06:54:50.578 3399-3399/? I/art: Late-enabling -Xcheck:jni
12-04 06:54:50.581 3399-3399/? W/art: Unexpected CPU variant for X86 using defaults: x86
12-04 06:54:50.610 3399-3405/? E/art: Failed sending reply to debugger: Broken pipe
12-04 06:54:50.610 3399-3405/? I/art: Debugger is no longer active
12-04 06:54:50.610 3399-3405/? I/art: Starting a blocking GC Instrumentation
12-04 06:54:50.836 3399-3399/? W/System: ClassLoader referenced unknown path: /data/app/com.example.sloid.splashgun-1/lib/x86
12-04 06:54:50.844 3399-3399/? I/InstantRun: starting instant run server: is main process
12-04 06:54:50.878 3399-3399/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
12-04 06:54:51.018 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.018 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.023 3399-3399/? I/art: Alloc sticky concurrent mark sweep GC freed 5048(581KB) AllocSpace objects, 0(0B) LOS objects, 48% free, 4MB/8MB, paused 154us total 5.391ms
12-04 06:54:51.023 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.029 3399-3399/? I/art: Alloc partial concurrent mark sweep GC freed 101(4KB) AllocSpace objects, 0(0B) LOS objects, 39% free, 4MB/7MB, paused 130us total 5.689ms
12-04 06:54:51.029 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.042 3399-3399/? I/art: Alloc concurrent mark sweep GC freed 6(168B) AllocSpace objects, 0(0B) LOS objects, 39% free, 4MB/7MB, paused 137us total 12.522ms
12-04 06:54:51.042 3399-3399/? I/art: Forcing collection of SoftReferences for 105MB allocation
12-04 06:54:51.042 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.051 3399-3399/? I/art: Alloc concurrent mark sweep GC freed 3(72B) AllocSpace objects, 0(0B) LOS objects, 39% free, 4MB/7MB, paused 144us total 8.744ms
12-04 06:54:51.051 3399-3399/? W/art: Throwing OutOfMemoryError "Failed to allocate a 110250012 byte allocation with 2981850 free bytes and 91MB until OOM"
12-04 06:54:51.051 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.051 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.054 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.059 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.065 3399-3399/? I/art: Alloc concurrent mark sweep GC freed 3(72B) AllocSpace objects, 0(0B) LOS objects, 39% free, 4MB/7MB, paused 126us total 6.298ms
12-04 06:54:51.065 3399-3399/? I/art: Forcing collection of SoftReferences for 105MB allocation
12-04 06:54:51.065 3399-3399/? I/art: Starting a blocking GC Alloc
12-04 06:54:51.072 3399-3399/? I/art: Alloc concurrent mark sweep GC freed 3(72B) AllocSpace objects, 0(0B) LOS objects, 39% free, 4MB/7MB, paused 116us total 6.824ms
12-04 06:54:51.072 3399-3399/? W/art: Throwing OutOfMemoryError "Failed to allocate a 110250012 byte allocation with 2981850 free bytes and 91MB until OOM"
12-04 06:54:51.072 3399-3399/? D/skia: --- allocation failed for scaled bitmap
12-04 06:54:51.073 3399-3399/? D/AndroidRuntime: Shutting down VM
12-04 06:54:51.075 3399-3399/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.sloid.splashgun, PID: 3399
                                                 java.lang.OutOfMemoryError: Failed to allocate a 110250012 byte allocation with 2981850 free bytes and 91MB until OOM
                                                     at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                     at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:620)
                                                     at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:455)
                                                     at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1155)
                                                     at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:720)
                                                     at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:571)
                                                     at android.content.res.Resources.loadDrawable(Resources.java:858)
                                                     at android.content.res.TypedArray.getDrawable(TypedArray.java:928)
                                                     at android.widget.ImageView.<init>(ImageView.java:162)
                                                     at android.widget.ImageView.<init>(ImageView.java:150)
                                                     at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
                                                     at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
                                                     at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                                     at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1024)
                                                     at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1081)
                                                     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:769)
                                                     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                     at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                     at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                     at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                     at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
                                                     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
                                                     at com.example.sloid.splashgun.SplashScreen.onCreate(SplashScreen.java:18)
                                                     at android.app.Activity.performCreate(Activity.java:6679)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                     at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:154)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)


问:
Regex: How to capture second part of the url by regex and jQuery
so these is my url which I need to split into two part.

```<code>1) http://localhost:8800/gb/

2) http://localhost:8800/gb/About.aspx

3) http://localhost:8800/gb/product.aspx?id=1&vref=201

4) http://localhost:8800/gb/Contact.aspx
</code>```

now tell me which regex I should use to split the above url.
the second part will hold the url after from country code

suppose this is my url http://localhost:8800/gb/About.aspx
so second part will be About.aspx

I got one regex (https?:\/\/[^\/]+)\/(.*) which split url into two part but I want to get after from country code. thanks

答:
One possible approach would be ^(?:\/\/|[^\/]+)*\/[a-zA-Z]{2}\/. This is simply based on Get relative URL from absolute URL with the addition to allow for a 2 character country code.

Demo: https://regex101.com/r/5fpRWX/1/

Body:
so these is my url which I need to split into two part.

1) http://localhost:8800/gb/

2) http://localhost:8800/gb/About.aspx

3) http://localhost:8800/gb/product.aspx?id=1&vref=201

4) http://localhost:8800/gb/Contact.aspx

now tell me which regex I should use to split the above url.
the second part will hold the url after from country code

suppose this is my url http://localhost:8800/gb/About.aspx
so second part will be About.aspx

I got one regex (https?:\/\/[^\/]+)\/(.*) which split url into two part but I want to get after from country code. thanks


问:
Translation Missing Error in Logstash Logs
I'm trying to feed data in csv files into elastic search using logstash. My logsatsh config file looks like this:

```<code>input {
    file {
        path => "C:\Users\shreya\Data\RetailData.csv"
        start_position => "beginning"
        #sincedb_path => "C:\Users\shreya\null"

    }
}
filter {
    csv {
        separator => ","
        id => "Store_ID"
        columns => ["Store","Date","Temperature","Fuel_Price", "MarkDown1", "MarkDown2", "MarkDown3", "MarkDown4", "CPI", "Unemployment", "IsHoliday"]
    }
    mutate {convert => ["Store", "integer"]}
    mutate {convert => ["Date", "date"]}
    mutate {convert => ["Temperature", "float"]}
    mutate {convert => ["Fuel_Price", "float"]}
    mutate {convert => ["CPI", "float"]}
    mutate {convert => ["Unemployment", "float"]}

}
output {
    elasticsearch {
        action => "index"
        hosts => "localhost:9200"
        index => "store"
        document_type => "store_retail"
    }
    stdout {}
    #stdout {
  #       codec => rubydebug
  #}
}
</code>```

But I'm getting an error and not able to figure out a way to solve that. I'm new to logstash. My error log looks like this:

```<code>[2017-12-02T15:56:38,150][INFO ][logstash.modules.scaffold] Initializing module {:module_name=>"fb_apache", :directory=>"C:/Users/shreya/logstash-6.0.0/modules/fb_apache/configuration"}
[2017-12-02T15:56:38,165][INFO ][logstash.modules.scaffold] Initializing module {:module_name=>"netflow", :directory=>"C:/Users/shreya/logstash-6.0.0/modules/netflow/configuration"}
[2017-12-02T15:56:38,243][WARN ][logstash.config.source.multilocal] Ignoring the 'pipelines.yml' file because modules or command line options are specified
[2017-12-02T15:56:39,117][INFO ][logstash.agent           ] Successfully started Logstash API endpoint {:port=>9600}
[2017-12-02T15:56:42,965][WARN ][logstash.outputs.elasticsearch] You are using a deprecated config setting "document_type" set in elasticsearch. Deprecated settings will continue to work, but are scheduled for removal from logstash in the future. Document types are being deprecated in Elasticsearch 6.0, and removed entirely in 7.0. You should avoid this feature If you have any questions about this, please visit the #logstash channel on freenode irc. {:name=>"document_type", :plugin=><LogStash::Outputs::ElasticSearch action=>"index", hosts=>["localhost:9200"], index=>"store", document_type=>"store_retail", id=>"91a4406a13e9377abb312acf5f6be8e609a685f9c84a5906af957e956119798c">}
[2017-12-02T15:56:43,604][INFO ][logstash.outputs.elasticsearch] Elasticsearch pool URLs updated {:changes=>{:removed=>[], :added=>[http://localhost:9200/]}}
[2017-12-02T15:56:43,604][INFO ][logstash.outputs.elasticsearch] Running health check to see if an Elasticsearch connection is working {:healthcheck_url=>http://localhost:9200/, :path=>"/"}
[2017-12-02T15:56:43,854][WARN ][logstash.outputs.elasticsearch] Restored connection to ES instance {:url=>"http://localhost:9200/"}
[2017-12-02T15:56:43,932][INFO ][logstash.outputs.elasticsearch] Using mapping template from {:path=>nil}
[2017-12-02T15:56:43,933][INFO ][logstash.outputs.elasticsearch] Attempting to install template {:manage_template=>{"template"=>"logstash-*", "version"=>60001, "settings"=>{"index.refresh_interval"=>"5s"}, "mappings"=>{"_default_"=>{"dynamic_templates"=>[{"message_field"=>{"path_match"=>"message", "match_mapping_type"=>"string", "mapping"=>{"type"=>"text", "norms"=>false}}}, {"string_fields"=>{"match"=>"*", "match_mapping_type"=>"string", "mapping"=>{"type"=>"text", "norms"=>false, "fields"=>{"keyword"=>{"type"=>"keyword", "ignore_above"=>256}}}}}], "properties"=>{"@timestamp"=>{"type"=>"date"}, "@version"=>{"type"=>"keyword"}, "geoip"=>{"dynamic"=>true, "properties"=>{"ip"=>{"type"=>"ip"}, "location"=>{"type"=>"geo_point"}, "latitude"=>{"type"=>"half_float"}, "longitude"=>{"type"=>"half_float"}}}}}}}}
[2017-12-02T15:56:43,964][INFO ][logstash.outputs.elasticsearch] New Elasticsearch output {:class=>"LogStash::Outputs::ElasticSearch", :hosts=>["//localhost:9200"]}
[2017-12-02T15:56:44,011][ERROR][logstash.pipeline        ] Error registering plugin {:pipeline_id=>"main", :plugin=>"#<LogStash::FilterDelegator:0x3e4985f1 @metric_events_out=org.jruby.proxy.org.logstash.instrument.metrics.counter.LongCounter$Proxy2 - namespace: [stats, pipelines, main, plugins, filters, e3501f879986420bd95a59d8a1c006d9bc4351a481c96bd5366e7edb54bc6fbb, events] key: out value:0, @metric_events_in=org.jruby.proxy.org.logstash.instrument.metrics.counter.LongCounter$Proxy2 - namespace: [stats, pipelines, main, plugins, filters, e3501f879986420bd95a59d8a1c006d9bc4351a481c96bd5366e7edb54bc6fbb, events] key: in value:0, @logger=#<LogStash::Logging::Logger:0x48eebcf8 @logger=#<Java::OrgApacheLoggingLog4jCore::Logger:0x113b0d16>>, @metric_events_time=org.jruby.proxy.org.logstash.instrument.metrics.counter.LongCounter$Proxy2 - namespace: [stats, pipelines, main, plugins, filters, e3501f879986420bd95a59d8a1c006d9bc4351a481c96bd5366e7edb54bc6fbb, events] key: duration_in_millis value:0, @id=\"e3501f879986420bd95a59d8a1c006d9bc4351a481c96bd5366e7edb54bc6fbb\", @klass=LogStash::Filters::Mutate, @metric_events=#<LogStash::Instrument::NamespacedMetric:0x7c8acc8 @metric=#<LogStash::Instrument::Metric:0x3afcd9b5 @collector=#<LogStash::Instrument::Collector:0x73e63041 @agent=nil, @metric_store=#<LogStash::Instrument::MetricStore:0x60e51f03 @store=#<Concurrent::Map:0x00000000000fb0 entries=3 default_proc=nil>, @structured_lookup_mutex=#<Mutex:0x2209413b>, @fast_lookup=#<Concurrent::Map:0x00000000000fb4 entries=86 default_proc=nil>>>>, @namespace_name=[:stats, :pipelines, :main, :plugins, :filters, :e3501f879986420bd95a59d8a1c006d9bc4351a481c96bd5366e7edb54bc6fbb, :events]>, @filter=<LogStash::Filters::Mutate convert=>{\"Date\"=>\"date\"}, id=>\"e3501f879986420bd95a59d8a1c006d9bc4351a481c96bd5366e7edb54bc6fbb\", enable_metric=>true, periodic_flush=>false>>", :error=>"translation missing: en.logstash.agent.configuration.invalid_plugin_register", :thread=>"#<Thread:0x3cc2461b@C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:290 run>"}
[2017-12-02T15:56:44,042][ERROR][logstash.pipeline        ] Pipeline aborted due to error {:pipeline_id=>"main", :exception=>#<LogStash::ConfigurationError: translation missing: en.logstash.agent.configuration.invalid_plugin_register>, :backtrace=>["C:/Users/shreya/logstash-6.0.0/vendor/bundle/jruby/2.3.0/gems/logstash-filter-mutate-3.1.6/lib/logstash/filters/mutate.rb:186:in `block in register'", "org/jruby/RubyHash.java:1343:in `each'", "C:/Users/shreya/logstash-6.0.0/vendor/bundle/jruby/2.3.0/gems/logstash-filter-mutate-3.1.6/lib/logstash/filters/mutate.rb:184:in `register'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:388:in `register_plugin'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:399:in `block in register_plugins'", "org/jruby/RubyArray.java:1734:in `each'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:399:in `register_plugins'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:801:in `maybe_setup_out_plugins'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:409:in `start_workers'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:333:in `run'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:293:in `block in start'"], :thread=>"#<Thread:0x3cc2461b@C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:290 run>"}
[2017-12-02T15:56:44,058][ERROR][logstash.agent           ] Failed to execute action {:id=>:main, :action_type=>LogStash::ConvergeResult::FailedAction, :message=>"Could not execute action: LogStash::PipelineAction::Create/pipeline_id:main, action_result: false", :backtrace=>nil}
</code>```

答:
The problem comes from the convert target in one of the mutate filters. From the documentation:

Valid conversion targets are: integer, float, string, and boolean.

So this part is causing the crash:

```<code>mutate {convert => ["Date", "date"]}
</code>```

If you want a to convert a String to a date, you'll have to use the date filter.

Body:
I'm trying to feed data in csv files into elastic search using logstash. My logsatsh config file looks like this:

input {
    file {
        path => "C:\Users\shreya\Data\RetailData.csv"
        start_position => "beginning"
        #sincedb_path => "C:\Users\shreya\null"

    }
}
filter {
    csv {
        separator => ","
        id => "Store_ID"
        columns => ["Store","Date","Temperature","Fuel_Price", "MarkDown1", "MarkDown2", "MarkDown3", "MarkDown4", "CPI", "Unemployment", "IsHoliday"]
    }
    mutate {convert => ["Store", "integer"]}
    mutate {convert => ["Date", "date"]}
    mutate {convert => ["Temperature", "float"]}
    mutate {convert => ["Fuel_Price", "float"]}
    mutate {convert => ["CPI", "float"]}
    mutate {convert => ["Unemployment", "float"]}

}
output {
    elasticsearch {
        action => "index"
        hosts => "localhost:9200"
        index => "store"
        document_type => "store_retail"
    }
    stdout {}
    #stdout {
  #       codec => rubydebug
  #}
}

But I'm getting an error and not able to figure out a way to solve that. I'm new to logstash. My error log looks like this:

[2017-12-02T15:56:38,150][INFO ][logstash.modules.scaffold] Initializing module {:module_name=>"fb_apache", :directory=>"C:/Users/shreya/logstash-6.0.0/modules/fb_apache/configuration"}
[2017-12-02T15:56:38,165][INFO ][logstash.modules.scaffold] Initializing module {:module_name=>"netflow", :directory=>"C:/Users/shreya/logstash-6.0.0/modules/netflow/configuration"}
[2017-12-02T15:56:38,243][WARN ][logstash.config.source.multilocal] Ignoring the 'pipelines.yml' file because modules or command line options are specified
[2017-12-02T15:56:39,117][INFO ][logstash.agent           ] Successfully started Logstash API endpoint {:port=>9600}
[2017-12-02T15:56:42,965][WARN ][logstash.outputs.elasticsearch] You are using a deprecated config setting "document_type" set in elasticsearch. Deprecated settings will continue to work, but are scheduled for removal from logstash in the future. Document types are being deprecated in Elasticsearch 6.0, and removed entirely in 7.0. You should avoid this feature If you have any questions about this, please visit the #logstash channel on freenode irc. {:name=>"document_type", :plugin=><LogStash::Outputs::ElasticSearch action=>"index", hosts=>["localhost:9200"], index=>"store", document_type=>"store_retail", id=>"91a4406a13e9377abb312acf5f6be8e609a685f9c84a5906af957e956119798c">}
[2017-12-02T15:56:43,604][INFO ][logstash.outputs.elasticsearch] Elasticsearch pool URLs updated {:changes=>{:removed=>[], :added=>[http://localhost:9200/]}}
[2017-12-02T15:56:43,604][INFO ][logstash.outputs.elasticsearch] Running health check to see if an Elasticsearch connection is working {:healthcheck_url=>http://localhost:9200/, :path=>"/"}
[2017-12-02T15:56:43,854][WARN ][logstash.outputs.elasticsearch] Restored connection to ES instance {:url=>"http://localhost:9200/"}
[2017-12-02T15:56:43,932][INFO ][logstash.outputs.elasticsearch] Using mapping template from {:path=>nil}
[2017-12-02T15:56:43,933][INFO ][logstash.outputs.elasticsearch] Attempting to install template {:manage_template=>{"template"=>"logstash-*", "version"=>60001, "settings"=>{"index.refresh_interval"=>"5s"}, "mappings"=>{"_default_"=>{"dynamic_templates"=>[{"message_field"=>{"path_match"=>"message", "match_mapping_type"=>"string", "mapping"=>{"type"=>"text", "norms"=>false}}}, {"string_fields"=>{"match"=>"*", "match_mapping_type"=>"string", "mapping"=>{"type"=>"text", "norms"=>false, "fields"=>{"keyword"=>{"type"=>"keyword", "ignore_above"=>256}}}}}], "properties"=>{"@timestamp"=>{"type"=>"date"}, "@version"=>{"type"=>"keyword"}, "geoip"=>{"dynamic"=>true, "properties"=>{"ip"=>{"type"=>"ip"}, "location"=>{"type"=>"geo_point"}, "latitude"=>{"type"=>"half_float"}, "longitude"=>{"type"=>"half_float"}}}}}}}}
[2017-12-02T15:56:43,964][INFO ][logstash.outputs.elasticsearch] New Elasticsearch output {:class=>"LogStash::Outputs::ElasticSearch", :hosts=>["//localhost:9200"]}
[2017-12-02T15:56:44,011][ERROR][logstash.pipeline        ] Error registering plugin {:pipeline_id=>"main", :plugin=>"#<LogStash::FilterDelegator:0x3e4985f1 @metric_events_out=org.jruby.proxy.org.logstash.instrument.metrics.counter.LongCounter$Proxy2 - namespace: [stats, pipelines, main, plugins, filters, e3501f879986420bd95a59d8a1c006d9bc4351a481c96bd5366e7edb54bc6fbb, events] key: out value:0, @metric_events_in=org.jruby.proxy.org.logstash.instrument.metrics.counter.LongCounter$Proxy2 - namespace: [stats, pipelines, main, plugins, filters, e3501f879986420bd95a59d8a1c006d9bc4351a481c96bd5366e7edb54bc6fbb, events] key: in value:0, @logger=#<LogStash::Logging::Logger:0x48eebcf8 @logger=#<Java::OrgApacheLoggingLog4jCore::Logger:0x113b0d16>>, @metric_events_time=org.jruby.proxy.org.logstash.instrument.metrics.counter.LongCounter$Proxy2 - namespace: [stats, pipelines, main, plugins, filters, e3501f879986420bd95a59d8a1c006d9bc4351a481c96bd5366e7edb54bc6fbb, events] key: duration_in_millis value:0, @id=\"e3501f879986420bd95a59d8a1c006d9bc4351a481c96bd5366e7edb54bc6fbb\", @klass=LogStash::Filters::Mutate, @metric_events=#<LogStash::Instrument::NamespacedMetric:0x7c8acc8 @metric=#<LogStash::Instrument::Metric:0x3afcd9b5 @collector=#<LogStash::Instrument::Collector:0x73e63041 @agent=nil, @metric_store=#<LogStash::Instrument::MetricStore:0x60e51f03 @store=#<Concurrent::Map:0x00000000000fb0 entries=3 default_proc=nil>, @structured_lookup_mutex=#<Mutex:0x2209413b>, @fast_lookup=#<Concurrent::Map:0x00000000000fb4 entries=86 default_proc=nil>>>>, @namespace_name=[:stats, :pipelines, :main, :plugins, :filters, :e3501f879986420bd95a59d8a1c006d9bc4351a481c96bd5366e7edb54bc6fbb, :events]>, @filter=<LogStash::Filters::Mutate convert=>{\"Date\"=>\"date\"}, id=>\"e3501f879986420bd95a59d8a1c006d9bc4351a481c96bd5366e7edb54bc6fbb\", enable_metric=>true, periodic_flush=>false>>", :error=>"translation missing: en.logstash.agent.configuration.invalid_plugin_register", :thread=>"#<Thread:0x3cc2461b@C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:290 run>"}
[2017-12-02T15:56:44,042][ERROR][logstash.pipeline        ] Pipeline aborted due to error {:pipeline_id=>"main", :exception=>#<LogStash::ConfigurationError: translation missing: en.logstash.agent.configuration.invalid_plugin_register>, :backtrace=>["C:/Users/shreya/logstash-6.0.0/vendor/bundle/jruby/2.3.0/gems/logstash-filter-mutate-3.1.6/lib/logstash/filters/mutate.rb:186:in `block in register'", "org/jruby/RubyHash.java:1343:in `each'", "C:/Users/shreya/logstash-6.0.0/vendor/bundle/jruby/2.3.0/gems/logstash-filter-mutate-3.1.6/lib/logstash/filters/mutate.rb:184:in `register'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:388:in `register_plugin'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:399:in `block in register_plugins'", "org/jruby/RubyArray.java:1734:in `each'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:399:in `register_plugins'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:801:in `maybe_setup_out_plugins'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:409:in `start_workers'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:333:in `run'", "C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:293:in `block in start'"], :thread=>"#<Thread:0x3cc2461b@C:/Users/shreya/logstash-6.0.0/logstash-core/lib/logstash/pipeline.rb:290 run>"}
[2017-12-02T15:56:44,058][ERROR][logstash.agent           ] Failed to execute action {:id=>:main, :action_type=>LogStash::ConvergeResult::FailedAction, :message=>"Could not execute action: LogStash::PipelineAction::Create/pipeline_id:main, action_result: false", :backtrace=>nil}

Body:
The problem comes from the convert target in one of the mutate filters. From the documentation:

Valid conversion targets are: integer, float, string, and boolean.

So this part is causing the crash:

mutate {convert => ["Date", "date"]}

If you want a to convert a String to a date, you'll have to use the date filter.


问:
Angular Routing Params
I'd like to know if there is a way that the parameters, which a route possesses, will stay even if I route/go to another page?

For example:

localhost:4200/welcomepage?param=true => localhost:4200/secondpage?param=true

答:
when navigating to another page, try as follows to pass the existing parameters</p>

```<code>constructor(private route: ActivatedRoute,
private router: Router) { }

const queryParams = Object.assign({}, this.route.snapshot.queryParams);
this.router.navigate(['./secondpage'], { queryParams: queryParams});
</code>```

Title: Angular Routing Params

Body:
when navigating to another page, try as follows to pass the existing parameters

constructor(private route: ActivatedRoute,
private router: Router) { }

const queryParams = Object.assign({}, this.route.snapshot.queryParams);
this.router.navigate(['./secondpage'], { queryParams: queryParams});


问:
Showing an arrow that is heading a specific location
Does anyone know how to place out an arrow that points to a specific annotation depending on my current heading. For example; I want the arrow to be vertical when the current heading is the same as the annotation's coordinates.
I am offering 50$ to the one doing this thing for me via paypal
Have a look at the picture below;

.

答: Sounds like you're trying to do the same thing as Using lattitude and longitude of the current location and destination location , how can we get the direction in iphone get the heading between your current position and some destination, then compare that heading with your current heading to determine which direction that arrow should face.</p>

ContentLicense: CC BY-SA 2.5


问:
javascript: replace classList that is into a conditional
I want change the class of a div any time, no mater what class it has. If the div has the class "mystyle" I want it to change into "mystyle1", and vice versa. My code is this:

<!DOCTYPE html>

Click the button to change the style class from DIV.

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

I am a DIV element

```

When we press the buttom it has to change the css style any time. But it doesn't.
I think that the problem has something to be with the mixed of the conditional (classList.contains) and the classList.replace, because I did it separately and it worked.

Do you know what it is my problem? Thank you.

答:
Few things:

You'd misspelt mystyle in x.classList.contains();

Your second if-statement should be an else-if. This is because it changes the class, and checks again for the new class, thus resetting it.

<!DOCTYPE html>

Click the button to change the style class from DIV.

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

I am a DIV element

```

Body:
I want change the class of a div any time, no mater what class it has. If the div has the class "mystyle" I want it to change into "mystyle1", and vice versa. My code is this:

<!DOCTYPE html>

Click the button to change the style class from DIV.

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

I am a DIV element

When we press the buttom it has to change the css style any time. But it doesn't.
I think that the problem has something to be with the mixed of the conditional (classList.contains) and the classList.replace, because I did it separately and it worked.

Do you know what it is my problem? Thank you.

Body:
Few things:

You'd misspelt mystyle in x.classList.contains();

Your second if-statement should be an else-if. This is because it changes the class, and checks again for the new class, thus resetting it.

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {
    width: 300px;
    height: 50px;
    background-color: coral;
    color: white;
    font-size: 25px;
}

.mystyle1 {
    width: 100px;
    height: 100px;
    background-color: black;
    color: coral;
    font-size: 30px;
}
</style>
</head>
<body>

<p>Click the button to change the style class from DIV.</p>

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

<div id="myDIV" class="mystyle">
I am a DIV element
</div>

<script>
function myFunction() {
    var x = document.getElementById("myDIV");

    if (x.classList.contains("mystyle")) {
        x.classList.replace("mystyle", "mystyle1");
    } else if (x.classList.contains("mystyle1")) {
        x.classList.replace("mystyle1", "mystyle");
    }
}
</script>

</body>
</html>


问:
Grails. Redirect not working after CURL call from remote server
I HAVE EDITED THE QUESTION TO SIMPLIFY IT

I have an app working in a domain like this:

```<code>http://localhost:8092/myapp
</code>```

If I access to

```<code>http://localhost:8092/myapp/ticket/save
</code>```

with a browser, everything goes fine. However, if I make a CURL call from command line to another controller, and from there I try to redirect to the controller "ticket" method "save", as shown in the URL above, it works only if the call is made from localhost. But if I made the call from a remote server it won't do anything.

This is the curl call:

```<code>curl --location http://192.168.1.18:8092/myapp/trans/index
</code>```

and the index method:

```<code>def index() {
    print "index"

    redirect(controller: "ticket", action:"save")
}
</code>```

When making the call from a remote client, Grails won't do the redirection and it does not show any error. However, in the terminal, it says:

```<code>curl  --location  http://192.168.1.18:8092/Post-editor_Grails/traduccion/index
curl: (7) couldn't connect to host
</code>```

BUT the call does reach the server, as "index" gets printed in Grails console. So I asume that error comes from the redirection.

I have tried to set absolute:true in the redirect, as shown here:

Grails redirect with reverse proxy

but it does not work either.

Any ideas?

答:
Nah, forget this question. In Config.groovy I had:

grails.serverURL = "http://localhost:8092/${appName}"

Just need to change localhost to 192.168.... (it needs the "absolute:true" though)

I don't know if I should delete the question

Body:
I HAVE EDITED THE QUESTION TO SIMPLIFY IT

I have an app working in a domain like this:

http://localhost:8092/myapp

If I access to

http://localhost:8092/myapp/ticket/save

with a browser, everything goes fine. However, if I make a CURL call from command line to another controller, and from there I try to redirect to the controller "ticket" method "save", as shown in the URL above, it works only if the call is made from localhost. But if I made the call from a remote server it won't do anything.

This is the curl call:

curl --location http://192.168.1.18:8092/myapp/trans/index

and the index method:

def index() {
    print "index"

    redirect(controller: "ticket", action:"save")
}

When making the call from a remote client, Grails won't do the redirection and it does not show any error. However, in the terminal, it says:

curl  --location  http://192.168.1.18:8092/Post-editor_Grails/traduccion/index
curl: (7) couldn't connect to host

BUT the call does reach the server, as "index" gets printed in Grails console. So I asume that error comes from the redirection.

I have tried to set absolute:true in the redirect, as shown here:

Grails redirect with reverse proxy

but it does not work either.

Any ideas?


问:
How many characters in varchar(max)?
How many characters can a SQL Server 2008 database field contain when the data type is VARCHAR(MAX)?</p>

答:
For future readers who need this answer quickly:

2^31-1 = 2 147 483 647 characters, or roughly 2.147 billion

Title: How many characters in varchar(max)?


问:
App Crashes when trying to load action bar in Android Studio
I am quite new to Android and have been learning it myself with some help with online videos. I am attempting to use two activities to go back and forth using an action bar. The first activity is just the main activity however the second is a map activity. When running through the emulator is crashes when I press on the button to go from the first activity to the second.

Here is my code -

Main Activity

```<code> @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //declare list view
        ListView listView = (ListView) findViewById(R.id.listView);
        //create array list called places using strings
        final ArrayList<String> places = new ArrayList<>();

        places.add("Add a new location");
        //create array adapter
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,places);
        //set up list view to use array adapter
        listView.setAdapter(arrayAdapter);

        [![listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {][1]][1]

                Intent i = new Intent(getApplicationContext(), MapsActivity.class);

                i.putExtra("locationInfo",position);
                //start activity with intent of i
                startActivity(i);
            }
        });
    }
</code>```

Map Activity -

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        ActionBar actionBar = getActionBar();

        actionBar.setDisplayHomeAsUpEnabled(true);

        Intent i = getIntent();

        Log.i("LocationInfo", Integer.toString(i.getIntExtra("locationInfo", -1)));

    }
</code>```

It seems to be crashing on the line - actionBar.setDisplayHomeAsUpEnables(true);

I have imported the action bar library and changed the API level on my emulator to see if that was the problem. However I have got a little stuck on what the problem is with my limited experience with Android.

Any ideas on how to rectify the problem would be fantastic.

Log Cat-

XML for main activity

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.lennydegriffa.memorableplaces.MainActivity">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>
</code>```

XML for Map Activity

```<code><fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lennydegriffa.memorableplaces.MapsActivity" />
</code>```

答:
Just check your style.xml, because it may be that you have done

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</code>```

change above to

```<code> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</code>```

Body:
I am quite new to Android and have been learning it myself with some help with online videos. I am attempting to use two activities to go back and forth using an action bar. The first activity is just the main activity however the second is a map activity. When running through the emulator is crashes when I press on the button to go from the first activity to the second.

Here is my code -

Main Activity

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //declare list view
        ListView listView = (ListView) findViewById(R.id.listView);
        //create array list called places using strings
        final ArrayList<String> places = new ArrayList<>();

        places.add("Add a new location");
        //create array adapter
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,places);
        //set up list view to use array adapter
        listView.setAdapter(arrayAdapter);

        [![listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {][1]][1]

                Intent i = new Intent(getApplicationContext(), MapsActivity.class);

                i.putExtra("locationInfo",position);
                //start activity with intent of i
                startActivity(i);
            }
        });
    }

Map Activity -

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        ActionBar actionBar = getActionBar();

        actionBar.setDisplayHomeAsUpEnabled(true);

        Intent i = getIntent();

        Log.i("LocationInfo", Integer.toString(i.getIntExtra("locationInfo", -1)));

    }

It seems to be crashing on the line - actionBar.setDisplayHomeAsUpEnables(true);

I have imported the action bar library and changed the API level on my emulator to see if that was the problem. However I have got a little stuck on what the problem is with my limited experience with Android.

Any ideas on how to rectify the problem would be fantastic.

Log Cat-

XML for main activity

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.lennydegriffa.memorableplaces.MainActivity">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

XML for Map Activity

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.lennydegriffa.memorableplaces.MapsActivity" />

Body:
Just check your style.xml, because it may be that you have done

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

change above to

 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">


问:
Can't make metalsmith-layouts and metalsmith-in-place work
I try to make me a boilerplate with metalsmith using some plugins but I can't make metalsmith-layouts and metalsmith-in-place work together. I tried many things and I succeed to make one of them work but never the second using a template engine (for instance handlebars).
It seems like metalsmith-layouts doesn't want to read files in .hbs.

I have properly installed handlebars ans jstransform-handlebars (and .hbs files gets properly transformed by metalsmith-in-place but can't make it work with metalsmith layouts ... And this is really annoying).

My goal is to use a layout file in which the content will be rendered using a template engine like handlebars.

Here is my index.js code :

```<code>const path = require('path');
const metalsmith = require('metalsmith');
const inPlace = require('metalsmith-in-place');
const layouts = require('metalsmith-layouts');
const assets = require('metalsmith-assets');
const sass = require('metalsmith-sass');
const htmlMinifier = require("metalsmith-html-minifier");
const permalinks = require('metalsmith-permalinks');

metalsmith(__dirname)
    .source('src')
    .destination('dist')
    .use(sass({
        file: './src/scss/*.scss',
        outputDir: "css/"
    }))
    .use(inPlace())                             //Template engine uses Handlebars
    .use(layouts({
         engine: 'handlebars',
         default: "layout.html.hbs"
    }))
    .use(htmlMinifier())
    .use(permalinks({
        relative: false,
        pattern: ':url'
    }))
    .use(assets({
        source: 'assets'
    }))
    .build((err) => err && console.error(err));
</code>```

And here is my directory:

答:
I finally came to the conclusion that the layout file MUST be a .html file. The content of its html file is processed with the engine specified in the

```<code>.use(layouts({
    engine: handlebars
}))
</code>```

despite the file isn't a .hbs file in this format which is quite confusing. The in-place plugin is useful to use template engine for contents pages.

Body:
I try to make me a boilerplate with metalsmith using some plugins but I can't make metalsmith-layouts and metalsmith-in-place work together. I tried many things and I succeed to make one of them work but never the second using a template engine (for instance handlebars).
It seems like metalsmith-layouts doesn't want to read files in .hbs.

I have properly installed handlebars ans jstransform-handlebars (and .hbs files gets properly transformed by metalsmith-in-place but can't make it work with metalsmith layouts ... And this is really annoying).

My goal is to use a layout file in which the content will be rendered using a template engine like handlebars.

Here is my index.js code :

const path = require('path');
const metalsmith = require('metalsmith');
const inPlace = require('metalsmith-in-place');
const layouts = require('metalsmith-layouts');
const assets = require('metalsmith-assets');
const sass = require('metalsmith-sass');
const htmlMinifier = require("metalsmith-html-minifier");
const permalinks = require('metalsmith-permalinks');

metalsmith(__dirname)
    .source('src')
    .destination('dist')
    .use(sass({
        file: './src/scss/*.scss',
        outputDir: "css/"
    }))
    .use(inPlace())                             //Template engine uses Handlebars
    .use(layouts({
         engine: 'handlebars',
         default: "layout.html.hbs"
    }))
    .use(htmlMinifier())
    .use(permalinks({
        relative: false,
        pattern: ':url'
    }))
    .use(assets({
        source: 'assets'
    }))
    .build((err) => err && console.error(err));

And here is my directory:

Body:
I finally came to the conclusion that the layout file MUST be a .html file. The content of its html file is processed with the engine specified in the

.use(layouts({
    engine: handlebars
}))

despite the file isn't a .hbs file in this format which is quite confusing. The in-place plugin is useful to use template engine for contents pages.


问:
How do I get the directory where a Bash script is located from within the script itself?
How do I get the path of the directory in which a Bash script is located, inside that script?

I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:

```<code>$ ./application
</code>```

答:
Hmm, if in the path, basename and dirname are just not going to cut it and walking the path is hard (what if the parent didn't export PATH?!).

However, the shell has to have an open handle to its script, and in Bash the handle is #255.

```<code>SELF=`readlink /proc/$$/fd/255`
</code>```

works for me.

OwnerDisplayName: Jim Robert

Body:
How do I get the path of the directory in which a Bash script is located, inside that script?

I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:

$ ./application

Body:
Hmm, if in the path, basename and dirname are just not going to cut it and walking the path is hard (what if the parent didn't export PATH?!).

However, the shell has to have an open handle to its script, and in Bash the handle is #255.

SELF=`readlink /proc/$$/fd/255`

works for me.

OwnerDisplayName: Joshua


问:
Crystal Reports grouping removes data
Basicaly, when i add another item to summarize, the group is filtered.  I'd like to show 0 or nothing if there is no data for the new item i'm adding.

Report images

The field i'm adding is from a different table. If i add a field from the same table it seems to allow blanks

答:
You are joining the tables using an INNER JOIN. you need to make this a left join.

If you're using the "Links" functionality you can use the Link Options dialog to set it to a Left Outer Join

If you're writing a SQL statement to join the tables you can just use a Left Join instead of an inner join

Title: Crystal Reports grouping removes data