问:
How to perform OrderBy followed by OrderByDescending?
I have a collection where I am trying to sort the records first by Quarter and then inside the quarter by highest amounts. My code so far is:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Test> lstTest = new List<Test>();
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 2), amount = 2500 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 2), amount = 10000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 5), amount = 4000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 10), amount = 40000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 15), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 25), amount = 12000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 5), amount = 38000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 10), amount = 38000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 15), amount = 4000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 20), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 20), amount = 20000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 15), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 20), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 20), amount = 4000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 31), amount = 1000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 9), amount = 50000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 11), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 21), amount = 1000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 21), amount = 10000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 28), amount = 5000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 5), amount = 45000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 7), amount = 98000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 9), amount = 7000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 25), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 31), amount = 1000 });

            var result = lstTest.Select(x => new
            {
                Amount = x.amount,
                Date = x.dt,
                MonthDiff = GetMonthsDiff(DateTime.Now, x.dt),
                Quater = GetQuarter(DateTime.Now, x.dt)
            }).OrderBy(o=>o.Quater).ToList();

            foreach (var res in result)
            {
                Console.WriteLine("Amount = {0}  Date= {1} MonthDiff= {2}  Quater= {3}", res.Amount, res.Date, res.MonthDiff, res.Quater);
            }
            Console.ReadKey();
        }

        public static string GetQuarter(DateTime start, DateTime end)// int month)
        {
            int month = GetMonthsDiff(start, end);
            string quarter =  month <= 3 ? "Q1" : (month >= 4 && month <= 6) ? "Q2" : (month >= 7 && month <= 9) ? "Q3" : "Q4";
            return quarter;
        }

        public static int GetMonthsDiff(DateTime start, DateTime end)
        {
            if (start > end)
                return GetMonthsDiff(end, start);

            int months = 0;
            do
            {
                start = start.AddMonths(1);
                if (start > end)
                    return months;

                months++;
            }
            while (true);
        }
    }

    public class Test
    {
        public DateTime dt { get; set; }
        public int amount { get; set; }
    }
}
</code>```

The output is

If I do OrderBy(o=>o.Quater).OrderByDescending(o=>o.Amount) the output changes to

That is it is first sorting by Quarter and then by Amount.

But I am looking for first sort by Quarter and within the Quarter sort by Amount descending.

The desired output is

What needs to be modified in the program so as achieve the target?

答:
replace

```<code>OrderBy(o=>o.Quater).OrderByDescending(o=>o.Amount)
</code>```

with

```<code>OrderBy(o=>o.Quater).ThenByDescending(o=>o.Amount)
</code>```

ThenByDescending performs a subsequent ordering of the elements in a
  sequence in descending order by using a specified comparer.

Body:
I have a collection where I am trying to sort the records first by Quarter and then inside the quarter by highest amounts. My code so far is:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Test> lstTest = new List<Test>();
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 2), amount = 2500 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 2), amount = 10000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 5), amount = 4000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 10), amount = 40000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 15), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 1, 25), amount = 12000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 5), amount = 38000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 10), amount = 38000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 15), amount = 4000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 20), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 2, 20), amount = 20000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 15), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 20), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 20), amount = 4000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 3, 31), amount = 1000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 9), amount = 50000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 11), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 21), amount = 1000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 21), amount = 10000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 4, 28), amount = 5000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 5), amount = 45000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 7), amount = 98000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 9), amount = 7000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 25), amount = 2000 });
            lstTest.Add(new Test { dt = new DateTime(2017, 5, 31), amount = 1000 });

            var result = lstTest.Select(x => new
            {
                Amount = x.amount,
                Date = x.dt,
                MonthDiff = GetMonthsDiff(DateTime.Now, x.dt),
                Quater = GetQuarter(DateTime.Now, x.dt)
            }).OrderBy(o=>o.Quater).ToList();

            foreach (var res in result)
            {
                Console.WriteLine("Amount = {0}  Date= {1} MonthDiff= {2}  Quater= {3}", res.Amount, res.Date, res.MonthDiff, res.Quater);
            }
            Console.ReadKey();
        }

        public static string GetQuarter(DateTime start, DateTime end)// int month)
        {
            int month = GetMonthsDiff(start, end);
            string quarter =  month <= 3 ? "Q1" : (month >= 4 && month <= 6) ? "Q2" : (month >= 7 && month <= 9) ? "Q3" : "Q4";
            return quarter;
        }

        public static int GetMonthsDiff(DateTime start, DateTime end)
        {
            if (start > end)
                return GetMonthsDiff(end, start);

            int months = 0;
            do
            {
                start = start.AddMonths(1);
                if (start > end)
                    return months;

                months++;
            }
            while (true);
        }
    }

    public class Test
    {
        public DateTime dt { get; set; }
        public int amount { get; set; }
    }
}

The output is

If I do OrderBy(o=>o.Quater).OrderByDescending(o=>o.Amount) the output changes to

That is it is first sorting by Quarter and then by Amount.

But I am looking for first sort by Quarter and within the Quarter sort by Amount descending.

The desired output is

What needs to be modified in the program so as achieve the target?

Body:
replace

OrderBy(o=>o.Quater).OrderByDescending(o=>o.Amount)

with

OrderBy(o=>o.Quater).ThenByDescending(o=>o.Amount)

ThenByDescending performs a subsequent ordering of the elements in a
  sequence in descending order by using a specified comparer.


来源: stackexchange

问:
Python Import class error, trying to understand the root directory __init__.py
I am just 4 days old to python. I am just trying to understand the root  __init__.py import functionality. Googled lot to understand the same but not able to find one useful link (may be my search key is not relevant) . Please share some links.

I am getting error as "ImportError: cannot import name Person"

Below is the structure

```<code>Example(directory)
    model
        __init__.py (empty)
        myclass.py
    __init__.py
    run.py
</code>```

myclass.py

```<code>class Person(object):
    def __init__(self):
        self.name = "Raja"

    def print_name(self):
        print self.name
</code>```

__init__.py

```<code>from model.myclass import Person
</code>```

run.py

```<code>from model import Person

def donext():
    person = Person()
    person.print_name()

if __name__ == '__main__':
    donext()
</code>```

答:
Either, as @gonczor suggested, you can simply leave __init__ empty (moreover, you don't need the root one) and import directly from the package:

```<code>from model.myclass import Person
</code>```

Or, if you intentionally want to flatten the interface of the package, this is as simple as this:

model/__init__.py

```<code>from myclass import Person
</code>```

run.py

```<code>from model import Person
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am just 4 days old to python. I am just trying to understand the root  __init__.py import functionality. Googled lot to understand the same but not able to find one useful link (may be my search key is not relevant) . Please share some links.

I am getting error as "ImportError: cannot import name Person"

Below is the structure

Example(directory)
    model
        __init__.py (empty)
        myclass.py
    __init__.py
    run.py

myclass.py

class Person(object):
    def __init__(self):
        self.name = "Raja"

    def print_name(self):
        print self.name

__init__.py

from model.myclass import Person

run.py

from model import Person

def donext():
    person = Person()
    person.print_name()

if __name__ == '__main__':
    donext()

Body:
Either, as @gonczor suggested, you can simply leave __init__ empty (moreover, you don't need the root one) and import directly from the package:

from model.myclass import Person

Or, if you intentionally want to flatten the interface of the package, this is as simple as this:

model/__init__.py

from myclass import Person

run.py

from model import Person


答:
Here you are sorting the list two times, you are getting the output of the final sort only, if you want to perform the second sort over the sorted result of the first then you have to make use of ThenByDescending(if you want the second sort in descending order or else use ThenBy()) followed by OrderBy as like this:

```<code>var sortedItems = lstTest.OrderBy(o=>o.Quater).ThenByDescending(o=>o.Amount);
</code>```

I have modified the code here in this example, you can check the output in the fiddle

ContentLicense: CC BY-SA 4.0

Title: How to perform OrderBy followed by OrderByDescending?

Body:
Here you are sorting the list two times, you are getting the output of the final sort only, if you want to perform the second sort over the sorted result of the first then you have to make use of ThenByDescending(if you want the second sort in descending order or else use ThenBy()) followed by OrderBy as like this:

var sortedItems = lstTest.OrderBy(o=>o.Quater).ThenByDescending(o=>o.Amount);

I have modified the code here in this example, you can check the output in the fiddle


问:
Break line after full stop when words near to 800
I have a long description , i want to break the string after every full stop when word count is greater then 800 .

Like count 800 characters THEN idenify the next occurrence of a ‘.’ break the line look for next 800 words then a full stop and then break the line again .

```<code>function TrimString($String, $Length){
    if(strlen($String)<=$Length){
        $stringValue=$String;
    } else {
        $new_l = strpos ($String , ".", $Length);
        $Length = $new_l+1;
        $stringValue=substr($String,0,$Length);
    }
    return $stringValue;
}
</code>```

i tried using this function but not working as expected .

```<code>$m=800;
echo TrimString(stripslashes($content),$m);
</code>```

Thanks in advance for your help .

答:
I understand your question like:

Search for the first . after each 800 signs and insert a new line.
If it's correct, so you have to loop through your string in your method like this example

```<code>function trimString($string, $length){
    $str_length = strlen($string);

    if ($str_length <= $length){
        return $string;
    }

    $from = 0;
    $string_value = '';

    // max amount of loops based on the length of $string and $length
    $loops = ceil($str_length / $length);

    for ($i = 1; $i <= $loops; $i++) {
        // $from could be 0 or the length of your last finding dot
        $tmp_length = $from + $length;

        if ($tmp_length > $str_length) {
            break;
        }

        // get the position of the dot after the calculated length
        $pos = strpos($string , ".", $tmp_length);

        // append the dot and a br-tag for a new line
        $string_value .= substr(substr($string, 0, $pos), $from) . ".<br/>";

        // set to the next position after the finding dot
        $from = $pos + 1;
    }

    return $string_value;
}

echo trimString("This is a test. This is not a test. This is a new test.", 5);
</code>```

Update #1

Because I was running in some errors with the function above I've made a new example and tested it with these cases. Now the last occurence of $search will be noticed too.

I hope this will help you

```<code>function trimString($haystack, $length, $search, $insert = ''){
    $str_length = strlen($haystack);

    if ($str_length <= $length){
        return $haystack;
    }

    $from = 0;
    $string_value = '';
    $search_after = $length;

    // find the last position of $search in the string
    $pos_last_dot = strrpos($haystack, $search);

    while ($search_after <= $pos_last_dot) {
        // get the position of $search after the last position
        $pos = strpos($haystack , $search, $search_after);

        // append the $search and the $insert for a new line
        $string_value .= substr(substr($haystack, 0, $pos), $from) . $search . $insert;

        // set the cursor to the next position after the finding $search
        $from = $pos + 1;

        // add the last occurence of $search
        if (($from + $length) >= $pos_last_dot && $pos != $pos_last_dot) {
            $string_value .= substr(substr($haystack, 0, $pos_last_dot), $from) . $search . $insert;
            break;
        }

        $search_after = $from + $length;
    }

    return $string_value;
}

echo trimString("This is a test. This is not a test. This is a new test This is a new test. foo. bar.", 10, ".", "<br/>");
</code>```

Body:
I have a long description , i want to break the string after every full stop when word count is greater then 800 .

Like count 800 characters THEN idenify the next occurrence of a ‘.’ break the line look for next 800 words then a full stop and then break the line again .

function TrimString($String, $Length){
    if(strlen($String)<=$Length){
        $stringValue=$String;
    } else {
        $new_l = strpos ($String , ".", $Length);
        $Length = $new_l+1;
        $stringValue=substr($String,0,$Length);
    }
    return $stringValue;
}

i tried using this function but not working as expected .

$m=800;
echo TrimString(stripslashes($content),$m);

Thanks in advance for your help .

Body:
I understand your question like:

Search for the first . after each 800 signs and insert a new line.
If it's correct, so you have to loop through your string in your method like this example

function trimString($string, $length){
    $str_length = strlen($string);

    if ($str_length <= $length){
        return $string;
    }

    $from = 0;
    $string_value = '';

    // max amount of loops based on the length of $string and $length
    $loops = ceil($str_length / $length);

    for ($i = 1; $i <= $loops; $i++) {
        // $from could be 0 or the length of your last finding dot
        $tmp_length = $from + $length;

        if ($tmp_length > $str_length) {
            break;
        }

        // get the position of the dot after the calculated length
        $pos = strpos($string , ".", $tmp_length);

        // append the dot and a br-tag for a new line
        $string_value .= substr(substr($string, 0, $pos), $from) . ".<br/>";

        // set to the next position after the finding dot
        $from = $pos + 1;
    }

    return $string_value;
}

echo trimString("This is a test. This is not a test. This is a new test.", 5);

Update #1

Because I was running in some errors with the function above I've made a new example and tested it with these cases. Now the last occurence of $search will be noticed too.

I hope this will help you

function trimString($haystack, $length, $search, $insert = ''){
    $str_length = strlen($haystack);

    if ($str_length <= $length){
        return $haystack;
    }

    $from = 0;
    $string_value = '';
    $search_after = $length;

    // find the last position of $search in the string
    $pos_last_dot = strrpos($haystack, $search);

    while ($search_after <= $pos_last_dot) {
        // get the position of $search after the last position
        $pos = strpos($haystack , $search, $search_after);

        // append the $search and the $insert for a new line
        $string_value .= substr(substr($haystack, 0, $pos), $from) . $search . $insert;

        // set the cursor to the next position after the finding $search
        $from = $pos + 1;

        // add the last occurence of $search
        if (($from + $length) >= $pos_last_dot && $pos != $pos_last_dot) {
            $string_value .= substr(substr($haystack, 0, $pos_last_dot), $from) . $search . $insert;
            break;
        }

        $search_after = $from + $length;
    }

    return $string_value;
}

echo trimString("This is a test. This is not a test. This is a new test This is a new test. foo. bar.", 10, ".", "<br/>");


问:
$week function and first day of week in aggregation
I use $project operator to extract week part from Date, then do grouping by weeks in aggregation pipeline:

```<code>{ $project: {
    year: { $year: [ "$datetime" ] },
    week: { $week: [ "$datetime" ] },
    ....
    }
},
....
{ $group: {
    _id: {
        year: "$year",
        week: "$week",
        },
        .....
    }
}
</code>```

But the $week operator I use, always counts Sunday as a first day of week, and we use Monday as first day of week in our location. Therefore, the results grouped by week are always incorrect for me.

The existing request in mongo tracking system seems to be unresolved for more than a year (is it really so rarely needed option?).

Any possible options are welcome. Maybe there is possibility to create some custom function in javascript and add/replace it somewhere?

答:
Trick: just change one line by subtracting one day from datetime

```<code>$project: {
    year: { $year: [ "$datetime" ] },
    week: { $week: {$subtract: ["$datetime", 86400000] } }, // <--- minus 1 day (in ms).
    ....
    }
</code>```

This works on new and old mongo versions.

Body:
I use $project operator to extract week part from Date, then do grouping by weeks in aggregation pipeline:

{ $project: {
    year: { $year: [ "$datetime" ] },
    week: { $week: [ "$datetime" ] },
    ....
    }
},
....
{ $group: {
    _id: {
        year: "$year",
        week: "$week",
        },
        .....
    }
}

But the $week operator I use, always counts Sunday as a first day of week, and we use Monday as first day of week in our location. Therefore, the results grouped by week are always incorrect for me.

The existing request in mongo tracking system seems to be unresolved for more than a year (is it really so rarely needed option?).

Any possible options are welcome. Maybe there is possibility to create some custom function in javascript and add/replace it somewhere?

Body:
Trick: just change one line by subtracting one day from datetime

$project: {
    year: { $year: [ "$datetime" ] },
    week: { $week: {$subtract: ["$datetime", 86400000] } }, // <--- minus 1 day (in ms).
    ....
    }

This works on new and old mongo versions.


问:
What is the result of the expression?
Does this code would work as expected in all browsers? Is there any notes in specification about it?

```<code>var attributes = this._attributes ? this._attributes : (this._attributes = []);
</code>```

I.e. if *this._attributes* not initialized, then new array will be created and that array will be assigned to *this._attributes* and to attributes.

答: No, I think unfortunately you may not access _attributes when it's undefined. So you have to check typeof attributes != "undefined".

ContentLicense: CC BY-SA 2.5

Title: What is the result of the expression?

Body:
Does this code would work as expected in all browsers? Is there any notes in specification about it?

var attributes = this._attributes ? this._attributes : (this._attributes = []);

I.e. if *this._attributes* not initialized, then new array will be created and that array will be assigned to *this._attributes* and to attributes.


问:
Using Like statement with DataView RowFIlter
I have a DataTable with some data and I want to filter with LIKE query so I have written a code like below and everything working fine, I'm generating the query and passing it to RowFilter object of DataView.

```<code>if (results.Count() == 2)
{
    if (results[0].ToString() == "" && results[1].ToString() != "")
    {
        searchString = String.Format("[" + searchBy + "] LIKE '%{0}'", results[1].ToString());
    }
    else if (results[0].ToString() != "" && results[1].ToString() == "")
    {
       searchString = String.Format("[" + searchBy + "] LIKE '{0}%'", results[0].ToString());
    }
    else if (results[0].ToString() != "" && results[1].ToString() != "")
    {
       searchString = String.Format("[" + searchBy + "] LIKE '{0}%{1}'", results[0].ToString(), results[1].ToString());
    }
}

if (searchString != "")
{
     DataView dv = new DataView(AccountList.Tables[0]);
     dv.RowFilter = searchString;
     var tab = dv.ToTable();
     DataSet data_set = new DataSet();
     data_set.Tables.Add(tab);
     ProcessDataSetAndLoadData(data_set);
}
</code>```

In above code segment is working fine except last else if condition, In that condition I'm getting the searchString like this,

[AccountCode] LIKE 'c%l'

When I passing this to RowFilter I'm getting the eror like below,

Error in Like operator: the string pattern 'c%l' is invalid.

From all other conditions I'm getting the searchString like below and those conditions are working fine.

```<code>[AccountCode] LIKE '%c%'
[AccountCode] LIKE 'c%'
[AccountCode] LIKE '%c
</code>```

My Question is why I'm getting the error only for the string like this
?.
    [AccountCode] LIKE 'c%l'

Please Advise me to complete my task.

答:
As @KiranBeladiya advise me, I generated searchString like below and it's working fine , I'm getting correct output so updating an answer because of future viewers.

```<code>searchString = String.Format("[" + searchBy + "] LIKE '"+ results[0].ToString() + "%' AND [" + searchBy + "] LIKE '" + "%" + results[1].ToString()+ "'");
</code>```

this returning string like below,

```<code>[AccountCode] LIKE 'c%' AND [AccountCode] LIKE '%l'
</code>```

So If pass this string to RowFilter object it is returning the same output of below string.

```<code>[AccountCode] LIKE 'c%l'
</code>```

Body:
I have a DataTable with some data and I want to filter with LIKE query so I have written a code like below and everything working fine, I'm generating the query and passing it to RowFilter object of DataView.

if (results.Count() == 2)
{
    if (results[0].ToString() == "" && results[1].ToString() != "")
    {
        searchString = String.Format("[" + searchBy + "] LIKE '%{0}'", results[1].ToString());
    }
    else if (results[0].ToString() != "" && results[1].ToString() == "")
    {
       searchString = String.Format("[" + searchBy + "] LIKE '{0}%'", results[0].ToString());
    }
    else if (results[0].ToString() != "" && results[1].ToString() != "")
    {
       searchString = String.Format("[" + searchBy + "] LIKE '{0}%{1}'", results[0].ToString(), results[1].ToString());
    }
}

if (searchString != "")
{
     DataView dv = new DataView(AccountList.Tables[0]);
     dv.RowFilter = searchString;
     var tab = dv.ToTable();
     DataSet data_set = new DataSet();
     data_set.Tables.Add(tab);
     ProcessDataSetAndLoadData(data_set);
}

In above code segment is working fine except last else if condition, In that condition I'm getting the searchString like this,

[AccountCode] LIKE 'c%l'

When I passing this to RowFilter I'm getting the eror like below,

Error in Like operator: the string pattern 'c%l' is invalid.

From all other conditions I'm getting the searchString like below and those conditions are working fine.

[AccountCode] LIKE '%c%'
[AccountCode] LIKE 'c%'
[AccountCode] LIKE '%c

My Question is why I'm getting the error only for the string like this
?.
    [AccountCode] LIKE 'c%l'

Please Advise me to complete my task.

Body:
As @KiranBeladiya advise me, I generated searchString like below and it's working fine , I'm getting correct output so updating an answer because of future viewers.

searchString = String.Format("[" + searchBy + "] LIKE '"+ results[0].ToString() + "%' AND [" + searchBy + "] LIKE '" + "%" + results[1].ToString()+ "'");

this returning string like below,

[AccountCode] LIKE 'c%' AND [AccountCode] LIKE '%l'

So If pass this string to RowFilter object it is returning the same output of below string.

[AccountCode] LIKE 'c%l'


问:
How can I reload recycleview?
This is my scenario:

Viewpager has two Fragments. Including HistoryFragment, which loads a RecycleView on creation.

I go ahead and add an item to the database from another Activity, however, it doesn't refresh the RecycleView, I need to close the app and load it again to see it refreshed.

How would you handle this?

RxJava? How would I notify the listener a changed occurred? Or do I simply reload the Fragment? (if so, how would I do that?)

答:
Use below code for reload whole fragment...</p>

```<code> FragmentTransaction ft = getFragmentManager().beginTransaction();
                                ft.detach(YourFragmentName.this).attach(YourFragmentName.this).commit();
</code>```

Title: How can I reload recycleview?

Body:
Use below code for reload whole fragment...

 FragmentTransaction ft = getFragmentManager().beginTransaction();
                                ft.detach(YourFragmentName.this).attach(YourFragmentName.this).commit();


问:
Different App name to be displayed in iTunes store
I have an apple app ready for sale in app store with the app name as    "product master".

I would like to add the string Oz to the app name as "Oz product master". Since the new name is too long, on the phone when installed, the app name is not shown fully below the app icon, it is displayed as "Oz pr.."

Is there a way to keep the app displayed as "product master" below the icon on iPhone and in the iTunes store, have the app displayed as "Oz product master"?

I have tried playing with fields "bundle identifier", "bundle display name" and "product name" but none of this is helping to have a different name displayed on iTunes store alone.

Can someone please advice how I achieve having different name on iTunes store only.

答:
The Product Name is what appears in your iphone only. The name in App Store is displayed following what you enter in appname in iTunesConnect.

Name in iTunes Store can be set as in the following image example:

See the red rectangle. Here you can have a long name that will appear in
iTunes Store.


问:
How I find numbers with repeating digits within a range
I'm trying to find all numbers within the range 000000000..999999999 that have at least 3 or more similar digits grouped together.

Here are examples of integers that pass: 112333678, 111234567, 122111876

Here are examples of integers that fail: 123456789, 122334455, 123123123

I ran this line in Ruby, and then my Macbook Pro with 16 GB of RAM ran out of memory: (000000000..999999999).to_a.select{|e| e.to_s =~ /(\d)\1+/}

答:
Let's count how many numbers with three or more repeating digits do you have. And let's focus on combinations where "1" is repeated 3 or more times.

To calculate this number we need to consider strings with only 3, only 4, ... all 10 occurences of "1".

That is cumulative binamial probabilty whcih can be computed like this:

```<code>cumulative = 0;
for k = 3:10
    cumulative = cumulative + (1/10)^k*(9/10)^(10-k)*nchoosek(10,k);
end
disp(cumulative)
</code>```

The answer is 0.0702. But in total you have 1010 different numbers. So, considering only repetition of "1" you got 0.0702 * 1010 numbers.

On your current implementation. I don't know much about Ruby, but i assume that to_a produces array of numbers from a range, so you asked to create array of 1010 numbers. Suppose that every number takes 8 bytes ( you cant store 9,999,999,999 in 4 bytes) so you ended up with 10^10*8/1024^3 ~= 74.5 GB.

Body:
Let's count how many numbers with three or more repeating digits do you have. And let's focus on combinations where "1" is repeated 3 or more times.

To calculate this number we need to consider strings with only 3, only 4, ... all 10 occurences of "1".

That is cumulative binamial probabilty whcih can be computed like this:

cumulative = 0;
for k = 3:10
    cumulative = cumulative + (1/10)^k*(9/10)^(10-k)*nchoosek(10,k);
end
disp(cumulative)

The answer is 0.0702. But in total you have 1010 different numbers. So, considering only repetition of "1" you got 0.0702 * 1010 numbers.

On your current implementation. I don't know much about Ruby, but i assume that to_a produces array of numbers from a range, so you asked to create array of 1010 numbers. Suppose that every number takes 8 bytes ( you cant store 9,999,999,999 in 4 bytes) so you ended up with 10^10*8/1024^3 ~= 74.5 GB.


答:
The app name on iTunes store has no effect on the app name displayed on the phone whatsoever. The app name to be displayed on the phone is the name of your Xcode project.
This means that you need to change the name of your Xcode project to whatever you want to be displayed on the phone and set the iTunes display name in iTunes connect

Title: Different App name to be displayed in iTunes store

Body:
I have an apple app ready for sale in app store with the app name as    "product master".

I would like to add the string Oz to the app name as "Oz product master". Since the new name is too long, on the phone when installed, the app name is not shown fully below the app icon, it is displayed as "Oz pr.."

Is there a way to keep the app displayed as "product master" below the icon on iPhone and in the iTunes store, have the app displayed as "Oz product master"?

I have tried playing with fields "bundle identifier", "bundle display name" and "product name" but none of this is helping to have a different name displayed on iTunes store alone.

Can someone please advice how I achieve having different name on iTunes store only.


问:
How to show link preview in TableviewCell iOS
In my iOS app, its like converting audio/text to text and displays in UITableviewCell.

But, If the user pasted link in chat textfield like "some text https://www.somelink.com/,  I want to show preview of that page like how facebook, Skype, etc other social networking apps doing, I have less idea about this.

I want to implement this in my UITableviewCell, Can anyone suggest me how can I move forward on this.

I am doing this app in Objective-C.

答:
Finally, I found solution for this. I have tried many ways to install the third party apis which is useful to show preview of website from a link, but, those are in swift, and my project is in Objective-C, but I was not able to install objective-c and swift pods into same project, got conflicts.

So, I just imported few XML/HTML parser classes and extracted the website title, image and description along with domain by passing the URL.

Following link helped me to extract website title, description, image and domain to show in preview.

https://github.com/myell0w/MTDURLPreview

I hope this will helps someone in future.


问:
Making a Database search engine like Google
I'm new to creating websites.I'm creating a Telephone directory search Engine.(Using PostgreSql,CGI scripts).My Database is having Name,Tel.No,City,State,Address.

Upto now I have created a search field like "google" where I can give any of the above Database entries and search.But now I want to give like "name+city+..." So that I can minimize the output entries.

答:
I don't happen to know the programming language you are using but I can give you an idea about the algorithyou may use.
it is a simple one actually and contains many (if-conditions)

like the follwoing :

if (name is provided) => bring matching results and store them in Set1
if (city is provided) => filter the results in Set1 and get only the matching ones and store them in S2
if (address is provided) => filter the results in S2 and get only the matching ones and store them in S3 ...etc.

This way you take the whole set of phone records and filter it one time after another until you have it filtered completely , and whatever the user enters will bring him some results

I mean if you enter one field you will get plenty of results and if you enter two fields you will have less results beacuse the results will be filtered twice and if he entered three fields the results will be filtered triple times and so on...

in short words ... Just use Filtering
sorry for the long answer


问:
Radiogroup in recyclerview
I am having a recyclerview where each list item has a radiogroup with 4 radio buttons. How can I store the state of each radiogroup correctly.
Here is my code. On scrolling up/down the states are incorrects. Thanks</p>

```<code>public class ElementListAdapter extends RecyclerView.Adapter<ElementListAdapter.ViewHolder> {

    private List<Element> elements = new ArrayList<>();
    private Context context;

    private int[] state;

    public ElementListAdapter(Context context, List<Element> elements) {
        this.context = context;
        this.elements = elements;

        this.state = new int[elements.size()];
        Arrays.fill(this.state, -1);
    }

    @Override
    public ElementListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_layout, parent,
                false);

        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final Element ele = elements.get(position);
        final String title = ele.getTitle();
        final String description = ele.getDescription();

        // Set text
        holder.tvTitle.setText(title);
        holder.tvDesciption.setText(description);

        if (ele.isHeader()) {
            holder.radioGroup.setVisibility(View.GONE);
        } else {
            holder.radioGroup.setVisibility(View.VISIBLE);
        }

        setRadio(holder, this.state[position]);

        holder.rb1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                state[position] = 0;
                setRadio(holder, state[position]);
            }
        });
        holder.rb2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                state[position] = 1;
                setRadio(holder, state[position]);
            }
        });
        holder.rb3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                state[position] = 2;
                setRadio(holder, state[position]);
            }
        });
        holder.rb4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                state[position] = 3;
                setRadio(holder, state[position]);
            }
        });

    }

    private void setRadio(final ViewHolder holder, int selection) {

        System.out.println("SELECT:" + selection);
        RadioButton b1 = holder.rb1;
        RadioButton b2 = holder.rb2;
        RadioButton b3 = holder.rb3;
        RadioButton b4 = holder.rb4;

        b1.setChecked(false);
        b2.setChecked(false);
        b3.setChecked(false);
        b4.setChecked(false);

        if (selection == 0) b1.setChecked(true);
        if (selection == 1) b2.setChecked(true);
        if (selection == 2) b3.setChecked(true);
        if (selection == 3) b4.setChecked(true);
    }

    @Override
    public int getItemCount() {
        return elements.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public View view;
        public TextView tvTitle;
        public TextView tvDesciption;

        public RadioGroup radioGroup;
        public RadioButton rb1, rb2, rb3, rb4;

        public ViewHolder(View itemView) {
            super(itemView);

            view = itemView;
            tvTitle = (TextView) itemView.findViewById(R.id.title);
            tvDesciption = (TextView) itemView.findViewById(R.id.description);

            radioGroup = (RadioGroup) itemView.findViewById(R.id.radioGroup);
            rb1 = (RadioButton) itemView.findViewById(R.id.rb1);
            rb2 = (RadioButton) itemView.findViewById(R.id.rb2);
            rb3 = (RadioButton) itemView.findViewById(R.id.rb3);
            rb4 = (RadioButton) itemView.findViewById(R.id.rb4);

        }
    }

}
</code>```

答:
this is what I did. In my onBindViewHolder

```<code>if(visualScore[position] == 1 ){
                holder.rg.check(R.id.rb_1);
            }else{
                if(audioScore[position] == 1){
                    holder.rg.check(R.id.rb_2);
                }else{
                    if(kinestScore[position] == 1){
                        holder.rg.check(R.id.rb_3);
                    }else{
                        holder.rg.clearCheck();
                    }
                }
            }
            holder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                    switch (checkedId) {
                        case (R.id.rb_1):
                            visualScore[position] = 1;
                            audioScore[position] = 0;
                            kinestScore[position] = 0;
                            break;
                        case (R.id.rb_2):
                            visualScore[position] = 0;
                            audioScore[position] = 1;
                            kinestScore[position] = 0;
                            break;
                        case (R.id.rb_3):
                            visualScore[position] = 0;
                            audioScore[position] = 0;
                            kinestScore[position] = 1;
                            break;
                    }
        });
</code>```

I declared all the score arrays as private global methods in the adapter class. Then, when submit button is clicked :

```<code>int v = 0, a = 0, k = 0;
                    for (int i = 0; i < Questions.length; i++){
                        v += visualScore[i];
                        a += audioScore[i];
                        k += kinestScore[i];
                    }
</code>```

Title: Radiogroup in recyclerview

Body:
I am having a recyclerview where each list item has a radiogroup with 4 radio buttons. How can I store the state of each radiogroup correctly.
Here is my code. On scrolling up/down the states are incorrects. Thanks

public class ElementListAdapter extends RecyclerView.Adapter<ElementListAdapter.ViewHolder> {

    private List<Element> elements = new ArrayList<>();
    private Context context;

    private int[] state;

    public ElementListAdapter(Context context, List<Element> elements) {
        this.context = context;
        this.elements = elements;

        this.state = new int[elements.size()];
        Arrays.fill(this.state, -1);
    }

    @Override
    public ElementListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_layout, parent,
                false);

        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final Element ele = elements.get(position);
        final String title = ele.getTitle();
        final String description = ele.getDescription();

        // Set text
        holder.tvTitle.setText(title);
        holder.tvDesciption.setText(description);

        if (ele.isHeader()) {
            holder.radioGroup.setVisibility(View.GONE);
        } else {
            holder.radioGroup.setVisibility(View.VISIBLE);
        }

        setRadio(holder, this.state[position]);

        holder.rb1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                state[position] = 0;
                setRadio(holder, state[position]);
            }
        });
        holder.rb2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                state[position] = 1;
                setRadio(holder, state[position]);
            }
        });
        holder.rb3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                state[position] = 2;
                setRadio(holder, state[position]);
            }
        });
        holder.rb4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                state[position] = 3;
                setRadio(holder, state[position]);
            }
        });

    }

    private void setRadio(final ViewHolder holder, int selection) {

        System.out.println("SELECT:" + selection);
        RadioButton b1 = holder.rb1;
        RadioButton b2 = holder.rb2;
        RadioButton b3 = holder.rb3;
        RadioButton b4 = holder.rb4;

        b1.setChecked(false);
        b2.setChecked(false);
        b3.setChecked(false);
        b4.setChecked(false);

        if (selection == 0) b1.setChecked(true);
        if (selection == 1) b2.setChecked(true);
        if (selection == 2) b3.setChecked(true);
        if (selection == 3) b4.setChecked(true);
    }

    @Override
    public int getItemCount() {
        return elements.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {

        public View view;
        public TextView tvTitle;
        public TextView tvDesciption;

        public RadioGroup radioGroup;
        public RadioButton rb1, rb2, rb3, rb4;

        public ViewHolder(View itemView) {
            super(itemView);

            view = itemView;
            tvTitle = (TextView) itemView.findViewById(R.id.title);
            tvDesciption = (TextView) itemView.findViewById(R.id.description);

            radioGroup = (RadioGroup) itemView.findViewById(R.id.radioGroup);
            rb1 = (RadioButton) itemView.findViewById(R.id.rb1);
            rb2 = (RadioButton) itemView.findViewById(R.id.rb2);
            rb3 = (RadioButton) itemView.findViewById(R.id.rb3);
            rb4 = (RadioButton) itemView.findViewById(R.id.rb4);

        }
    }

}

Body:
this is what I did. In my onBindViewHolder

if(visualScore[position] == 1 ){
                holder.rg.check(R.id.rb_1);
            }else{
                if(audioScore[position] == 1){
                    holder.rg.check(R.id.rb_2);
                }else{
                    if(kinestScore[position] == 1){
                        holder.rg.check(R.id.rb_3);
                    }else{
                        holder.rg.clearCheck();
                    }
                }
            }
            holder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                    switch (checkedId) {
                        case (R.id.rb_1):
                            visualScore[position] = 1;
                            audioScore[position] = 0;
                            kinestScore[position] = 0;
                            break;
                        case (R.id.rb_2):
                            visualScore[position] = 0;
                            audioScore[position] = 1;
                            kinestScore[position] = 0;
                            break;
                        case (R.id.rb_3):
                            visualScore[position] = 0;
                            audioScore[position] = 0;
                            kinestScore[position] = 1;
                            break;
                    }
        });

I declared all the score arrays as private global methods in the adapter class. Then, when submit button is clicked :

int v = 0, a = 0, k = 0;
                    for (int i = 0; i < Questions.length; i++){
                        v += visualScore[i];
                        a += audioScore[i];
                        k += kinestScore[i];
                    }


问:
Finding the longest border of a string
First, let me tell you what the border of a string is,

```<code>let x = "abacab"
let y = "ababab"
</code>```

The border of a string is a substring which is both a proper prefix and proper suffix of the string — "proper" meaning that the whole string does not count as a substring. The longest border of x is "ab". The longest border of y is "abab" (the prefix and suffix can overlap).

Another example:

In string "abcde hgrab abcde", then "abcde" is a prefix as well as suffix. Thus it is also the longest border of the string above.

How can I find the longest border of a string?

答:
Here's a Java implementation, based on the assumption that borders are proper substrings. (Otherwise the longest border is simply the string length.)

```<code>public static int findLongestBorder(String s) {
    int len = s.length();
    for (int i = len - 1; i > 0; i--) {
        String prefix = s.substring(0, i);
        String suffix = s.substring(len - i, len);
        if (prefix.equals(suffix)) {
            return i;
        }
    }
    return 0;
}
</code>```

This could be optimized a bit by starting with the string's character array and then comparing individual characters, but the idea behind the algorithm is clearer the way I wrote it.

Title: Finding the longest border of a string

Body:
First, let me tell you what the border of a string is,

let x = "abacab"
let y = "ababab"

The border of a string is a substring which is both a proper prefix and proper suffix of the string — "proper" meaning that the whole string does not count as a substring. The longest border of x is "ab". The longest border of y is "abab" (the prefix and suffix can overlap).

Another example:

In string "abcde hgrab abcde", then "abcde" is a prefix as well as suffix. Thus it is also the longest border of the string above.

How can I find the longest border of a string?

Body:
Here's a Java implementation, based on the assumption that borders are proper substrings. (Otherwise the longest border is simply the string length.)

public static int findLongestBorder(String s) {
    int len = s.length();
    for (int i = len - 1; i > 0; i--) {
        String prefix = s.substring(0, i);
        String suffix = s.substring(len - i, len);
        if (prefix.equals(suffix)) {
            return i;
        }
    }
    return 0;
}

This could be optimized a bit by starting with the string's character array and then comparing individual characters, but the idea behind the algorithm is clearer the way I wrote it.


问:
While importing Database file in myPHP Admin I'm getting error CREATE TABLE IF NOT EXISTS `wpcp_2_aiowps_event
While importing a Database file in myPHP Admin I'm getting the following error:

CREATE TABLE IF NOT EXISTS wpcp_2_aiowps_events (   id bigint(20) NOT NULL AUTO_INCREMENT,   event_type varchar(150) NOT NULL DEFAULT '',   username varchar(150) DEFAULT NULL,   user_id bigint(20) DEFAULT NULL,   event_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00',   ip_or_host varchar(100) DEFAULT NULL,   referer_info varchar(255) DEFAULT NULL,   url varchar(255) DEFAULT NULL,   country_code varchar(50) DEFAULT NULL,   event_data longtext,   PRIMARY KEY (id) ) TYPE=MyISAM AUTO_INCREMENT=1  MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'TYPE=MyISAM AUTO_INCREMENT=1' at line 13

How can I solve this and import the data successfully without any errors

答:
Note
      The older TYPE option was synonymous with ENGINE. TYPE was deprecated in MySQL 4.0 and removed in MySQL 5.5. When upgrading to MySQL 5.5 or later, you must convert existing applications that rely on TYPE to use ENGINE instead.

So you should use

```<code> CREATE TABLE IF NOT EXISTS wpcp_2_aiowps_events ( id bigint(20) NOT NULL AUTO_INCREMENT, event_type varchar(150) NOT NULL DEFAULT '', username varchar(150) DEFAULT NULL, user_id bigint(20) DEFAULT NULL, event_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00', ip_or_host varchar(100) DEFAULT NULL, referer_info varchar(255) DEFAULT NULL, url varchar(255) DEFAULT NULL, country_code varchar(50) DEFAULT NULL, event_data longtext, PRIMARY KEY (id) )ENGINE = MyISAM ;
</code>```

Body:
Note
      The older TYPE option was synonymous with ENGINE. TYPE was deprecated in MySQL 4.0 and removed in MySQL 5.5. When upgrading to MySQL 5.5 or later, you must convert existing applications that rely on TYPE to use ENGINE instead.

So you should use

 CREATE TABLE IF NOT EXISTS wpcp_2_aiowps_events ( id bigint(20) NOT NULL AUTO_INCREMENT, event_type varchar(150) NOT NULL DEFAULT '', username varchar(150) DEFAULT NULL, user_id bigint(20) DEFAULT NULL, event_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00', ip_or_host varchar(100) DEFAULT NULL, referer_info varchar(255) DEFAULT NULL, url varchar(255) DEFAULT NULL, country_code varchar(50) DEFAULT NULL, event_data longtext, PRIMARY KEY (id) )ENGINE = MyISAM ;


问:
NSIS uninstaller does not app files if not installed in program files
Hi the below program fails to delete app files if not in program files, I mean if user installs in some other location. After uninstall the registry values are deleted but not the files in the app folder. Any help would be much appreciated.</p>

```<code>RequestExecutionLevel admin
!define MULTIUSER_EXECUTIONLEVEL Admin
!define MULTIUSER_INSTALLMODE_COMMANDLINE
!include MultiUser.nsh
!include FileFunc.nsh

!ifndef PRODUCT_VERSION
  !define PRODUCT_VERSION "0.0.0.0"
!endif

!ifndef BUILD_TARGET
    !define BUILD_TARGET "Release"
!endif

!define OUT_FILE "PlaytestMateSetup.exe"

!if ${BUILD_TARGET} == "Debug"
!define PRODUCT_NAME "Playtest Mate 2.0 Debug"
!define PRODUCT_WEB_SITE "https://127.0.0.1:3000/"
!define MUI_ICON "..\PlaytestMate\Resources\Icons\IconRed.ico"
!endif

!if ${BUILD_TARGET} == "ReleaseTest"
!define PRODUCT_NAME "Playtest Mate 2.0 Staging"
!define PRODUCT_WEB_SITE "https://ca1-ptmstg01.ad.ea.com/"
!define MUI_ICON "..\PlaytestMate\Resources\Icons\IconBlue.ico"
!endif

!if ${BUILD_TARGET} == "Release"
!define PRODUCT_NAME "Playtest Mate 2.0"
!define PRODUCT_WEB_SITE "https://ca1-ptmprd01.ad.ea.com/"
!define MUI_ICON "..\PlaytestMate\Resources\Icons\IconBlack.ico"
!endif

!define PRODUCT_PUBLISHER "EA Digital Illusions CE AB"
!define RUN_REG_KEY "SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
!define PRODUCT_UNINST_KEY "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}"
!define PRODUCT_INST_KEY "SOFTWARE\${PRODUCT_NAME}"

;BUILD_DIR and CERT_PATH have to be in relation to the .nsi file
!define BUILD_DIR "..\..\Bin\${BUILD_TARGET}"

; PTM-1089
; CERT settings
!define CERT_FILE "ea_root.cer"
!define CERT_PATH "3rdparty\${CERT_FILE}"
; end PTM-1089

!include "MUI2.nsh"

; 64 bit support
!include x64.nsh

; MUI Settings
!define MUI_ABORTWARNING

!define MUI_UNICON "${NSISDIR}\Contrib\Graphics\Icons\modern-uninstall.ico"
; Welcome page
!insertmacro MUI_PAGE_WELCOME
; Directory page
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE "DirectoryLeave"
; Instfiles page
!insertmacro MUI_PAGE_DIRECTORY

!insertmacro MUI_PAGE_INSTFILES
; Finish page

Function DirectoryLeave

    # Show message box then take the user back to the Directory page.
    MessageBox MB_OK|MB_ICONEXCLAMATION "PTM consumes huge space because of the build sizes. We recommend to use a drive have maximum space other than C Drive"

FunctionEnd

Function createDesktopShortcut
  CreateShortCut "$DESKTOP\${PRODUCT_NAME}.lnk" "$INSTDIR\PlaytestMate.exe" "-shortcut"
FunctionEnd

!define MUI_FINISHPAGE_SHOWREADME ""
!define MUI_FINISHPAGE_SHOWREADME_TEXT "Create Desktop Shortcut"
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION createDesktopShortcut

; Option to run PTM after install
!define MUI_FINISHPAGE_RUN "$INSTDIR\PlaytestMate.exe"

!insertmacro MUI_PAGE_FINISH

; Uninstaller pages
!define MUI_PAGE_CUSTOMFUNCTION_SHOW un.ModifyUnWelcome
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE un.LeaveUnWelcome
!insertmacro MUI_UNPAGE_WELCOME
!insertmacro MUI_UNPAGE_INSTFILES

; Language files
!insertmacro MUI_LANGUAGE "English"

; MUI end ------

Name "${PRODUCT_NAME}"
OutFile "${OUT_FILE}"
VIProductVersion ${PRODUCT_VERSION}

VIAddVersionKey ProductName "${PRODUCT_NAME} Installer"
VIAddVersionKey CompanyName "${PRODUCT_PUBLISHER}"
VIAddVersionKey FileDescription "Installs ${PRODUCT_NAME}"
VIAddVersionKey FileVersion ${PRODUCT_VERSION}
VIAddVersionKey ProductVersion ${PRODUCT_VERSION}
VIAddVersionKey OriginalFilename "${OUT_FILE}"

InstallDir "$PROGRAMFILES\${PRODUCT_NAME}"

ShowInstDetails show
ShowUnInstDetails show

Function .onInit
  !insertmacro MULTIUSER_INIT
  ReadRegStr $R0 HKLM "${PRODUCT_UNINST_KEY}" "QuietUninstallString"
  StrCmp $R0 "" done uninst

  ;Run the uninstaller
  uninst:
  ClearErrors
  Exec '$R0' ; instead of the ExecWait line

  done:
  ${If} ${RunningX64}
    ; disable registry redirection (enable access to 64-bit portion of registry)
    SetRegView 64
    ; change install dir
    StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCT_NAME}"
  ${Else}
    MessageBox MB_OK "${PRODUCT_NAME} needs 64-bit Windows"
    Abort
  ${EndIf}

  UserInfo::GetAccountType
  pop $0
  ${If} $0 != "admin" ;Require admin rights on NT4+
    MessageBox mb_iconstop "${PRODUCT_NAME} requires Administrator privileges"
    SetErrorLevel 740 ;ERROR_ELEVATION_REQUIRED
    Quit
  ${EndIf}
FunctionEnd

Function .onInstSuccess
  RMDir /r "$LOCALAPPDATA\${PRODUCT_NAME}"

  IfSilent startlauncher finished
  startlauncher:
    Exec '"$INSTDIR\PlaytestMate.exe"'
  finished:
FunctionEnd

Section "MainSection" SEC01
  Call EnsureNotRunning

  Delete "$INSTDIR\*.*"

  SetOutPath "$INSTDIR"
  SetOverwrite try
  File "${BUILD_DIR}\Builds.Core.dll"
  File "${BUILD_DIR}\Builds.Core.Service.Platform.Origin.dll"
  File "${BUILD_DIR}\EngineIoClientDotNet.dll"
  File "${BUILD_DIR}\INIFileParser.dll"
  File "${BUILD_DIR}\log4net.config"
  File "${BUILD_DIR}\log4net.dll"
  File "${BUILD_DIR}\log4net.xml"
  File "${BUILD_DIR}\Newtonsoft.Json.dll"
  File "${BUILD_DIR}\Newtonsoft.Json.xml"
  File "${BUILD_DIR}\PlaytestMate.Core.dll"
  File "${BUILD_DIR}\PlaytestMate.Core.dll.config"
  File "${BUILD_DIR}\PlaytestMate.exe"
  File "${BUILD_DIR}\PlaytestMate.exe.config"
  File "${BUILD_DIR}\SocketIoClientDotNet.dll"
  File "${BUILD_DIR}\WebSocket4Net.dll"
  ; PTM-1089
  File "${CERT_PATH}"
  ; end PTM-1089

  CreateDirectory "$SMPROGRAMS\${PRODUCT_NAME}"
  CreateShortCut "$SMPROGRAMS\${PRODUCT_NAME}\${PRODUCT_NAME}.lnk" "$INSTDIR\PlaytestMate.exe" "-shortcut"
  CreateShortCut "$INSTDIR\Show log files.lnk" "$WINDIR\explorer.exe" "%USERPROFILE%\Documents\PlaytestMate" "$WINDIR\system32\imageres.dll" 172

  ; PTM-1089 you can remove this once we get a proper cert
  Push "$INSTDIR\${CERT_FILE}"
  Call AddCertificateToStore
  Pop $0
  ${If} $0 != success
     MessageBox MB_OK "EA Root Certificate import failed: $0"
  ${EndIf}
  ; end PTM-1089
SectionEnd

Section -AdditionalIcons
  WriteIniStr "$INSTDIR\${PRODUCT_NAME}.URL" "InternetShortcut" "URL" "${PRODUCT_WEB_SITE}"
  CreateShortCut "$SMPROGRAMS\${PRODUCT_NAME}\Website.lnk" "$INSTDIR\${PRODUCT_NAME}.url"
  CreateShortCut "$SMPROGRAMS\${PRODUCT_NAME}\Uninstall.lnk" "$INSTDIR\uninstall.exe"
SectionEnd

Section -Post
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "DisplayName" "$(^Name)"
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "QuietUninstallString" "$\"$INSTDIR\uninstall.exe$\" /S"
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "InstallLocation" "$INSTDIR"
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "DisplayIcon" "$INSTDIR\PlaytestMate.exe"
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "DisplayVersion" "${PRODUCT_VERSION}"
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "Publisher" "${PRODUCT_PUBLISHER}"

  WriteRegStr HKLM "${PRODUCT_INST_KEY}" "InstallPath" "$INSTDIR\PlaytestMate.exe"
  WriteRegStr HKLM "${PRODUCT_INST_KEY}" "Version" "${PRODUCT_VERSION}"

  ; estimated size
  ${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2
  IntFmt $0 "0x%08X" $0
  WriteRegDWORD HKLM "${PRODUCT_UNINST_KEY}" "EstimatedSize" "$0"

  WriteRegDWORD HKLM "${PRODUCT_UNINST_KEY}" "VersionMajor" 2
  WriteRegDWORD HKLM "${PRODUCT_UNINST_KEY}" "VersionMinor" 0

  ; Runs PTM on Windows start-up
  WriteRegStr HKLM "${RUN_REG_KEY}" "PlaytestMate" "$INSTDIR\PlaytestMate.exe"

  WriteUninstaller "$INSTDIR\uninstall.exe"
SectionEnd

!macro NOTRUNNINGMACRO un
Function ${un}EnsureNotRunning
  ${DisableX64FSRedirection}
  SetOutPath "$INSTDIR"
  File ".\killProcess.ps1"
  nsExec::ExecToStack 'Powershell.exe -inputformat none -noprofile ".\killProcess.ps1"'

  ${EnableX64FSRedirection}

  Sleep 500
  performCheck:
  System::Call 'kernel32::OpenMutex(i 0x100000, b 0, t "Global\{${BUILD_TARGET} }") i .R0'
  IntCmp $R0 0 backupCheck isRunning isRunning
  backupCheck:
  System::Call 'kernel32::OpenMutex(i 0x100000, b 0, t "Global\{0}") i .R0'
  IntCmp $R0 0 notRunning isRunning isRunning
  isRunning:
  System::Call 'kernel32::CloseHandle(i $R0)'
  MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION "${PRODUCT_NAME} is running. Please close it first" /SD IDCANCEL IDOK performCheck
  Abort
  notRunning:
FunctionEnd
!macroend

!insertmacro NOTRUNNINGMACRO ""
!insertmacro NOTRUNNINGMACRO "un."

Function un.onUninstSuccess
  HideWindow
  IfSilent finished
    MessageBox MB_ICONINFORMATION|MB_OK "${PRODUCT_NAME} was successfully removed from your computer."
  finished:
FunctionEnd

Function un.onInit
  !insertmacro MULTIUSER_UNINIT

  ${If} ${RunningX64}
    ; disable registry redirection (enable access to 64-bit portion of registry)
    SetRegView 64
    ; change install dir
    StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCT_NAME}"
  ${EndIf}
FunctionEnd

Var keepUserSettingsCheckbox
Var keepUserSettingsBool

Function un.ModifyUnWelcome
  ${NSD_CreateCheckbox} 120u -18u 50% 12u "Remove user settings"
  Pop $keepUserSettingsCheckbox
  SetCtlColors $keepUserSettingsCheckbox "" ${MUI_BGCOLOR}
  ${NSD_Check} $keepUserSettingsCheckbox ; Check it by default
FunctionEnd

Function un.LeaveUnWelcome
  ${NSD_GetState} $keepUserSettingsCheckbox $0
  ${If} $0 <> 0
    StrCpy $keepUserSettingsBool "True"
  ${Else}
    StrCpy $keepUserSettingsBool "False"
${EndIf}
FunctionEnd

Function un.GetMyDocs
  ReadRegStr $0 HKCU \
             "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" \
             Personal
FunctionEnd

Section Uninstall
  Call un.EnsureNotRunning

  RMDir /r "$INSTDIR"
  RMDir /r "$INSTDIR\crashDumps"
  Delete "$SMPROGRAMS\${PRODUCT_NAME}\*.*"
  RMDir /r "$SMPROGRAMS\${PRODUCT_NAME}"
  RMDir /r "$PROGRAMFILES64\${PRODUCT_NAME}"

  StrCmp $keepUserSettingsBool "True" 0 +11
  Delete "$LOCALAPPDATA\${PRODUCT_NAME}\*.*"
  RMDir /r "$LOCALAPPDATA\${PRODUCT_NAME}"

  Call un.GetMyDocs
  RMDir /r "$0\${PRODUCT_NAME}"

  Delete "$DESKTOP\${PRODUCT_NAME}.lnk"

  DeleteRegKey HKLM "${PRODUCT_UNINST_KEY}"
  DeleteRegKey HKLM "${PRODUCT_INST_KEY}"
  DeleteRegValue HKLM "${RUN_REG_KEY}" "${PRODUCT_NAME}"

  SetAutoClose true
SectionEnd
</code>```

答:
With just a quick glance at your document here. Maybe try using this were applicable.. Don't quote me on this; I'm tired and should get some sleep.. Lol. Good luck.</p>

```<code>WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "UninstallString" `"$INSTDIR\uninstall.exe"`
WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "QuietUninstallString" `"$INSTDIR\uninstall.exe" /S`
</code>```

Body:
Hi the below program fails to delete app files if not in program files, I mean if user installs in some other location. After uninstall the registry values are deleted but not the files in the app folder. Any help would be much appreciated.

RequestExecutionLevel admin
!define MULTIUSER_EXECUTIONLEVEL Admin
!define MULTIUSER_INSTALLMODE_COMMANDLINE
!include MultiUser.nsh
!include FileFunc.nsh

!ifndef PRODUCT_VERSION
  !define PRODUCT_VERSION "0.0.0.0"
!endif

!ifndef BUILD_TARGET
    !define BUILD_TARGET "Release"
!endif

!define OUT_FILE "PlaytestMateSetup.exe"

!if ${BUILD_TARGET} == "Debug"
!define PRODUCT_NAME "Playtest Mate 2.0 Debug"
!define PRODUCT_WEB_SITE "https://127.0.0.1:3000/"
!define MUI_ICON "..\PlaytestMate\Resources\Icons\IconRed.ico"
!endif

!if ${BUILD_TARGET} == "ReleaseTest"
!define PRODUCT_NAME "Playtest Mate 2.0 Staging"
!define PRODUCT_WEB_SITE "https://ca1-ptmstg01.ad.ea.com/"
!define MUI_ICON "..\PlaytestMate\Resources\Icons\IconBlue.ico"
!endif

!if ${BUILD_TARGET} == "Release"
!define PRODUCT_NAME "Playtest Mate 2.0"
!define PRODUCT_WEB_SITE "https://ca1-ptmprd01.ad.ea.com/"
!define MUI_ICON "..\PlaytestMate\Resources\Icons\IconBlack.ico"
!endif

!define PRODUCT_PUBLISHER "EA Digital Illusions CE AB"
!define RUN_REG_KEY "SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
!define PRODUCT_UNINST_KEY "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}"
!define PRODUCT_INST_KEY "SOFTWARE\${PRODUCT_NAME}"

;BUILD_DIR and CERT_PATH have to be in relation to the .nsi file
!define BUILD_DIR "..\..\Bin\${BUILD_TARGET}"

; PTM-1089
; CERT settings
!define CERT_FILE "ea_root.cer"
!define CERT_PATH "3rdparty\${CERT_FILE}"
; end PTM-1089

!include "MUI2.nsh"

; 64 bit support
!include x64.nsh

; MUI Settings
!define MUI_ABORTWARNING

!define MUI_UNICON "${NSISDIR}\Contrib\Graphics\Icons\modern-uninstall.ico"
; Welcome page
!insertmacro MUI_PAGE_WELCOME
; Directory page
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE "DirectoryLeave"
; Instfiles page
!insertmacro MUI_PAGE_DIRECTORY

!insertmacro MUI_PAGE_INSTFILES
; Finish page

Function DirectoryLeave

    # Show message box then take the user back to the Directory page.
    MessageBox MB_OK|MB_ICONEXCLAMATION "PTM consumes huge space because of the build sizes. We recommend to use a drive have maximum space other than C Drive"

FunctionEnd

Function createDesktopShortcut
  CreateShortCut "$DESKTOP\${PRODUCT_NAME}.lnk" "$INSTDIR\PlaytestMate.exe" "-shortcut"
FunctionEnd

!define MUI_FINISHPAGE_SHOWREADME ""
!define MUI_FINISHPAGE_SHOWREADME_TEXT "Create Desktop Shortcut"
!define MUI_FINISHPAGE_SHOWREADME_FUNCTION createDesktopShortcut

; Option to run PTM after install
!define MUI_FINISHPAGE_RUN "$INSTDIR\PlaytestMate.exe"

!insertmacro MUI_PAGE_FINISH

; Uninstaller pages
!define MUI_PAGE_CUSTOMFUNCTION_SHOW un.ModifyUnWelcome
!define MUI_PAGE_CUSTOMFUNCTION_LEAVE un.LeaveUnWelcome
!insertmacro MUI_UNPAGE_WELCOME
!insertmacro MUI_UNPAGE_INSTFILES

; Language files
!insertmacro MUI_LANGUAGE "English"

; MUI end ------

Name "${PRODUCT_NAME}"
OutFile "${OUT_FILE}"
VIProductVersion ${PRODUCT_VERSION}

VIAddVersionKey ProductName "${PRODUCT_NAME} Installer"
VIAddVersionKey CompanyName "${PRODUCT_PUBLISHER}"
VIAddVersionKey FileDescription "Installs ${PRODUCT_NAME}"
VIAddVersionKey FileVersion ${PRODUCT_VERSION}
VIAddVersionKey ProductVersion ${PRODUCT_VERSION}
VIAddVersionKey OriginalFilename "${OUT_FILE}"

InstallDir "$PROGRAMFILES\${PRODUCT_NAME}"

ShowInstDetails show
ShowUnInstDetails show

Function .onInit
  !insertmacro MULTIUSER_INIT
  ReadRegStr $R0 HKLM "${PRODUCT_UNINST_KEY}" "QuietUninstallString"
  StrCmp $R0 "" done uninst

  ;Run the uninstaller
  uninst:
  ClearErrors
  Exec '$R0' ; instead of the ExecWait line

  done:
  ${If} ${RunningX64}
    ; disable registry redirection (enable access to 64-bit portion of registry)
    SetRegView 64
    ; change install dir
    StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCT_NAME}"
  ${Else}
    MessageBox MB_OK "${PRODUCT_NAME} needs 64-bit Windows"
    Abort
  ${EndIf}

  UserInfo::GetAccountType
  pop $0
  ${If} $0 != "admin" ;Require admin rights on NT4+
    MessageBox mb_iconstop "${PRODUCT_NAME} requires Administrator privileges"
    SetErrorLevel 740 ;ERROR_ELEVATION_REQUIRED
    Quit
  ${EndIf}
FunctionEnd

Function .onInstSuccess
  RMDir /r "$LOCALAPPDATA\${PRODUCT_NAME}"

  IfSilent startlauncher finished
  startlauncher:
    Exec '"$INSTDIR\PlaytestMate.exe"'
  finished:
FunctionEnd

Section "MainSection" SEC01
  Call EnsureNotRunning

  Delete "$INSTDIR\*.*"

  SetOutPath "$INSTDIR"
  SetOverwrite try
  File "${BUILD_DIR}\Builds.Core.dll"
  File "${BUILD_DIR}\Builds.Core.Service.Platform.Origin.dll"
  File "${BUILD_DIR}\EngineIoClientDotNet.dll"
  File "${BUILD_DIR}\INIFileParser.dll"
  File "${BUILD_DIR}\log4net.config"
  File "${BUILD_DIR}\log4net.dll"
  File "${BUILD_DIR}\log4net.xml"
  File "${BUILD_DIR}\Newtonsoft.Json.dll"
  File "${BUILD_DIR}\Newtonsoft.Json.xml"
  File "${BUILD_DIR}\PlaytestMate.Core.dll"
  File "${BUILD_DIR}\PlaytestMate.Core.dll.config"
  File "${BUILD_DIR}\PlaytestMate.exe"
  File "${BUILD_DIR}\PlaytestMate.exe.config"
  File "${BUILD_DIR}\SocketIoClientDotNet.dll"
  File "${BUILD_DIR}\WebSocket4Net.dll"
  ; PTM-1089
  File "${CERT_PATH}"
  ; end PTM-1089

  CreateDirectory "$SMPROGRAMS\${PRODUCT_NAME}"
  CreateShortCut "$SMPROGRAMS\${PRODUCT_NAME}\${PRODUCT_NAME}.lnk" "$INSTDIR\PlaytestMate.exe" "-shortcut"
  CreateShortCut "$INSTDIR\Show log files.lnk" "$WINDIR\explorer.exe" "%USERPROFILE%\Documents\PlaytestMate" "$WINDIR\system32\imageres.dll" 172

  ; PTM-1089 you can remove this once we get a proper cert
  Push "$INSTDIR\${CERT_FILE}"
  Call AddCertificateToStore
  Pop $0
  ${If} $0 != success
     MessageBox MB_OK "EA Root Certificate import failed: $0"
  ${EndIf}
  ; end PTM-1089
SectionEnd

Section -AdditionalIcons
  WriteIniStr "$INSTDIR\${PRODUCT_NAME}.URL" "InternetShortcut" "URL" "${PRODUCT_WEB_SITE}"
  CreateShortCut "$SMPROGRAMS\${PRODUCT_NAME}\Website.lnk" "$INSTDIR\${PRODUCT_NAME}.url"
  CreateShortCut "$SMPROGRAMS\${PRODUCT_NAME}\Uninstall.lnk" "$INSTDIR\uninstall.exe"
SectionEnd

Section -Post
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "DisplayName" "$(^Name)"
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\""
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "QuietUninstallString" "$\"$INSTDIR\uninstall.exe$\" /S"
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "InstallLocation" "$INSTDIR"
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "DisplayIcon" "$INSTDIR\PlaytestMate.exe"
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "DisplayVersion" "${PRODUCT_VERSION}"
  WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "Publisher" "${PRODUCT_PUBLISHER}"

  WriteRegStr HKLM "${PRODUCT_INST_KEY}" "InstallPath" "$INSTDIR\PlaytestMate.exe"
  WriteRegStr HKLM "${PRODUCT_INST_KEY}" "Version" "${PRODUCT_VERSION}"

  ; estimated size
  ${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2
  IntFmt $0 "0x%08X" $0
  WriteRegDWORD HKLM "${PRODUCT_UNINST_KEY}" "EstimatedSize" "$0"

  WriteRegDWORD HKLM "${PRODUCT_UNINST_KEY}" "VersionMajor" 2
  WriteRegDWORD HKLM "${PRODUCT_UNINST_KEY}" "VersionMinor" 0

  ; Runs PTM on Windows start-up
  WriteRegStr HKLM "${RUN_REG_KEY}" "PlaytestMate" "$INSTDIR\PlaytestMate.exe"

  WriteUninstaller "$INSTDIR\uninstall.exe"
SectionEnd

!macro NOTRUNNINGMACRO un
Function ${un}EnsureNotRunning
  ${DisableX64FSRedirection}
  SetOutPath "$INSTDIR"
  File ".\killProcess.ps1"
  nsExec::ExecToStack 'Powershell.exe -inputformat none -noprofile ".\killProcess.ps1"'

  ${EnableX64FSRedirection}

  Sleep 500
  performCheck:
  System::Call 'kernel32::OpenMutex(i 0x100000, b 0, t "Global\{${BUILD_TARGET} }") i .R0'
  IntCmp $R0 0 backupCheck isRunning isRunning
  backupCheck:
  System::Call 'kernel32::OpenMutex(i 0x100000, b 0, t "Global\{0}") i .R0'
  IntCmp $R0 0 notRunning isRunning isRunning
  isRunning:
  System::Call 'kernel32::CloseHandle(i $R0)'
  MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION "${PRODUCT_NAME} is running. Please close it first" /SD IDCANCEL IDOK performCheck
  Abort
  notRunning:
FunctionEnd
!macroend

!insertmacro NOTRUNNINGMACRO ""
!insertmacro NOTRUNNINGMACRO "un."

Function un.onUninstSuccess
  HideWindow
  IfSilent finished
    MessageBox MB_ICONINFORMATION|MB_OK "${PRODUCT_NAME} was successfully removed from your computer."
  finished:
FunctionEnd

Function un.onInit
  !insertmacro MULTIUSER_UNINIT

  ${If} ${RunningX64}
    ; disable registry redirection (enable access to 64-bit portion of registry)
    SetRegView 64
    ; change install dir
    StrCpy $INSTDIR "$PROGRAMFILES64\${PRODUCT_NAME}"
  ${EndIf}
FunctionEnd

Var keepUserSettingsCheckbox
Var keepUserSettingsBool

Function un.ModifyUnWelcome
  ${NSD_CreateCheckbox} 120u -18u 50% 12u "Remove user settings"
  Pop $keepUserSettingsCheckbox
  SetCtlColors $keepUserSettingsCheckbox "" ${MUI_BGCOLOR}
  ${NSD_Check} $keepUserSettingsCheckbox ; Check it by default
FunctionEnd

Function un.LeaveUnWelcome
  ${NSD_GetState} $keepUserSettingsCheckbox $0
  ${If} $0 <> 0
    StrCpy $keepUserSettingsBool "True"
  ${Else}
    StrCpy $keepUserSettingsBool "False"
${EndIf}
FunctionEnd

Function un.GetMyDocs
  ReadRegStr $0 HKCU \
             "SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" \
             Personal
FunctionEnd

Section Uninstall
  Call un.EnsureNotRunning

  RMDir /r "$INSTDIR"
  RMDir /r "$INSTDIR\crashDumps"
  Delete "$SMPROGRAMS\${PRODUCT_NAME}\*.*"
  RMDir /r "$SMPROGRAMS\${PRODUCT_NAME}"
  RMDir /r "$PROGRAMFILES64\${PRODUCT_NAME}"

  StrCmp $keepUserSettingsBool "True" 0 +11
  Delete "$LOCALAPPDATA\${PRODUCT_NAME}\*.*"
  RMDir /r "$LOCALAPPDATA\${PRODUCT_NAME}"

  Call un.GetMyDocs
  RMDir /r "$0\${PRODUCT_NAME}"

  Delete "$DESKTOP\${PRODUCT_NAME}.lnk"

  DeleteRegKey HKLM "${PRODUCT_UNINST_KEY}"
  DeleteRegKey HKLM "${PRODUCT_INST_KEY}"
  DeleteRegValue HKLM "${RUN_REG_KEY}" "${PRODUCT_NAME}"

  SetAutoClose true
SectionEnd

Body:
With just a quick glance at your document here. Maybe try using this were applicable.. Don't quote me on this; I'm tired and should get some sleep.. Lol. Good luck.

WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "UninstallString" `"$INSTDIR\uninstall.exe"`
WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "QuietUninstallString" `"$INSTDIR\uninstall.exe" /S`


问:
Updating profiles with the LinkedIn REST API
Is it possible to update a profile's Education, Specialities and/or Experience via the LinkedIn API?

I am able to make normal GET calls just fine.

I ask here because documentation on their website is not yielding any results and Stackoverflow would have more practical experience with it.

EDIT: Further searching has led me to find that this is indeed not possible. I will leave this question up for others to see in case they are wondering about the same thing.

答:
In the newer API's you can.
Here is the latest API link:
https://developer.linkedin.com/docs/guide/v2/people/profile-edit-api

So, yes, now you can.


问:
Regexp replace all symbols excluding # and @
I am not super confident with using regexp, but my end goal is to have something that is removing all symbols excluding @ and #.

What I have now is [\\p{P}\\d].
It works fine but it also removes @ and # which I need to keep.

Here is the sample input string:

```<code>^Hello, my #friend @Даниил%% 中英 字 典!!.
</code>```

that I am trying to change into

```<code>Hello my #friend @Даниил 中英 字 典
</code>```

答:
Capture the symbols you need to keep and replace with $1 backreference to restore the captured part in the resulting string:

```<code>package main

import (
    "fmt"
    "regexp"
)

func main() {
    s := "^Hello, my #friend @Даниил%% 中英 字 典!!."
    re := regexp.MustCompile(`([#@])|[\p{P}\p{S}\d]`)
    s = re.ReplaceAllString(s, "$1")
    fmt.Println(s)
}
</code>```

See this Go demo printing Hello my #friend @Даниил 中英 字 典.

Note that ^ does not belong to the \p{P}  category, thus, I added \p{S} one.

The pattern is ([#@])|[\p{P}\p{S}\d], see its online demo.

Details:

([#@]) - Capturing group 1 (referred to with $1 / ${1} from the replacement pattern) matching a # or @

| - or

[\p{P}\p{S}\d] - a punctuation, symbol or digit char.

Body:
I am not super confident with using regexp, but my end goal is to have something that is removing all symbols excluding @ and #.

What I have now is [\\p{P}\\d].
It works fine but it also removes @ and # which I need to keep.

Here is the sample input string:

^Hello, my #friend @Даниил%% 中英 字 典!!.

that I am trying to change into

Hello my #friend @Даниил 中英 字 典

Body:
Capture the symbols you need to keep and replace with $1 backreference to restore the captured part in the resulting string:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    s := "^Hello, my #friend @Даниил%% 中英 字 典!!."
    re := regexp.MustCompile(`([#@])|[\p{P}\p{S}\d]`)
    s = re.ReplaceAllString(s, "$1")
    fmt.Println(s)
}

See this Go demo printing Hello my #friend @Даниил 中英 字 典.

Note that ^ does not belong to the \p{P}  category, thus, I added \p{S} one.

The pattern is ([#@])|[\p{P}\p{S}\d], see its online demo.

Details:

([#@]) - Capturing group 1 (referred to with $1 / ${1} from the replacement pattern) matching a # or @

| - or

[\p{P}\p{S}\d] - a punctuation, symbol or digit char.


问:
Searching by has_parent and another query elasticsearch
I have a parent/child relationship and I need to filter children based on parent ID and child properties. However, I can filter children by parent ID but I can not filter by any child properties.

Here is my search:

```<code>{
    "query": {
        "bool": {
            "should": [
                {
                    "match": {
                        "name": "beer"
                    }
                }
            ],
            "must": [
                {
                    "has_parent": {
                        "type": "pubs",
                        "score_mode": "score",
                        "query": {
                            "ids": {
                                "values": ["AVx3Ruk03JWWfjjJokHs"]
                            }
                        }
                    }
                }
            ]
        }
    }
}
</code>```

But I was given results like this:

```<code>{
    "took": 98,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 0.5,
        "hits": [
            {
                "_index": "wildwest",
                "_type": "drinks",
                "_id": "AVx3Xc8g3JWWfjjJokHx",
                "_score": 0.5,
                "_routing": "AVx3Ruk03JWWfjjJokHs",
                "_parent": "AVx3Ruk03JWWfjjJokHs",
                "_source": {
                    "name": "Milk",
                    "description": "Milk description",
                    "unit_price": 2.9,
                    "amount": 20
                }
            }
        ]
    }
}
</code>```

What am I doing wrong?
I'm using Elasticsearch 2.4.

NOTE: I tried to put all filters inside should query, but I was given drinks from another pub. Changing to must query nothing is returned.

答:
Query </p>

```<code>POST parent_child_index/drinks/_search
    {
        "query": {
            "bool": {
                "must": [{
                        "term": {
                            "name": {
                                "value": "milk"
                            }
                        }
                    },
                    {
                        "has_parent": {
                            "type": "pubs",
                            "score_mode": "score",
                            "query": {
                                "ids": {
                                    "values": ["AVx8F96XkBWZrYmFvTpK"]
                                }
                            }
                        }
                    }
                ]
            }
        }
    }
</code>```

Body:
I have a parent/child relationship and I need to filter children based on parent ID and child properties. However, I can filter children by parent ID but I can not filter by any child properties.

Here is my search:

{
    "query": {
        "bool": {
            "should": [
                {
                    "match": {
                        "name": "beer"
                    }
                }
            ],
            "must": [
                {
                    "has_parent": {
                        "type": "pubs",
                        "score_mode": "score",
                        "query": {
                            "ids": {
                                "values": ["AVx3Ruk03JWWfjjJokHs"]
                            }
                        }
                    }
                }
            ]
        }
    }
}

But I was given results like this:

{
    "took": 98,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 1,
        "max_score": 0.5,
        "hits": [
            {
                "_index": "wildwest",
                "_type": "drinks",
                "_id": "AVx3Xc8g3JWWfjjJokHx",
                "_score": 0.5,
                "_routing": "AVx3Ruk03JWWfjjJokHs",
                "_parent": "AVx3Ruk03JWWfjjJokHs",
                "_source": {
                    "name": "Milk",
                    "description": "Milk description",
                    "unit_price": 2.9,
                    "amount": 20
                }
            }
        ]
    }
}

What am I doing wrong?
I'm using Elasticsearch 2.4.

NOTE: I tried to put all filters inside should query, but I was given drinks from another pub. Changing to must query nothing is returned.

Body:
Query

POST parent_child_index/drinks/_search
    {
        "query": {
            "bool": {
                "must": [{
                        "term": {
                            "name": {
                                "value": "milk"
                            }
                        }
                    },
                    {
                        "has_parent": {
                            "type": "pubs",
                            "score_mode": "score",
                            "query": {
                                "ids": {
                                    "values": ["AVx8F96XkBWZrYmFvTpK"]
                                }
                            }
                        }
                    }
                ]
            }
        }
    }


问:
Anyone can tell me the different ways or things through which we can identify the IOT devices?
Anyone can tell me the different ways or things through which we can identify the IOT devices?

Like we can identify the IOT device through IP address , mac address, and headers in this way what else things are through which an IOT device can be identified..??

For any gud sugestion i will be very thankfull to you....

答:
Getting API from devices' suppliers is good way.
Sometimes it is not enough to get API because we have to handle non-API requirement or so many protocols which are not well defined.

Interactor(www.interactor.com) is worth to check it and this solution might be good to check it too

https://www.youtube.com/watch?v=BmDVbgm2Oa4
We can interact with things without coding, only through simple configurations just like router did.

There are a few pain points that we can meet when we need to handle IoT things. There are so many devices in IoT(Imagine the street that we are walking on). Many of them have different protocols and data types. Some of them might be out of production. I think this is the real problem for IoT. No matter how many companies released new IoT devices, we need to integrate all things on street with all things.


问:
Android: Add a view to a specific Layout from code
I want to dynamically add some views to a LinearLayout that is already defined in XML.

I'm able to add views to the screen but they are not being placed 'inside' the right LinearLayout.

How can I get a reference to this specific Layout from code, similar to getting a View by using findViewById()?

答:
Better Version:
To add another layout in activity/Fragment

```<code>LayoutInflater mInflater = LayoutInflater.from(getActivity());
View mProgressBarFooter = mInflater.inflate(R.layout.spinner, null, false);
textLoader = (TextView) mProgressBarFooter.findViewById(R.id.footer_label);
</code>```

Happy Coding(-:

Body:
Better Version:
To add another layout in activity/Fragment

LayoutInflater mInflater = LayoutInflater.from(getActivity());
View mProgressBarFooter = mInflater.inflate(R.layout.spinner, null, false);
textLoader = (TextView) mProgressBarFooter.findViewById(R.id.footer_label);

Happy Coding(-:


问:
Does CodeIgniter automatically prevent SQL injection when using function like insert(), update() , where(), order_by()?
Note :My question is not a duplicate question for Does CodeIgniter automatically prevent SQL injection? or how to avoid sql injection in codeigniter because it asked query() function. I am asking function like insert(), update() , where(), order_by()?

I am asking that following types of queries also automatically prevent SQL injection?

01.

```<code>$data = array(
        'title' => $title,
        'name' => $name,
        'date' => $date
);

$this->db->where('school', $school);
$this->db->update('mytable', $data);
</code>```

02

```<code>$this->db->select('*');
$this->db->from('table_name');
$this->db->where('pro_name', $pro_name);
$this->db->order_by($pro_type, 'desc');
$query = $this->db->get();
return $query->result_array();
</code>```

Assume that all variables are GET or POSTS values.

答:
CodeIgniter's Active Record methods https://www.codeigniter.com/userguide2/database/active_record.html automatically escape queries for you, to prevent injection.

You may find answer in here https://stackoverflow.com/a/5857481/4895810

Body:
Note :My question is not a duplicate question for Does CodeIgniter automatically prevent SQL injection? or how to avoid sql injection in codeigniter because it asked query() function. I am asking function like insert(), update() , where(), order_by()?

I am asking that following types of queries also automatically prevent SQL injection?

01.

$data = array(
        'title' => $title,
        'name' => $name,
        'date' => $date
);

$this->db->where('school', $school);
$this->db->update('mytable', $data);

02

$this->db->select('*');
$this->db->from('table_name');
$this->db->where('pro_name', $pro_name);
$this->db->order_by($pro_type, 'desc');
$query = $this->db->get();
return $query->result_array();

Assume that all variables are GET or POSTS values.


问:
Invariant scale geometry
I am writing a mesh editor where I have manipulators with the help of which I change the vertices of the mesh. The task is to render the manipulators with constant dimensions, which would not change when changing the camera and viewport parameters. The projection matrix is perspective. I will be grateful for ideas how to implement the invariant scale geometry.</p>

答:
If I got it right you want to render some markers (for example vertex drag editation area) with the same visual size for any depth they are rendered to.

There are 2 approaches for this:

scale with depth

compute perpendicular distance to camera view (simple dot product) and scale the marker size so it has the same visual size invariant on the depth.

So if P0  is your camera position and Z is your camera view direction unit vector (usually Z axis). Then for any position P compute the scale like this:

```<code>depth = dot(P-P0,Z)
</code>```

Now the scale depends on wanted visual size0 at some specified depth0. Now using triangle similarity we want:

```<code>size/dept = size0/depth0
size = size0*depth/depth0
</code>```

so render your marker with size or scale depth/depth0. In case of using scaling you need to scale around your target position P otherwise your marker would shift to the sides (so translate, scale, translate back).

compute screen position and use non perspective rendering

so you transform target coordinates the same way as the graphic pipeline does until you got the screen x,y position. Remember it and in pass that will render your markers just use that instead of real position. For this rendering pass either use some constant depth (distance from camera) or use non perspective view matrix.

For more info see Understanding 4x4 homogenous transform matrices

[Edit1] pixel size

you need to use FOVx,FOVy projection angles and view/screen resolution (xs,ys) for that. That means if depth is znear and coordinate is at half of the angle then the projected coordinate will go to edge of screen:

```<code>tan(FOVx/2) = (xs/2)*pixelx/znear
tan(FOVy/2) = (ys/2)*pixely/znear
---------------------------------
pixelx = 2*znear*tan(FOVx/2)/xs
pixely = 2*znear*tan(FOVy/2)/ys
</code>```

Where pixelx,pixely is size (per axis) representing single pixel visually at depth znear. In case booth sizes are the same (so pixel is square) you have all you need. In case they are not equal (pixel is not square) then you need to render markers in screen axis aligned coordinates so approach #2 is more suitable for such case.

So if you chose depth0=znear then you can set size0 as n*pixelx and/or n*pixely to get the visual size of n pixels. Or use any dept0 and rewrite the computation to:

```<code>pixelx = 2*depth0*tan(FOVx/2)/xs
pixely = 2*depth0*tan(FOVy/2)/ys
</code>```

Just to be complete:

```<code>size0x = size_in_pixels*(2*depth0*tan(FOVx/2)/xs)
size0y = size_in_pixels*(2*depth0*tan(FOVy/2)/ys)
-------------------------------------------------
sizex = size_in_pixels*(2*depth0*tan(FOVx/2)/xs)*(depth/depth0)
sizey = size_in_pixels*(2*depth0*tan(FOVy/2)/ys)*(depth/depth0)
---------------------------------------------------------------
sizex = size_in_pixels*(2*tan(FOVx/2)/xs)*(depth)
sizey = size_in_pixels*(2*tan(FOVy/2)/ys)*(depth)
---------------------------------------------------------------
sizex = size_in_pixels*2*depth*tan(FOVx/2)/xs
sizey = size_in_pixels*2*depth*tan(FOVy/2)/ys
</code>```

Title: Invariant scale geometry

Body:
If I got it right you want to render some markers (for example vertex drag editation area) with the same visual size for any depth they are rendered to.

There are 2 approaches for this:

scale with depth

compute perpendicular distance to camera view (simple dot product) and scale the marker size so it has the same visual size invariant on the depth.

So if P0  is your camera position and Z is your camera view direction unit vector (usually Z axis). Then for any position P compute the scale like this:

depth = dot(P-P0,Z)

Now the scale depends on wanted visual size0 at some specified depth0. Now using triangle similarity we want:

size/dept = size0/depth0
size = size0*depth/depth0

so render your marker with size or scale depth/depth0. In case of using scaling you need to scale around your target position P otherwise your marker would shift to the sides (so translate, scale, translate back).

compute screen position and use non perspective rendering

so you transform target coordinates the same way as the graphic pipeline does until you got the screen x,y position. Remember it and in pass that will render your markers just use that instead of real position. For this rendering pass either use some constant depth (distance from camera) or use non perspective view matrix.

For more info see Understanding 4x4 homogenous transform matrices

[Edit1] pixel size

you need to use FOVx,FOVy projection angles and view/screen resolution (xs,ys) for that. That means if depth is znear and coordinate is at half of the angle then the projected coordinate will go to edge of screen:

tan(FOVx/2) = (xs/2)*pixelx/znear
tan(FOVy/2) = (ys/2)*pixely/znear
---------------------------------
pixelx = 2*znear*tan(FOVx/2)/xs
pixely = 2*znear*tan(FOVy/2)/ys

Where pixelx,pixely is size (per axis) representing single pixel visually at depth znear. In case booth sizes are the same (so pixel is square) you have all you need. In case they are not equal (pixel is not square) then you need to render markers in screen axis aligned coordinates so approach #2 is more suitable for such case.

So if you chose depth0=znear then you can set size0 as n*pixelx and/or n*pixely to get the visual size of n pixels. Or use any dept0 and rewrite the computation to:

pixelx = 2*depth0*tan(FOVx/2)/xs
pixely = 2*depth0*tan(FOVy/2)/ys

Just to be complete:

size0x = size_in_pixels*(2*depth0*tan(FOVx/2)/xs)
size0y = size_in_pixels*(2*depth0*tan(FOVy/2)/ys)
-------------------------------------------------
sizex = size_in_pixels*(2*depth0*tan(FOVx/2)/xs)*(depth/depth0)
sizey = size_in_pixels*(2*depth0*tan(FOVy/2)/ys)*(depth/depth0)
---------------------------------------------------------------
sizex = size_in_pixels*(2*tan(FOVx/2)/xs)*(depth)
sizey = size_in_pixels*(2*tan(FOVy/2)/ys)*(depth)
---------------------------------------------------------------
sizex = size_in_pixels*2*depth*tan(FOVx/2)/xs
sizey = size_in_pixels*2*depth*tan(FOVy/2)/ys


问:
Accessing database on server using android studio
I'm a complete beginner in android programming and am trying to make an app which requires access to the database on local host using the android studio, using the IP address of the server, I've watched many tutorial videos but still am not sure where to pass the IP address of the server.
The server uses MySQL, I've tried using JDBC but still unable to achieve the result.

Here is my code, any help would be appreciated.

```<code>`package com.example.vishal.connectiontest;
import java.sql.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import static android.R.attr.name;
import static com.example.vishal.connectiontest.DemoClass.main;

public class MainActivity extends AppCompatActivity {

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

        final Button B1 = (Button)findViewById(R.id.button);
        final TextView e1 = (TextView) findViewById(R.id.HelloWorld);

        B1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    String result = main();
                    e1.setText(result.toString());
                }
                catch(java.lang.Exception e){
                    System.out.println("Exception");

                }

            }

        });

    }
}

class DemoClass
{

    public static String main()throws Exception
    {
        String url = "jdbc:mysql://125.10.10.214/demo" ;
        String uname = "root";
        String pass = "";
        String ip = "";
        String query = "Select UserName from user_info where Id = '90000515'";

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, uname,pass);
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery(query);

        rs.next();
        String name = rs.getString("UserName");
        return (name);

    }

}`
</code>```

答:
Easiest way of integrating Database to your Android Application is using Firebase.
It's really easy to use and other than Database, it has File Storage Services, Cloud Messaging, Analytics and many more.
I would recommend use of firebase database.
Here have a look at it's Documentation:
https://firebase.google.com/docs/database/</p>

Body:
I'm a complete beginner in android programming and am trying to make an app which requires access to the database on local host using the android studio, using the IP address of the server, I've watched many tutorial videos but still am not sure where to pass the IP address of the server.
The server uses MySQL, I've tried using JDBC but still unable to achieve the result.

Here is my code, any help would be appreciated.

`package com.example.vishal.connectiontest;
import java.sql.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import static android.R.attr.name;
import static com.example.vishal.connectiontest.DemoClass.main;

public class MainActivity extends AppCompatActivity {

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

        final Button B1 = (Button)findViewById(R.id.button);
        final TextView e1 = (TextView) findViewById(R.id.HelloWorld);

        B1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    String result = main();
                    e1.setText(result.toString());
                }
                catch(java.lang.Exception e){
                    System.out.println("Exception");

                }

            }

        });

    }
}

class DemoClass
{

    public static String main()throws Exception
    {
        String url = "jdbc:mysql://125.10.10.214/demo" ;
        String uname = "root";
        String pass = "";
        String ip = "";
        String query = "Select UserName from user_info where Id = '90000515'";

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, uname,pass);
        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery(query);

        rs.next();
        String name = rs.getString("UserName");
        return (name);

    }

}`