问:
Changing the geom order in a stacked ggplot legend
I am trying to change the order in which my legend displays the points and lines using ggplot for my graph.

Currently I have my graph itself displaying dots first then lines on top of the dots which is what I want. Here is a reproducible example:

```<code>ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_point(aes(colour = Species, shape = Species)) +
  geom_smooth()
</code>```

As you can see from the legend, it has overlayed the values in the order plotted, but I would like to reverse this. I know that I could overlay the points on top of the plot as follows:

```<code>ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_smooth() +
  geom_point(aes(colour = Species, shape = Species))
</code>```

I have searched and found the function guides(fill = guide_legend(reverse = TRUE)) from here, but this is having no effect.

Any help much appreciated

答:
Here are two methods that will allow the order in which grobs in the legend are drawn to be manipulated, but neither is straightforward.

The first uses ggplot's gtable. The column "z" in the layout data frame gives the order in which the grobs are drawn. But one has to get to the layout data frame of the legend itself in order to manipulate the legend's grobs. Something like this:

```<code>library(ggplot2)
library(gtable)
library(grid)

df = read.table(text =
"School      Year    Value
 A           1998    5
 B           1999    10
 C           2000    15
 A           2000    7
 B           2001    15
 C           2002    20", sep = "", header = TRUE)

p <- ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_point(aes(colour = Species, shape = Species), size = 2) +
  geom_smooth()

# Get the ggplot grob
gt <- ggplotGrob(p)

# Get the legend
leg <- gt$grobs[gt$layout$name == "guide-box"][[1]]$grobs[[1]]

# Check the layout
leg$layout
</code>```

lines 4 and 5 draw the first legend key, but it draws the point first (key-3-1-1) then the line segment (key-3-1-2). Swapping the z-values will ensure that the line segment is plotted first, then the point. Similarly, for lines 7 & 8, and lines 10 & 11.

```<code># Swap the z-values for the relevant lines in the layout table
leg$layout[c(4:5, 7:8, 10:11), "z"] <- c(5:4, 8:7, 11:10)

# Put legend back into ggplot grob
gt$grobs[gt$layout$name == "guide-box"][[1]]$grobs[[1]] <- leg

# Draw it
grid.newpage()
grid.draw(gt)
</code>```

The second method uses grid's editing functions to change the order.

```<code># Get the ggplot grob
gt <- ggplotGrob(p)

# Get the legend grob
leg = getGrob(grid.force(gt), gPath("guides"), grep = TRUE)

# Get a list of grobs (in the legend).
# This also gives the order.
grid.ls(grid.force(leg))

# Nearly the same names for the grobs,
#   and the same order as before
#   (don't count the indented grobs).

# Change the order in which grobs are drawn
leg = reorderGrob(leg,  c(5:4, 8:7, 11:10), back = FALSE)

# Remove the original legend and replace with the new legend
gt = removeGrob(grid.force(gt), "guides", grep = TRUE)
gt = addGrob(gt, leg, "guide-box", grep = TRUE)

# Draw the plot
grid.newpage()
grid.draw(gt)
</code>```

Body:
I am trying to change the order in which my legend displays the points and lines using ggplot for my graph.

Currently I have my graph itself displaying dots first then lines on top of the dots which is what I want. Here is a reproducible example:

ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_point(aes(colour = Species, shape = Species)) +
  geom_smooth()

As you can see from the legend, it has overlayed the values in the order plotted, but I would like to reverse this. I know that I could overlay the points on top of the plot as follows:

ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_smooth() +
  geom_point(aes(colour = Species, shape = Species))

I have searched and found the function guides(fill = guide_legend(reverse = TRUE)) from here, but this is having no effect.

Any help much appreciated

Body:
Here are two methods that will allow the order in which grobs in the legend are drawn to be manipulated, but neither is straightforward.

The first uses ggplot's gtable. The column "z" in the layout data frame gives the order in which the grobs are drawn. But one has to get to the layout data frame of the legend itself in order to manipulate the legend's grobs. Something like this:

library(ggplot2)
library(gtable)
library(grid)

df = read.table(text =
"School      Year    Value
 A           1998    5
 B           1999    10
 C           2000    15
 A           2000    7
 B           2001    15
 C           2002    20", sep = "", header = TRUE)

p <- ggplot(iris, aes(Sepal.Width, Petal.Width, linetype = Species)) +
  geom_point(aes(colour = Species, shape = Species), size = 2) +
  geom_smooth()

# Get the ggplot grob
gt <- ggplotGrob(p)

# Get the legend
leg <- gt$grobs[gt$layout$name == "guide-box"][[1]]$grobs[[1]]

# Check the layout
leg$layout

lines 4 and 5 draw the first legend key, but it draws the point first (key-3-1-1) then the line segment (key-3-1-2). Swapping the z-values will ensure that the line segment is plotted first, then the point. Similarly, for lines 7 & 8, and lines 10 & 11.

# Swap the z-values for the relevant lines in the layout table
leg$layout[c(4:5, 7:8, 10:11), "z"] <- c(5:4, 8:7, 11:10)

# Put legend back into ggplot grob
gt$grobs[gt$layout$name == "guide-box"][[1]]$grobs[[1]] <- leg

# Draw it
grid.newpage()
grid.draw(gt)

The second method uses grid's editing functions to change the order.

# Get the ggplot grob
gt <- ggplotGrob(p)

# Get the legend grob
leg = getGrob(grid.force(gt), gPath("guides"), grep = TRUE)

# Get a list of grobs (in the legend).
# This also gives the order.
grid.ls(grid.force(leg))

# Nearly the same names for the grobs,
#   and the same order as before
#   (don't count the indented grobs).

# Change the order in which grobs are drawn
leg = reorderGrob(leg,  c(5:4, 8:7, 11:10), back = FALSE)

# Remove the original legend and replace with the new legend
gt = removeGrob(grid.force(gt), "guides", grep = TRUE)
gt = addGrob(gt, leg, "guide-box", grep = TRUE)

# Draw the plot
grid.newpage()
grid.draw(gt)


来源: stackexchange

问:
Prevent Superuser from deleting/removing/editing User Email in Django Admin
I am using django-allauth for User signup and login purposes. Users can login using both username and email.

```<code># settings.py

# Custom User Model
AUTH_USER_MODEL = 'users.User'

# ask for either username or email during login
ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
# Set Email field as required during signup
ACCOUNT_EMAIL_REQUIRED = True
# Set email versification necessary before creating account
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
# Don't ask for username while signing up.
# Users can later edit/change username in their profile.
# If username is not set, use email to log in.
ACCOUNT_USERNAME_REQUIRED = False
# Login the user after email-confirmations
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
</code>```

I have a users app which implements a custom User Model as shown.

```<code># users/models.py

class User(AbstractUser):

    name = models.CharField(blank=True, max_length=255)

    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse('users:detail', kwargs={'username': self.username})
</code>```

Using this setup, I am able to make user login via both email and username. However, the problem being the fact that Superuser is able to edit/remove 'email' in Django Admin. I don't want such behaviours. (An attempt to remove username however gives an "field required" error.)

My question now is,
How to prevent the Admin from editing the user information. i.e make 'username' and 'email' read-only fields.

答:
Well, superuser is the most privileged user of the system.
It's logical that superuser has absolute access to everything.

If you want a user to have only some of the access rights, you can do that by making a new admin group and add Admins to that group. Remove the right to modify the user table for that group.

ContentLicense: CC BY-SA 3.0

Body:
I am using django-allauth for User signup and login purposes. Users can login using both username and email.

# settings.py

# Custom User Model
AUTH_USER_MODEL = 'users.User'

# ask for either username or email during login
ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
# Set Email field as required during signup
ACCOUNT_EMAIL_REQUIRED = True
# Set email versification necessary before creating account
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
# Don't ask for username while signing up.
# Users can later edit/change username in their profile.
# If username is not set, use email to log in.
ACCOUNT_USERNAME_REQUIRED = False
# Login the user after email-confirmations
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True

I have a users app which implements a custom User Model as shown.

# users/models.py

class User(AbstractUser):

    name = models.CharField(blank=True, max_length=255)

    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse('users:detail', kwargs={'username': self.username})

Using this setup, I am able to make user login via both email and username. However, the problem being the fact that Superuser is able to edit/remove 'email' in Django Admin. I don't want such behaviours. (An attempt to remove username however gives an "field required" error.)

My question now is,
How to prevent the Admin from editing the user information. i.e make 'username' and 'email' read-only fields.


Title: Database Joins with single record with multiple coulmns

Body:
Industry Table

+----+--------------+
| ID | IndustryName |
+----+--------------+
|  1 |     Auto     |
|  2 |     Pets     |
+----+--------------+

Images Table

+----+------------+--------------+
| ID | IndustryId |   ImageURL   |
+----+------------+--------------+
|  1 |     1      |      URL1    |
|  2 |     1      |      URL2    |
|  3 |     1      |      URL3    |
+----+------------+--------------+

I wanna get result of Select Query as follows

 +----+------------+------------------+
 | ID | IndustryId |ImageURLContains  |
 +----+------------+------------------+
 | 1  | Auto       |(URL1,URL2,URL3)  |
 +----+------------+------------------+

And we can have n number of URLS against one IndustryId.

Body:
Try It With Stuff Function

CREATE TABLE Images_Table(ID INT ,IndustryId INT , IMageURL NVARCHAR(50))

INSERT INTO Images_Table
SELECT 1,1,'URL1'UNION ALL
SELECT 2,1,'URL2'UNION ALL
SELECT 3,1,'URL3'

SELECT
    ID IndstryId,IndustryName,
    STUFF(
        (
            SELECT ' ,'+ISNULL(IMageURL,'')
            FROM Images_Table t2
            WHERE t2.IndustryId=t1.ID
            ORDER BY t2.Id
            FOR XML PATH('')
        ),1,2,'') ImageURL
FROM (SELECT ID,ISNULL(IndustryName,'') IndustryName FROM Industry_Table) t1

Following Output I'm Getting it

IndstryId   IndustryName                                       ImageURL
----------- -------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1           Auto                                               URL1 ,URL2 ,URL3


问:
SELECT Max index for multiple column values in the same table?
I have the following database structure:

```<code>post_id | language | index
</code>```

Data looks like:

```<code>1  |  en  |  1
1  |  en  |  2
1  |  en  |  3

1  |  fr |  1
1  |  fr |  2
</code>```

language is a shortcode like en, fr, etc. index is an incrementing integer. There is at least one language code in the database.

I need to get the max value of index for each language.

Currently i get all languages for a post

```<code>SELECT DISTINCT(language) FROM my_table WHERE post_id = ?
</code>```

and iterate then over the language array to get the Max value for each language

```<code>SELECT MAX(index) FROM my_table WHERE post_id = ? AND language = 'language_code'
</code>```

Is there a way to execute just one query to achieve this result?

The result should look like:

```<code>1  |  en  |  3
1  |  fr  |  2
</code>```

答:
You can use GROUP BY to achieve this.

You can check this link for more infos about the usage of GROUP BY with MAX: SQL MAX() with group by

```<code>SELECT post_id, language, MAX(index)
  FROM my_table
  GROUP BY post_id, language;
</code>```

The result of this query will be all the languages associated with the max index.

```<code>post_id | language | MAX(index)
1 | en |  3
1 | fr |  2
</code>```

Hope this helps!

Body:
I have the following database structure:

post_id | language | index

Data looks like:

1  |  en  |  1
1  |  en  |  2
1  |  en  |  3

1  |  fr |  1
1  |  fr |  2

language is a shortcode like en, fr, etc. index is an incrementing integer. There is at least one language code in the database.

I need to get the max value of index for each language.

Currently i get all languages for a post

SELECT DISTINCT(language) FROM my_table WHERE post_id = ?

and iterate then over the language array to get the Max value for each language

SELECT MAX(index) FROM my_table WHERE post_id = ? AND language = 'language_code'

Is there a way to execute just one query to achieve this result?

The result should look like:

1  |  en  |  3
1  |  fr  |  2

Body:
You can use GROUP BY to achieve this.

You can check this link for more infos about the usage of GROUP BY with MAX: SQL MAX() with group by

SELECT post_id, language, MAX(index)
  FROM my_table
  GROUP BY post_id, language;

The result of this query will be all the languages associated with the max index.

post_id | language | MAX(index)
1 | en |  3
1 | fr |  2

Hope this helps!


问:
Non-Prime Number Counter in C
I want to write a program for storing all the non-prime(composite) numbers before 10.000 in an array. I did this algorithm below, but it's not working. When I print out the array which is supposed to be holding composite numbers, it's simply counting from 4 to 10.000 .

Where is the problem? I really looked so much but I can't see.

```<code>#include <stdio.h>
#define SIZE 10000

void compositeChecker(int[]);

int main() {
    int k;
    int compositeArray[SIZE]= {0};
    compositeChecker(compositeArray);
    for(k=0; k<100; k++) {
        printf("%d\n",compositeArray[k]);
    }
}

void compositeChecker(int arr[]) {
    int i,j,counter=0;

    for(i=4; i<10000; i++) {
        for(j=2; j<i; j++) {
            if((i%j)==0) {
                counter++;
            }
        }
        if(counter!=0) {
            arr[i-4]=i;
        }
    }
}
</code>```

答:
The problem with your code is clearly not resetting counter as @DavidHoelzer points out.  But there's another bug as simply fixing counter leaves zeros in your output where the primes were.

I believe the real fix is to eliminate counter as it's wrongheaded.  Once you determine a number is composite, you keep checking more divisors but ignore all that extra work when you test if (counter != 0). So, we should just make a note once we find the first divisor and move onto the next number.  This is a perfect use of a break statement:

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

#define SIZE 100

void compositeChecker(bool array[]) {

    for (int i = 3; i < SIZE; i++) {
        for (int j = 2; j < i; j++) {
            if (i % j == 0) {
                array[i] = true;
                break;
            }
        }
    }
}

int main() {

    bool compositeArray[SIZE] = {false};

    compositeChecker(compositeArray);

    for (int k = 0; k < SIZE; k++) {
        if (compositeArray[k]) {
                printf("%d\n", k);
        }
    }
}
</code>```

Note that I've also changed compositeArray not to be a list of composite numbers but rather a list of booleans indicating whether a particular index is composite or not.

A final issue is one of terminology.  Your code is looking for composite numbers but your title and text say non-prime.  The difference is how you handle 0 and 1.  If you're looking for composite numbers, exclude them.  If you're looking for non-prime numbers, include them.

Title: Non-Prime Number Counter in C

Body:
I want to write a program for storing all the non-prime(composite) numbers before 10.000 in an array. I did this algorithm below, but it's not working. When I print out the array which is supposed to be holding composite numbers, it's simply counting from 4 to 10.000 .

Where is the problem? I really looked so much but I can't see.

#include <stdio.h>
#define SIZE 10000

void compositeChecker(int[]);

int main() {
    int k;
    int compositeArray[SIZE]= {0};
    compositeChecker(compositeArray);
    for(k=0; k<100; k++) {
        printf("%d\n",compositeArray[k]);
    }
}

void compositeChecker(int arr[]) {
    int i,j,counter=0;

    for(i=4; i<10000; i++) {
        for(j=2; j<i; j++) {
            if((i%j)==0) {
                counter++;
            }
        }
        if(counter!=0) {
            arr[i-4]=i;
        }
    }
}

Body:
The problem with your code is clearly not resetting counter as @DavidHoelzer points out.  But there's another bug as simply fixing counter leaves zeros in your output where the primes were.

I believe the real fix is to eliminate counter as it's wrongheaded.  Once you determine a number is composite, you keep checking more divisors but ignore all that extra work when you test if (counter != 0). So, we should just make a note once we find the first divisor and move onto the next number.  This is a perfect use of a break statement:

#include <stdio.h>
#include <stdbool.h>

#define SIZE 100

void compositeChecker(bool array[]) {

    for (int i = 3; i < SIZE; i++) {
        for (int j = 2; j < i; j++) {
            if (i % j == 0) {
                array[i] = true;
                break;
            }
        }
    }
}

int main() {

    bool compositeArray[SIZE] = {false};

    compositeChecker(compositeArray);

    for (int k = 0; k < SIZE; k++) {
        if (compositeArray[k]) {
                printf("%d\n", k);
        }
    }
}

Note that I've also changed compositeArray not to be a list of composite numbers but rather a list of booleans indicating whether a particular index is composite or not.

A final issue is one of terminology.  Your code is looking for composite numbers but your title and text say non-prime.  The difference is how you handle 0 and 1.  If you're looking for composite numbers, exclude them.  If you're looking for non-prime numbers, include them.


问:
Selecting a Range in a Document
To select text as heading I use this:

```<code>Dim rng As MsWord.Range = oDoc.Paragraphs(1).Range
</code>```

How to select all other text in document - from second line/paragraph in document till the end of document

I tried:

```<code>Dim startLocation As Object = oDoc.Sentences(2).Start
Dim endLocation As Object = oDoc.Sentences(2).End
rng = oDoc.Range(Start:=startLocation, End:=endLocation)
</code>```

but problem is how to define end number. How to select all text from second line to end? If uploaded documents would be with different lenght

答:
You can use oDoc.Range.End like:

oDoc.Range(oDoc.Paragraphs(2).Range.Start, oDoc.Range.End).Select

Title: Selecting a Range in a Document

Body:
To select text as heading I use this:

Dim rng As MsWord.Range = oDoc.Paragraphs(1).Range

How to select all other text in document - from second line/paragraph in document till the end of document

I tried:

Dim startLocation As Object = oDoc.Sentences(2).Start
Dim endLocation As Object = oDoc.Sentences(2).End
rng = oDoc.Range(Start:=startLocation, End:=endLocation)

but problem is how to define end number. How to select all text from second line to end? If uploaded documents would be with different lenght


问:
How to skip carriage returns in csv file while reading from cloud storage using google cloud dataflow in java
I have a CSV file which consists of new carriage returns (\n) in each row.
While reading the CSV file from cloud storage using TextIO.read function of Apache beam it is considering  \n as new record. how can i overcome this issue.

I have tried with by extending filebasedsource but it is reading only first line of the CSV file when we apply pTransorms.

help will be appreciated

Thanks in Advance

答:
TextIO can not do this - it always splits input based on carriage returns and is not aware of CSV-specific quoting of some of these carriage returns.

However, Beam 2.2 includes a transform that will make it very easy for you to write the CSV-specific (or any other file format specific reading) code yourself: FileIO. Do something like this:

```<code>p.apply(FileIO.match().filepattern("gs://..."))
 .apply(FileIO.readMatches())
 .apply(ParDo.of(new DoFn<ReadableFile, TableRow>() {
   @ProcessElement
   public void process(ProcessContext c) throws IOException {
     try (InputStream is = Channels.newInputStream(c.element().open())) {
       // ... Use your favorite Java CSV library ...
       ... c.output(next csv record) ...
     }
   }
 }))
</code>```

Body:
TextIO can not do this - it always splits input based on carriage returns and is not aware of CSV-specific quoting of some of these carriage returns.

However, Beam 2.2 includes a transform that will make it very easy for you to write the CSV-specific (or any other file format specific reading) code yourself: FileIO. Do something like this:

p.apply(FileIO.match().filepattern("gs://..."))
 .apply(FileIO.readMatches())
 .apply(ParDo.of(new DoFn<ReadableFile, TableRow>() {
   @ProcessElement
   public void process(ProcessContext c) throws IOException {
     try (InputStream is = Channels.newInputStream(c.element().open())) {
       // ... Use your favorite Java CSV library ...
       ... c.output(next csv record) ...
     }
   }
 }))


问:
Word boundary to use in unicode text for Python regex
I want to use word boundary in a regex for matching some unicode text. Unicode letters are detected as word boundary in Python regex as here:

```<code>>>> re.search(r"\by\b","üyü")
<_sre.SRE_Match object at 0x02819E58>

>>> re.search(r"\by\b","ğyğ")
<_sre.SRE_Match object at 0x028250C8>

>>> re.search(r"\by\b","uyu")
>>>
</code>```

What should I do in order to make the word boundary symbol not match unicode letters?

答:
```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

s = ur"abcd ААБВ"
import re
rx1 = re.compile(ur"(?u)АБВ")
rx2 = re.compile(ur"(?u)АБВ\b")
rx3 = re.compile(ur"(?u)\bАБВ\b")
print rx1.findall(s)
print rx2.findall(s)
print rx3.findall(s)

print re.search(ur'(?u)ривет\b', ur'Привет')
print re.search(ur'(?u)\bривет\b', ur'Привет')
</code>```

Output:

```<code>[u'\u0410\u0411\u0412']
[u'\u0410\u0411\u0412']
[]
<_sre.SRE_Match object at 0x01F056B0>
None
</code>```

Body:
I want to use word boundary in a regex for matching some unicode text. Unicode letters are detected as word boundary in Python regex as here:

>>> re.search(r"\by\b","üyü")
<_sre.SRE_Match object at 0x02819E58>

>>> re.search(r"\by\b","ğyğ")
<_sre.SRE_Match object at 0x028250C8>

>>> re.search(r"\by\b","uyu")
>>>

What should I do in order to make the word boundary symbol not match unicode letters?

Body:
#!/usr/bin/python
# -*- coding: utf-8 -*-

s = ur"abcd ААБВ"
import re
rx1 = re.compile(ur"(?u)АБВ")
rx2 = re.compile(ur"(?u)АБВ\b")
rx3 = re.compile(ur"(?u)\bАБВ\b")
print rx1.findall(s)
print rx2.findall(s)
print rx3.findall(s)

print re.search(ur'(?u)ривет\b', ur'Привет')
print re.search(ur'(?u)\bривет\b', ur'Привет')

Output:

[u'\u0410\u0411\u0412']
[u'\u0410\u0411\u0412']
[]
<_sre.SRE_Match object at 0x01F056B0>
None


问:
PreferenceFragmentCompat not listening to first touch event
I created a PreferenceFragmentCompat settings everything is working fine but I noticed something odd, clicking on setting button first time when preference screen loaded and I touch on some preference it does not respond to my first touch but right after it works normally this is my code

```<code>public class SettingsFragment extends PreferenceFragmentCompat implements HomeActivity.Authentication, Preference.OnPreferenceClickListener, SharedPreferences.OnSharedPreferenceChangeListener, ConfirmAlertDialog.OnDialogClickInterface {
@Override
public boolean onPreferenceClick(final Preference preference) {
    final String key = preference.getKey();

    switch (key) {
        case "remove_ads":
            homeActivity.purchaseRemoveAds();
            break;
        case "hide_icon":
            try {
                homeActivity.loadFragment(new HideOptiosTutorial(), getParentFragment().getFragmentManager().beginTransaction());
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;

        case "key_share_app_link":
            shareAppFile();

            break;

        case "move_to_sdcard":

            showMovetoSdDialog();

            break;
        case "button_internal":

            showMovetoInternalDialog();

            break;
        case "back_up_sdcard":
            if (isSDCardUnmounted()) {
                showSDCardMountError();
            } else {

                globalPasswords = getBackupPasswords();

                if (!FileUtilis.isSafAllowed(getActivity())) {
                    showSDCardNotAllowedDialog(983);
                    //
                    return false;
                }

                if (globalPasswords.size() == 0) {
                    showNoBackupFoundMsg();
                } else {
                    showDialogToBackupFromSDCard();
                }
            }
            break;
        case "change_password":
            showChangePinDialog();
            break;

        case "key_rate_us":
            rateApplication();
            break;
        case "app_link":
            SavedAlbumsFragment.showAppLockLink(getActivity());
            break;
        case "view_intruders":
            startActivity(new Intent(homeActivity, ViewIntruders.class));
            break;
        case "theme":
            showSelectTehmeDialog();
            break;

        case "enter_email":

            showChangeEmailDialog();
            break;
    }

    return false;
}
@Override
public void onCreatePreferences(Bundle bundle, String s) {
    addPreferencesFromResource(R.xml.pref_headers);
    Log.e("Mateen","onCreatePreferences");

    homeActivity = ((HomeActivity) getActivity());
    homeActivity.addAuthenticationListner(this);
    localDatabase = LocalDatabase.getInstance(getActivity());
    localPreferences = new LocalPreferences(getActivity());

    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    LocalBroadcastManager.getInstance(homeActivity).registerReceiver(broadcastReceiver,new IntentFilter("Remove_Is_Purchased"));

    removeAdsPref=findPreference("remove_ads");
    mCategory = (PreferenceCategory)findPreference("cat_remove_ads");

    if (localPreferences.IsRemovedAdsPurchased())
    {
        mCategory.removePreference(removeAdsPref);
        getPreferenceScreen().removePreference(mCategory);
    }
    else
    {
        removeAdsPref.setOnPreferenceClickListener(this);
    }

    findPreference("move_to_sdcard").setOnPreferenceClickListener(this);
    findPreference("view_intruders").setOnPreferenceClickListener(this);
    findPreference("button_internal").setOnPreferenceClickListener(this);
    findPreference("back_up_sdcard").setOnPreferenceClickListener(this);
    findPreference("change_password").setOnPreferenceClickListener(this);
    findPreference("key_rate_us").setOnPreferenceClickListener(this);
    findPreference("app_link").setOnPreferenceClickListener(this);
    findPreference("hide_icon").setOnPreferenceClickListener(this);
    findPreference("key_share_app_link").setOnPreferenceClickListener(this);
    findPreference("listPref_wrong_tries").setOnPreferenceClickListener(this);
    findPreference("theme").setOnPreferenceClickListener(this);
    findPreference("enter_email").setOnPreferenceClickListener(this);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        findPreference("key_cam_short").setVisible(false);
        findPreference("key_vid_short").setVisible(false);
    }

    if (!PreferenceManager.getDefaultSharedPreferences(homeActivity).getBoolean("key_intruder_detection",false))
    {
        findPreference("listPref_wrong_tries").setEnabled(false);
    }
    if (!Reprint.isHardwarePresent()) {
        findPreference("key_fingerprint").setEnabled(false);
    }

    if (!FileUtilis.isSdcardPresent(getActivity())) {
        findPreference("move_to_sdcard").setEnabled(false);
        findPreference("button_internal").setEnabled(false);
        findPreference("back_up_sdcard").setEnabled(false);

        //  findPreference("change_password").setEnabled(false);
        findPreference("always_save_to_sdcard").setEnabled(false);
    }
    //add xml

}
</code>```

and this is my preference xml:

```<code><android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.andr]oid.com/apk/res-auto"
app:key="preferenceScreen">

<!-- These settings headers are only used on tablets. -->z
<android.support.v7.preference.PreferenceCategory  android:title="@string/cate_remove_ads"
    android:key="cat_remove_ads">
    <Preference
        android:key="remove_ads"
        android:summary="@string/txt_remove_ads"
        android:title="@string/remove_ads" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/storage">

    <Preference
        android:key="move_to_sdcard"
        android:summary="@string/export_sdcard_summary"
        android:title="@string/txt_move_to_external" />

    <Preference
        android:key="button_internal"
        android:summary="@string/export_internal_summary"
        android:title="@string/txt_move_too_internal" />

    <Preference
        android:key="back_up_sdcard"
        android:summary="@string/backup_summary"
        android:title="@string/back_from_sdcard" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="always_save_to_sdcard"
        android:summary="@string/always_on_sd_card"
        android:title="@string/sav_loc" />

</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/cate_security">

    <Preference
        android:key="hide_icon"
        android:title="@string/hide_icon" />

    <Preference
        android:key="app_link"
        android:summary="@string/app_link_title"
        android:title="@string/app_link_detail" />

    <Preference
        android:key="change_password"
        android:title="@string/chagne_password" />

    <Preference
        android:key="enter_email"
        android:title="@string/forgot_email_title"
        android:summary="@string/enter_email_to_recover" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="shuffle_pin"
        android:summary="@string/shuffle_summary"
        android:title="@string/shuffle_title" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_fingerprint"
        android:summary="@string/summary_fingerprint"
        android:title="@string/fingerprint_auth" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/cate_intruder">
    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_intruder_detection"
        android:summary="@string/take_intruder_picture_summary"
        android:title="@string/take_intruder_picture" />

    <android.support.v7.preference.ListPreference
        android:defaultValue="3"
        android:entries="@array/wrong_tries"
        android:entryValues="@array/wrong_tries"
        android:summary="%s"
        android:title="@string/wrong_tries"
        android:key="listPref_wrong_tries" />
    <Preference
        android:key="view_intruders"
        android:summary="@string/show_intruder_pic"
        android:title="@string/show_intruder_pic_summary" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/cate_others">
    <Preference
        android:key="theme"
        android:summary="@string/chose_theme"
        android:title="@string/select_theme" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_cam_short"
        android:summary="@string/cam_short_detail"
        android:title="@string/sec_selfi_shortcut" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_vid_short"
        android:summary="@string/vid_short_detail"
        android:title="@string/sec_vid_shortcut" />

    <Preference
        android:key="key_share_app_link"
        android:summary="@string/share_app_link_detail"
        android:title="@string/share_app_link_title" />

    <Preference
        android:key="key_rate_us"
        android:summary="@string/rate_detail"
        android:title="@string/rate_us" />
</android.support.v7.preference.PreferenceCategory>
</code>```

Please guide me what am I doing wrong?
Is it support libs issue or I am doing something wrong?

答:
i solved my problem by removing this line from my fragment layout's xml

```<code>        app:layout_scrollFlags="scroll|enterAlways"
</code>```

from:

```<code>  <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:layout_scrollFlags="scroll|enterAlways"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</code>```

now it is listening to my every damn touch :D Happy coding

Body:
I created a PreferenceFragmentCompat settings everything is working fine but I noticed something odd, clicking on setting button first time when preference screen loaded and I touch on some preference it does not respond to my first touch but right after it works normally this is my code

public class SettingsFragment extends PreferenceFragmentCompat implements HomeActivity.Authentication, Preference.OnPreferenceClickListener, SharedPreferences.OnSharedPreferenceChangeListener, ConfirmAlertDialog.OnDialogClickInterface {
@Override
public boolean onPreferenceClick(final Preference preference) {
    final String key = preference.getKey();

    switch (key) {
        case "remove_ads":
            homeActivity.purchaseRemoveAds();
            break;
        case "hide_icon":
            try {
                homeActivity.loadFragment(new HideOptiosTutorial(), getParentFragment().getFragmentManager().beginTransaction());
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;

        case "key_share_app_link":
            shareAppFile();

            break;

        case "move_to_sdcard":

            showMovetoSdDialog();

            break;
        case "button_internal":

            showMovetoInternalDialog();

            break;
        case "back_up_sdcard":
            if (isSDCardUnmounted()) {
                showSDCardMountError();
            } else {

                globalPasswords = getBackupPasswords();

                if (!FileUtilis.isSafAllowed(getActivity())) {
                    showSDCardNotAllowedDialog(983);
                    //
                    return false;
                }

                if (globalPasswords.size() == 0) {
                    showNoBackupFoundMsg();
                } else {
                    showDialogToBackupFromSDCard();
                }
            }
            break;
        case "change_password":
            showChangePinDialog();
            break;

        case "key_rate_us":
            rateApplication();
            break;
        case "app_link":
            SavedAlbumsFragment.showAppLockLink(getActivity());
            break;
        case "view_intruders":
            startActivity(new Intent(homeActivity, ViewIntruders.class));
            break;
        case "theme":
            showSelectTehmeDialog();
            break;

        case "enter_email":

            showChangeEmailDialog();
            break;
    }

    return false;
}
@Override
public void onCreatePreferences(Bundle bundle, String s) {
    addPreferencesFromResource(R.xml.pref_headers);
    Log.e("Mateen","onCreatePreferences");

    homeActivity = ((HomeActivity) getActivity());
    homeActivity.addAuthenticationListner(this);
    localDatabase = LocalDatabase.getInstance(getActivity());
    localPreferences = new LocalPreferences(getActivity());

    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    LocalBroadcastManager.getInstance(homeActivity).registerReceiver(broadcastReceiver,new IntentFilter("Remove_Is_Purchased"));

    removeAdsPref=findPreference("remove_ads");
    mCategory = (PreferenceCategory)findPreference("cat_remove_ads");

    if (localPreferences.IsRemovedAdsPurchased())
    {
        mCategory.removePreference(removeAdsPref);
        getPreferenceScreen().removePreference(mCategory);
    }
    else
    {
        removeAdsPref.setOnPreferenceClickListener(this);
    }

    findPreference("move_to_sdcard").setOnPreferenceClickListener(this);
    findPreference("view_intruders").setOnPreferenceClickListener(this);
    findPreference("button_internal").setOnPreferenceClickListener(this);
    findPreference("back_up_sdcard").setOnPreferenceClickListener(this);
    findPreference("change_password").setOnPreferenceClickListener(this);
    findPreference("key_rate_us").setOnPreferenceClickListener(this);
    findPreference("app_link").setOnPreferenceClickListener(this);
    findPreference("hide_icon").setOnPreferenceClickListener(this);
    findPreference("key_share_app_link").setOnPreferenceClickListener(this);
    findPreference("listPref_wrong_tries").setOnPreferenceClickListener(this);
    findPreference("theme").setOnPreferenceClickListener(this);
    findPreference("enter_email").setOnPreferenceClickListener(this);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        findPreference("key_cam_short").setVisible(false);
        findPreference("key_vid_short").setVisible(false);
    }

    if (!PreferenceManager.getDefaultSharedPreferences(homeActivity).getBoolean("key_intruder_detection",false))
    {
        findPreference("listPref_wrong_tries").setEnabled(false);
    }
    if (!Reprint.isHardwarePresent()) {
        findPreference("key_fingerprint").setEnabled(false);
    }

    if (!FileUtilis.isSdcardPresent(getActivity())) {
        findPreference("move_to_sdcard").setEnabled(false);
        findPreference("button_internal").setEnabled(false);
        findPreference("back_up_sdcard").setEnabled(false);

        //  findPreference("change_password").setEnabled(false);
        findPreference("always_save_to_sdcard").setEnabled(false);
    }
    //add xml

}

and this is my preference xml:

<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.andr]oid.com/apk/res-auto"
app:key="preferenceScreen">

z
<android.support.v7.preference.PreferenceCategory  android:title="@string/cate_remove_ads"
    android:key="cat_remove_ads">
    <Preference
        android:key="remove_ads"
        android:summary="@string/txt_remove_ads"
        android:title="@string/remove_ads" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/storage">

    <Preference
        android:key="move_to_sdcard"
        android:summary="@string/export_sdcard_summary"
        android:title="@string/txt_move_to_external" />

    <Preference
        android:key="button_internal"
        android:summary="@string/export_internal_summary"
        android:title="@string/txt_move_too_internal" />

    <Preference
        android:key="back_up_sdcard"
        android:summary="@string/backup_summary"
        android:title="@string/back_from_sdcard" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="always_save_to_sdcard"
        android:summary="@string/always_on_sd_card"
        android:title="@string/sav_loc" />

</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/cate_security">

    <Preference
        android:key="hide_icon"
        android:title="@string/hide_icon" />

    <Preference
        android:key="app_link"
        android:summary="@string/app_link_title"
        android:title="@string/app_link_detail" />

    <Preference
        android:key="change_password"
        android:title="@string/chagne_password" />

    <Preference
        android:key="enter_email"
        android:title="@string/forgot_email_title"
        android:summary="@string/enter_email_to_recover" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="shuffle_pin"
        android:summary="@string/shuffle_summary"
        android:title="@string/shuffle_title" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_fingerprint"
        android:summary="@string/summary_fingerprint"
        android:title="@string/fingerprint_auth" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/cate_intruder">
    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_intruder_detection"
        android:summary="@string/take_intruder_picture_summary"
        android:title="@string/take_intruder_picture" />

    <android.support.v7.preference.ListPreference
        android:defaultValue="3"
        android:entries="@array/wrong_tries"
        android:entryValues="@array/wrong_tries"
        android:summary="%s"
        android:title="@string/wrong_tries"
        android:key="listPref_wrong_tries" />
    <Preference
        android:key="view_intruders"
        android:summary="@string/show_intruder_pic"
        android:title="@string/show_intruder_pic_summary" />
</android.support.v7.preference.PreferenceCategory>

<android.support.v7.preference.PreferenceCategory android:title="@string/cate_others">
    <Preference
        android:key="theme"
        android:summary="@string/chose_theme"
        android:title="@string/select_theme" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_cam_short"
        android:summary="@string/cam_short_detail"
        android:title="@string/sec_selfi_shortcut" />

    <android.support.v7.preference.SwitchPreferenceCompat
        android:defaultValue="false"
        android:key="key_vid_short"
        android:summary="@string/vid_short_detail"
        android:title="@string/sec_vid_shortcut" />

    <Preference
        android:key="key_share_app_link"
        android:summary="@string/share_app_link_detail"
        android:title="@string/share_app_link_title" />

    <Preference
        android:key="key_rate_us"
        android:summary="@string/rate_detail"
        android:title="@string/rate_us" />
</android.support.v7.preference.PreferenceCategory>

Please guide me what am I doing wrong?
Is it support libs issue or I am doing something wrong?

Body:
i solved my problem by removing this line from my fragment layout's xml

        app:layout_scrollFlags="scroll|enterAlways"

from:

  <android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:layout_scrollFlags="scroll|enterAlways"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

now it is listening to my every damn touch :D Happy coding


问:
dynamically adding textboxes to a form by the click of a button
I am a php programmer .I have a user input form in which a person should be able to add as many text boxes (to enter muliple email ids ) as he wishes , by the click of a button.eg:He clicks the button for the first time an additional text box is added.He clicks the button for the second time , another text box added ....and so on and  so forth.</p>

答:
You can create elements via document.createElement, and append them to a form via appendChild, like so:

```<code>var textbox = document.createElement('input');
textbox.type = 'text';
document.getElementById('theForm').appendChild(textbox);
</code>```

(That assumes the form has an id = "theForm", but you can get the reference to the form other ways.)

If you want to wrap it in a label, that's easy, too:

```<code>var label, textbox;
label = document.createElement('label');
label.appendChild(document.createTextNode('Another email address: '));
textbox = document.createElement('input');
textbox.type = 'text';
label.appendChild(textbox);
document.getElementById('theForm').appendChild(label);
</code>```

Live example

If you kick around the DOM specs (DOM Core 2 is the most widely-supported at present, as is the HTML stuff on top of it; DOM Core 3 is getting some support now), you'll find other things you can do — like inserting into the form in the middle rather than appending to the end, etc.

Most of the time, you can use innerHTML to add to DOM structures (it's supported by every major browser, and is getting standardized as part of HTML5), but there are some browser quirks around form fields, specifically, which is why I've gone with the DOM interface above.

You haven't said you're using a library, and so the above is pure JavaScript+DOM. It's fairly simple, but in real world use you can quickly run into complications. That's where a JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others can save you time, smoothing over browser differences and complications for you, allowing you to focus on what you're actually trying to do.

For instance, in the linked example, I had to provide a hookEvent function to handle the fact that some browsers use the (standardized) addEventListener function, while IE prior to IE9 uses attachEvent instead. And libraries will handle the form field quirks I was talking about, allowing you to specify your fields using straight HTML, like this:

Using jQuery:

```<code>$("#theForm").append("<label>Another email address: <input type='text'>");
</code>```

Live example

Using Prototype:

```<code>$("theForm").insert("<br><label>Another email address: <input type='text'>");
</code>```

Live example

ContentLicense: CC BY-SA 2.5

Body:
You can create elements via document.createElement, and append them to a form via appendChild, like so:

var textbox = document.createElement('input');
textbox.type = 'text';
document.getElementById('theForm').appendChild(textbox);

(That assumes the form has an id = "theForm", but you can get the reference to the form other ways.)

If you want to wrap it in a label, that's easy, too:

var label, textbox;
label = document.createElement('label');
label.appendChild(document.createTextNode('Another email address: '));
textbox = document.createElement('input');
textbox.type = 'text';
label.appendChild(textbox);
document.getElementById('theForm').appendChild(label);

Live example

If you kick around the DOM specs (DOM Core 2 is the most widely-supported at present, as is the HTML stuff on top of it; DOM Core 3 is getting some support now), you'll find other things you can do — like inserting into the form in the middle rather than appending to the end, etc.

Most of the time, you can use innerHTML to add to DOM structures (it's supported by every major browser, and is getting standardized as part of HTML5), but there are some browser quirks around form fields, specifically, which is why I've gone with the DOM interface above.

You haven't said you're using a library, and so the above is pure JavaScript+DOM. It's fairly simple, but in real world use you can quickly run into complications. That's where a JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others can save you time, smoothing over browser differences and complications for you, allowing you to focus on what you're actually trying to do.

For instance, in the linked example, I had to provide a hookEvent function to handle the fact that some browsers use the (standardized) addEventListener function, while IE prior to IE9 uses attachEvent instead. And libraries will handle the form field quirks I was talking about, allowing you to specify your fields using straight HTML, like this:

Using jQuery:

$("#theForm").append("<label>Another email address: <input type='text'>");

Live example

Using Prototype:

$("theForm").insert("<br><label>Another email address: <input type='text'>");

Live example


问:
.htaccess to redirect to subfolder

Im trying to do the following: if I go to www.example.com/panel -> i want to open index.php in folder panel, if I go to www.example.com/panel/somehing - i want it to translate this to www.example.com/panel/index.php?content=something

Now I've tried all sort of possible solutions here that includes redirecting to sub-folder like

```<code>RewriteCond %{REQUEST_URI} !^/subfolder/public/ [NC]
RewriteRule ^(.*)$ subfolder/public/$1 [L]
</code>```

but this completely overrides my main index.php and redirects everything to sub-folder.

And I do use simple conditions and rules like this:

```<code>RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/.+$
RewriteRule ^check-out/?$ index.php?content=check-out [NC,L]
</code>```

And this works nicely, the way I want to.

So if I'm in location

```<code>www.example.com/panel/user
</code>```

I need something like

```<code>RewriteRule ^panel/([^/]+)$ panel/index.php?content=$1 [NC,L]
</code>```

Where ([^/]+)$ and $1 would in this case represent "user" and site should redirect to

```<code>www.example.com/panel/index.php?content=user
</code>```

答:
Inside your panel/.htaccess have this code:

```<code>DirectoryIndex index.php
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .+ index.php?content=$0 [L,QSA]
</code>```

Title: .htaccess to redirect to subfolder

Body:
Im trying to do the following: if I go to www.example.com/panel -> i want to open index.php in folder panel, if I go to www.example.com/panel/somehing - i want it to translate this to www.example.com/panel/index.php?content=something

Now I've tried all sort of possible solutions here that includes redirecting to sub-folder like

RewriteCond %{REQUEST_URI} !^/subfolder/public/ [NC]
RewriteRule ^(.*)$ subfolder/public/$1 [L]

but this completely overrides my main index.php and redirects everything to sub-folder.

And I do use simple conditions and rules like this:

RewriteCond %{REQUEST_URI} !^/[0-9]+\..+\.cpaneldcv$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/.+$
RewriteRule ^check-out/?$ index.php?content=check-out [NC,L]

And this works nicely, the way I want to.

So if I'm in location

www.example.com/panel/user

I need something like

RewriteRule ^panel/([^/]+)$ panel/index.php?content=$1 [NC,L]

Where ([^/]+)$ and $1 would in this case represent "user" and site should redirect to

www.example.com/panel/index.php?content=user

Body:
Inside your panel/.htaccess have this code:

DirectoryIndex index.php
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .+ index.php?content=$0 [L,QSA]


问:
Routing in express
I have structure like this:

```<code>server.ts
routes/
    index.ts
    homeRoute.ts
</code>```

In server.ts:

```<code>let app = Express();
app.use(router);
</code>```

In routes/index.ts:

```<code>const routes = Router();
export default function router() {
  routes.use('/home', homeRoute);
}
</code>```

In routes/homeRoutes.ts

```<code>let homeRouter = Express.Router();

export default function homeRoute(req: Request, res: Response, next: NextFunction) {
  console.log('home route');
  homeRouter.get('/home', function);
  next();
}
</code>```

My problem is when i call http://localhost:3000, it run to index.ts file ( I console.log some things so I know that), however it don't execute my routes.use('/home', homeRoute).

I don't know why it is. Please help me fix it.

答:
Understand how import and export works. Ideally your code should be something like this.

server.ts

```<code>import * as express from 'express';
import {routes} from './routes';
const app = express();
routes(app);
</code>```

routes/index.ts

```<code>import {homeRoute} from './homeRoutes';
export const routes = (app) => {
  homeRoute(app);
}
</code>```

routes/homeRoutes.ts

```<code>export const homeRoute = (app) => {
  app.get('/home', function (req, res, next) {
    res.render('home');
  });
}
</code>```

Title: Routing in express

Body:
I have structure like this:

server.ts
routes/
    index.ts
    homeRoute.ts

In server.ts:

let app = Express();
app.use(router);

In routes/index.ts:

const routes = Router();
export default function router() {
  routes.use('/home', homeRoute);
}

In routes/homeRoutes.ts

let homeRouter = Express.Router();

export default function homeRoute(req: Request, res: Response, next: NextFunction) {
  console.log('home route');
  homeRouter.get('/home', function);
  next();
}

My problem is when i call http://localhost:3000, it run to index.ts file ( I console.log some things so I know that), however it don't execute my routes.use('/home', homeRoute).

I don't know why it is. Please help me fix it.

Body:
Understand how import and export works. Ideally your code should be something like this.

server.ts

import * as express from 'express';
import {routes} from './routes';
const app = express();
routes(app);

routes/index.ts

import {homeRoute} from './homeRoutes';
export const routes = (app) => {
  homeRoute(app);
}

routes/homeRoutes.ts

export const homeRoute = (app) => {
  app.get('/home', function (req, res, next) {
    res.render('home');
  });
}


问:
Laravel many migrations issue
10 people start new project with laravel.
After for example 2,3 years there will be many migrations.

In case when new programmer joins the team he will setup development environment with code and database.

The problem is that if there are many migrations it will run too slow if there are thousand of migrations.

How to handle this?

答:
Yes running 100s of migrations each time is going to become a headache. You'll want to create a snapshot of your database tables and make that your first migration.

For example lets say you have a blog with a posts and users table. For each table you're going to need a create table statement. If you're working with MySql to get your create table statement for your users table you would query:

SHOW CREATE TABLE users

Once you have your create table statements you can make a new migration which runs those queries and archive all your old migrations.

```<code>class CreateSnapshotTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Create users table
        DB::statement("
            CREATE TABLE `users` (
                `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                `password` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
                `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
                `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
                `remember_token` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
                `created_at` timestamp NULL DEFAULT NULL,
                `updated_at` timestamp NULL DEFAULT NULL,
                `deleted_at` timestamp NULL DEFAULT NULL,
                PRIMARY KEY (`id`),
                UNIQUE KEY `users_email_unique` (`email`)
            );
        ");

        // Create posts table
        DB::statement("
            CREATE TABLE `posts` (
                `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

                // ...etc.

                PRIMARY KEY (`id`),
                UNIQUE KEY `users_email_unique` (`email`)
            );
        ");
    }
}
</code>```

Title: Laravel many migrations issue

Body:
Yes running 100s of migrations each time is going to become a headache. You'll want to create a snapshot of your database tables and make that your first migration.

For example lets say you have a blog with a posts and users table. For each table you're going to need a create table statement. If you're working with MySql to get your create table statement for your users table you would query:

SHOW CREATE TABLE users

Once you have your create table statements you can make a new migration which runs those queries and archive all your old migrations.

class CreateSnapshotTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        // Create users table
        DB::statement("
            CREATE TABLE `users` (
                `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                `password` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
                `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
                `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
                `remember_token` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
                `created_at` timestamp NULL DEFAULT NULL,
                `updated_at` timestamp NULL DEFAULT NULL,
                `deleted_at` timestamp NULL DEFAULT NULL,
                PRIMARY KEY (`id`),
                UNIQUE KEY `users_email_unique` (`email`)
            );
        ");

        // Create posts table
        DB::statement("
            CREATE TABLE `posts` (
                `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

                // ...etc.

                PRIMARY KEY (`id`),
                UNIQUE KEY `users_email_unique` (`email`)
            );
        ");
    }
}


问:
Algorithm for finding all paths in a NxN grid
Imagine a robot sitting on the upper left hand corner of an NxN grid. The robot can only move in two directions: right and down. How many possible paths are there for the robot?

I could find solution to this problem on Google, but I am not very clear with the explanations. I am trying to clearly understand the logic on how to solve this and implement in Java. Any help is appreciated.

Update: This is an interview question. For now, I am trying to reach the bottom-right end and print the possible paths.

答:
Below is the code in Java to count all the possible paths from top left corner to bottom right corner of a NXN matrix.</p>

```<code>public class paths_in_matrix {

    /**
     * @param args
     */
    static int n=5;
    private boolean[][] board=new boolean[n][n];
    int numPaths=0;
    paths_in_matrix(){
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                board[i][j]=false;
            }
        }
    }
    private void togglePiece(int i,int j){
        this.board[i][j]=!this.board[i][j];
    }
    private boolean hasBeenVisited(int i,int j){
        return this.board[i][j];
    }
    private boolean exists(int i,int j){
        return i < n && i > -1 && j < n && j > -1;
    }
    private boolean viablePosition(int i,int j){
        return exists(i, j) && !hasBeenVisited(i,j);
    }
    private void traversePaths(int i,int j){
        //BASE CASE: if reached (n - 1, n - 1), count as path and stop.
        if (i == (n - 1) && j == (n - 1)) {
          this.numPaths++;
          return;
        }
        this.togglePiece(i, j);
        //RECURSIVE CASE: if next point is a viable position, go there and make the same decision

        //go right if possible
        if (this.viablePosition(i, j + 1)) {
          traversePaths(i, j + 1);
        }
      //go left if possible
        if (this.viablePosition(i, j - 1)) {
          traversePaths( i, j - 1);
        }

        //go down if possible
        if (this.viablePosition(i + 1, j)) {
          traversePaths( i + 1, j);
        }

        //go up if possible
        if (this.viablePosition(i - 1, j)) {
          traversePaths(i - 1, j);
        }

        //reset the board back to the way you found it after you've gone forward so that other paths can see it as a viable position for their routes
        this.togglePiece(i, j);

    }
    private int robotPaths(){

        traversePaths(0,0);
        return this.numPaths;
    }
    public static void main(String[] args) {
        paths_in_matrix mat=new paths_in_matrix();
        System.out.println(mat.robotPaths());
    }

}
</code>```

Body:
Below is the code in Java to count all the possible paths from top left corner to bottom right corner of a NXN matrix.

public class paths_in_matrix {

    /**
     * @param args
     */
    static int n=5;
    private boolean[][] board=new boolean[n][n];
    int numPaths=0;
    paths_in_matrix(){
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                board[i][j]=false;
            }
        }
    }
    private void togglePiece(int i,int j){
        this.board[i][j]=!this.board[i][j];
    }
    private boolean hasBeenVisited(int i,int j){
        return this.board[i][j];
    }
    private boolean exists(int i,int j){
        return i < n && i > -1 && j < n && j > -1;
    }
    private boolean viablePosition(int i,int j){
        return exists(i, j) && !hasBeenVisited(i,j);
    }
    private void traversePaths(int i,int j){
        //BASE CASE: if reached (n - 1, n - 1), count as path and stop.
        if (i == (n - 1) && j == (n - 1)) {
          this.numPaths++;
          return;
        }
        this.togglePiece(i, j);
        //RECURSIVE CASE: if next point is a viable position, go there and make the same decision

        //go right if possible
        if (this.viablePosition(i, j + 1)) {
          traversePaths(i, j + 1);
        }
      //go left if possible
        if (this.viablePosition(i, j - 1)) {
          traversePaths( i, j - 1);
        }

        //go down if possible
        if (this.viablePosition(i + 1, j)) {
          traversePaths( i + 1, j);
        }

        //go up if possible
        if (this.viablePosition(i - 1, j)) {
          traversePaths(i - 1, j);
        }

        //reset the board back to the way you found it after you've gone forward so that other paths can see it as a viable position for their routes
        this.togglePiece(i, j);

    }
    private int robotPaths(){

        traversePaths(0,0);
        return this.numPaths;
    }
    public static void main(String[] args) {
        paths_in_matrix mat=new paths_in_matrix();
        System.out.println(mat.robotPaths());
    }

}


问:
How can the assignment from int to object be possible in C++?
```<code>class phone {
    public:
        phone(int x) { num = x; }
        int number(void) { return num; }
        void number(int x) { num = x; }

    private:
        int num;
};

int main(void)
{
    phone p1(10);

    p1 = 20;    // here!

    return 0;
}
</code>```

Hi, guys

Just I declared a simple class like above one.

After that I assigned int value to the object that class, then it worked!

(I printed its value. It was stored properly)

If there is not a construct with int parameter, a compile error occurred.

So, I think it's related with a constructor. Is that right?

Please give me a good explanation.

Thanks.

答:
This is legal because C++ interprets any constructor that can be called with a single argument of type T as a means of implicitly converting from Ts to the custom object type.  In your case, the code

```<code>p1 = 20;
</code>```

is interpreted as

```<code>p1.operator= (20);
</code>```

Which is, in turn, interpreted as

```<code>p1.operator= (phone(20));
</code>```

This behavior is really weird, and it's almost certainly not what you wanted.  To disable it, you can mark the constructor explicit to disable the implicit conversion:

```<code>class phone {
    public:
        explicit phone(int x) { num = x; }
        int number(void) { return num; }
        void number(int x) { num = x; }

    private:
        int num;
};
</code>```

Now, the constructor won't be considered when doing implicit conversions, and the above code will cause an error.

Body:
class phone {
    public:
        phone(int x) { num = x; }
        int number(void) { return num; }
        void number(int x) { num = x; }

    private:
        int num;
};

int main(void)
{
    phone p1(10);

    p1 = 20;    // here!

    return 0;
}

Hi, guys

Just I declared a simple class like above one.

After that I assigned int value to the object that class, then it worked!

(I printed its value. It was stored properly)

If there is not a construct with int parameter, a compile error occurred.

So, I think it's related with a constructor. Is that right?

Please give me a good explanation.

Thanks.

Body:
This is legal because C++ interprets any constructor that can be called with a single argument of type T as a means of implicitly converting from Ts to the custom object type.  In your case, the code

p1 = 20;

is interpreted as

p1.operator= (20);

Which is, in turn, interpreted as

p1.operator= (phone(20));

This behavior is really weird, and it's almost certainly not what you wanted.  To disable it, you can mark the constructor explicit to disable the implicit conversion:

class phone {
    public:
        explicit phone(int x) { num = x; }
        int number(void) { return num; }
        void number(int x) { num = x; }

    private:
        int num;
};

Now, the constructor won't be considered when doing implicit conversions, and the above code will cause an error.


问:
All com.android.support libraries must use the exact same version specification
After updating to android studio 2.3 I got this error message.
I know it's just a hint as the app run normally but it's really strange.

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 25.1.1, 24.0.0. Examples include com.android.support:animated-vector-drawable:25.1.1 and com.android.support:mediarouter-v7:24.0.0

my gradle:

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'

    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.android.support:support-v4:25.1.1'
    compile 'com.android.support:design:25.1.1'
    compile 'com.android.support:recyclerview-v7:25.1.1'
    compile 'com.android.support:cardview-v7:25.1.1'
    compile 'com.google.android.gms:play-services-maps:10.2.0'
    compile 'com.google.android.gms:play-services:10.2.0'

    compile 'io.reactivex.rxjava2:rxjava:2.0.1'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.jakewharton:butterknife:8.4.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
    compile 'com.blankj:utilcode:1.3.6'
    compile 'com.orhanobut:logger:1.15'
    compile 'com.facebook.stetho:stetho:1.4.2'

    provided 'com.google.auto.value:auto-value:1.2'
    annotationProcessor 'com.google.auto.value:auto-value:1.2'
    annotationProcessor 'com.ryanharter.auto.value:auto-value-parcel:0.2.5'

    compile 'com.mikepenz:iconics-core:2.8.2@aar'
    compile('com.mikepenz:materialdrawer:5.8.1@aar') { transitive = true }
    compile 'com.mikepenz:google-material-typeface:2.2.0.3.original@aar'
    compile 'me.zhanghai.android.materialprogressbar:library:1.3.0'
    compile 'com.github.GrenderG:Toasty:1.1.1'
    compile 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.8.0'
    compile 'com.github.MAXDeliveryNG:slideview:1.0.0'

    compile 'com.facebook.fresco:fresco:1.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'

    compile 'com.google.maps.android:android-maps-utils:0.4.4'
    compile 'com.github.jd-alexander:library:1.1.0'
}
</code>```

答:
If the same error is on appcompat

```<code>implementation 'com.android.support:appcompat-v7:27.0.1'
</code>```

then adding design solved it.

```<code>implementation 'com.android.support:appcompat-v7:27.0.1'
implementation 'com.android.support:design:27.0.1'
</code>```

For me, adding

```<code>implementation 'de.mrmaffen:vlc-android-sdk:2.0.6'
</code>```

was including appcompat-v7:23.1.1 in

.idea/libraries

without vlc, appcompat alone is enough.

Body:
After updating to android studio 2.3 I got this error message.
I know it's just a hint as the app run normally but it's really strange.

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 25.1.1, 24.0.0. Examples include com.android.support:animated-vector-drawable:25.1.1 and com.android.support:mediarouter-v7:24.0.0

my gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    testCompile 'junit:junit:4.12'

    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.android.support:support-v4:25.1.1'
    compile 'com.android.support:design:25.1.1'
    compile 'com.android.support:recyclerview-v7:25.1.1'
    compile 'com.android.support:cardview-v7:25.1.1'
    compile 'com.google.android.gms:play-services-maps:10.2.0'
    compile 'com.google.android.gms:play-services:10.2.0'

    compile 'io.reactivex.rxjava2:rxjava:2.0.1'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.jakewharton:butterknife:8.4.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
    compile 'com.blankj:utilcode:1.3.6'
    compile 'com.orhanobut:logger:1.15'
    compile 'com.facebook.stetho:stetho:1.4.2'

    provided 'com.google.auto.value:auto-value:1.2'
    annotationProcessor 'com.google.auto.value:auto-value:1.2'
    annotationProcessor 'com.ryanharter.auto.value:auto-value-parcel:0.2.5'

    compile 'com.mikepenz:iconics-core:2.8.2@aar'
    compile('com.mikepenz:materialdrawer:5.8.1@aar') { transitive = true }
    compile 'com.mikepenz:google-material-typeface:2.2.0.3.original@aar'
    compile 'me.zhanghai.android.materialprogressbar:library:1.3.0'
    compile 'com.github.GrenderG:Toasty:1.1.1'
    compile 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.8.0'
    compile 'com.github.MAXDeliveryNG:slideview:1.0.0'

    compile 'com.facebook.fresco:fresco:1.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'

    compile 'com.google.maps.android:android-maps-utils:0.4.4'
    compile 'com.github.jd-alexander:library:1.1.0'
}

Body:
If the same error is on appcompat

implementation 'com.android.support:appcompat-v7:27.0.1'

then adding design solved it.

implementation 'com.android.support:appcompat-v7:27.0.1'
implementation 'com.android.support:design:27.0.1'

For me, adding

implementation 'de.mrmaffen:vlc-android-sdk:2.0.6'

was including appcompat-v7:23.1.1 in

.idea/libraries

without vlc, appcompat alone is enough.


问:
VBA Delete Duplicates code faster
Currently using this code, however, I have a huge set of data, and this runs really slow for that. I need to remove any duplicate information, and keep the highest row of information.

```<code>dim dup as variant, r as long, lncheckduplicatescolumn as long
With wb_DST.Sheets(sWs_DST)
     lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
     for r = lncheckduplicatescolumn  to 2 step -1
         dup = application.match(.cells(r, "A").value, .columns(1), 0)
             if dup < r then .rows(dup).delete
     next r
end with
</code>```

Data:

```<code>       Column A              Column B
          A                      1
          B                      2
          C                      3
          A                      3
</code>```

Result should be:

```<code>           B                     2
           C                     3
           A                     3
</code>```

The order of data in column A doesnt matter as long as it is unique, and retains the information that is in the higher row number. While the code I shared works, it is too slow for a large data set.

答:
Another fast method, is to use the Dictionary object. You can check if any of the values in Column A already exists in the Dictionary. If they do (meaning it's a duplicate), then don't delete them every time, this adds a long time for code's run-time. Instead, you can use a DelRng object, which is a Range that uses Union to merge multiple rows that are duplicates.

Later on, you can delete the entire ducplicates range at once by using DelRng.Delete.

Code

```<code>Option Explicit

Sub RemoveDuplicatesUsingDict()

Dim wb_DST As Workbook
Dim sWs_DST As String

'  Dictionary variables
Dim Dict As Object
Dim DictIndex As Long, ExistIndex As Long

Dim DelRng As Range
Dim LastRow As Long, i As Long

' --- parameters for my internal testing ---
Set wb_DST = ThisWorkbook
sWs_DST = "Sheet1"

Application.ScreenUpdating = False

Set Dict = CreateObject("Scripting.Dictionary")

With wb_DST.Sheets(sWs_DST)
     LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' get last row with data in column "A"

     For i = LastRow To 2 Step -1
        If Not Dict.exists(.Range("A" & i).Value) Then ' value doesn't exists yet in Dictionary >> add this Key
            Dict.Add .Range("A" & i).Value, .Range("A" & i).Value
        Else ' value already exists in Dictionary >> add it to DelRng (later will delete the entire range)
            If Not DelRng Is Nothing Then
                Set DelRng = Application.Union(DelRng, .Rows(i)) ' add current row to existing DelRng
            Else
                Set DelRng = .Rows(i)
            End If
        End If
     Next i
End With

' delete the entire range at 1-shot
If Not DelRng Is Nothing Then DelRng.Delete

Application.ScreenUpdating = True

End Sub
</code>```

Title: VBA Delete Duplicates code faster

Body:
Currently using this code, however, I have a huge set of data, and this runs really slow for that. I need to remove any duplicate information, and keep the highest row of information.

dim dup as variant, r as long, lncheckduplicatescolumn as long
With wb_DST.Sheets(sWs_DST)
     lncheckduplicatescolumn = .Cells(.Rows.Count, "A").End(xlUp).row
     for r = lncheckduplicatescolumn  to 2 step -1
         dup = application.match(.cells(r, "A").value, .columns(1), 0)
             if dup < r then .rows(dup).delete
     next r
end with

Data:

       Column A              Column B
          A                      1
          B                      2
          C                      3
          A                      3

Result should be:

           B                     2
           C                     3
           A                     3

The order of data in column A doesnt matter as long as it is unique, and retains the information that is in the higher row number. While the code I shared works, it is too slow for a large data set.

Body:
Another fast method, is to use the Dictionary object. You can check if any of the values in Column A already exists in the Dictionary. If they do (meaning it's a duplicate), then don't delete them every time, this adds a long time for code's run-time. Instead, you can use a DelRng object, which is a Range that uses Union to merge multiple rows that are duplicates.

Later on, you can delete the entire ducplicates range at once by using DelRng.Delete.

Code

Option Explicit

Sub RemoveDuplicatesUsingDict()

Dim wb_DST As Workbook
Dim sWs_DST As String

'  Dictionary variables
Dim Dict As Object
Dim DictIndex As Long, ExistIndex As Long

Dim DelRng As Range
Dim LastRow As Long, i As Long

' --- parameters for my internal testing ---
Set wb_DST = ThisWorkbook
sWs_DST = "Sheet1"

Application.ScreenUpdating = False

Set Dict = CreateObject("Scripting.Dictionary")

With wb_DST.Sheets(sWs_DST)
     LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' get last row with data in column "A"

     For i = LastRow To 2 Step -1
        If Not Dict.exists(.Range("A" & i).Value) Then ' value doesn't exists yet in Dictionary >> add this Key
            Dict.Add .Range("A" & i).Value, .Range("A" & i).Value
        Else ' value already exists in Dictionary >> add it to DelRng (later will delete the entire range)
            If Not DelRng Is Nothing Then
                Set DelRng = Application.Union(DelRng, .Rows(i)) ' add current row to existing DelRng
            Else
                Set DelRng = .Rows(i)
            End If
        End If
     Next i
End With

' delete the entire range at 1-shot
If Not DelRng Is Nothing Then DelRng.Delete

Application.ScreenUpdating = True

End Sub


问:
Background thread that loads data in asp.net
I want to load data to my application domain using a thread so it will be executed at all times. How can I achieve this? I want the thread will start when iis starts and terminate when iis exits.

Note:
I want to do this so I can use disconnected architecture in my asp.net application.

Thanks in advance,
Kfir

答:
Kfir,

The simplest way to do this is to launch a blocking background-worker during the App_Start() method on Global.asax and then to kill it using App_Stop() in Global.asax.

Have the thread sit on a WaitHandle until it's ready for more data and then signal it to wait back up. Or if you really wanted to code something ghetto, you could just have it poll on a fixed interval using a timer.


问:
how to add filters on vb HttpWebRequest
This code, is working perfectly (getting data with web request) :

```<code> Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim oauth_token = "8e269b44b2d7d73eb0b46112af5f4xxx"
    Dim oauth_token_secret = "80da1edadcba1e66e47d2e20f075cxxx"
    Dim oauth_consumer_key = "3626311748bcf2072da2bd475fccfxxx"
    Dim oauth_consumer_secret = "0cbb0df8d840e22b96d4f80449e7exxx"
    Dim oauth_version = "1.0"
    Dim oauth_signature_method = "HMAC-SHA1"
    Dim oauth_nonce = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
    Dim timeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
    Dim oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
    Dim resource_url = "http://www.inart.com/api/rest/products/store/1"
    Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}"
    Dim baseString = String.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, oauth_version)
    baseString = String.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString))
    Dim compositeKey = String.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret))
    Dim oauth_signature As String
    Using hasher As New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))
        oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
    End Using
    Dim headerFormat = "OAuth oauth_nonce=""{0}"", oauth_signature_method=""{1}"", " + "oauth_timestamp=""{2}"", oauth_consumer_key=""{3}"",
                        " + "oauth_token=""{4}"", oauth_signature=""{5}"", " + "oauth_version=""{6}"""
    Dim authHeader = String.Format(headerFormat, Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp),
                     Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_version))
    ServicePointManager.Expect100Continue = True
    Dim request As HttpWebRequest = DirectCast(WebRequest.Create(resource_url), HttpWebRequest)
    request.Headers.Add("Authorization", authHeader)
    request.Method = "GET"
    request.ContentType = "application/json"
    request.Accept = "application/json"
    Try
        Dim response As WebResponse = request.GetResponse()
        Dim datastream As Stream = response.GetResponseStream
        Dim reader As StreamReader = New StreamReader(datastream)
        Dim responsefromserver As String = reader.ReadToEnd
        If responsefromserver = Nothing Then
            TextBox1.Text = "No response from server"
        Else
            Dim json As String = responsefromserver
            Dim ser As JObject = JObject.Parse(json)
            Dim data As List(Of JToken) = ser.Children().ToList
            Dim output As String = ""
            Dim successReq As Boolean = False
            Dim avDom As String = ""
            Dim counter As Integer = 0
            For Each item As JProperty In data
                item.CreateReader()
                output += "|-" & item.Name.ToString & " :  " & item.Value.ToString & "-"
                output += Environment.NewLine
                counter += 1
            Next
            TextBox1.Text = output
            TextBox1.Text += Environment.NewLine + counter.ToString
            reader.Close()
            response.Close()
        End If
    Catch ex As Exception
        TextBox1.Text = ex.Message.ToString
    End Try
End Sub
</code>```

When i try to add some filters, it fails. for example, I try to add the limit filter this way : Dim resource_url = "http://www.inart.com/api/rest/products/store/1?limit=1".

I am sure that the filter is ok because i tried at postman application and it is working! see print screen

What should I change or add?
Thank you.

答:
```<code> Dim url As String = "http://www.inart.com/api/rest/products/store/1?limit=1&page=2"
        Dim oauthconsumerkey As String = "3626311748bcf2072da2bd475fccssss"
        Dim oauthconsumersecret As String = "0cbb0df8d840e22b96d4f80449sssss"
        Dim oauthtoken As String = "8e269b44b2d7d73essss2af5f454e"
        Dim oauthtokensecret As String = "80da1edadcba1e66e47d2e2sssss"
        Dim oauthsignaturemethod As String = "HMAC-SHA1"
        Dim oauthversion As String = "1.0"
        Dim oauthnonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
        Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
        Dim oauthtimestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
        Dim basestringParameters As SortedDictionary(Of String, String) = New SortedDictionary(Of String, String)()
        basestringParameters.Add("limit", "1")
        basestringParameters.Add("page", "2")
        basestringParameters.Add("oauth_version", oauthversion)
        basestringParameters.Add("oauth_consumer_key", oauthconsumerkey)
        basestringParameters.Add("oauth_nonce", oauthnonce)
        basestringParameters.Add("oauth_signature_method", oauthsignaturemethod)
        basestringParameters.Add("oauth_timestamp", oauthtimestamp)
        basestringParameters.Add("oauth_token", oauthtoken)
        Dim baseString As StringBuilder = New StringBuilder()
        baseString.Append("GET" & "&")
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split("?"c)(0)) & "&"))
        For Each entry As KeyValuePair(Of String, String) In basestringParameters
            baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key & "=" + entry.Value & "&")))
        Next
        Dim finalBaseString As String = baseString.ToString().Substring(0, baseString.Length - 3)
        Dim signingKey As String = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) & "&" + EncodeCharacters(Uri.EscapeDataString(oauthtokensecret))
        Dim hasher As HMACSHA1 = New HMACSHA1(New ASCIIEncoding().GetBytes(signingKey))
        Dim oauthsignature As String = Convert.ToBase64String(hasher.ComputeHash(New ASCIIEncoding().GetBytes(finalBaseString)))
        ServicePointManager.Expect100Continue = False
        Dim wRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
        Dim authorizationHeaderParams As StringBuilder = New StringBuilder()
        authorizationHeaderParams.Append("OAuth ")
        authorizationHeaderParams.Append("oauth_nonce=" & """" + Uri.EscapeDataString(oauthnonce) & """,")
        authorizationHeaderParams.Append("oauth_signature_method=" & """" + Uri.EscapeDataString(oauthsignaturemethod) & """,")
        authorizationHeaderParams.Append("oauth_timestamp=" & """" + Uri.EscapeDataString(oauthtimestamp) & """,")
        authorizationHeaderParams.Append("oauth_consumer_key=" & """" + Uri.EscapeDataString(oauthconsumerkey) & """,")
        If Not String.IsNullOrEmpty(oauthtoken) Then authorizationHeaderParams.Append("oauth_token=" & """" + Uri.EscapeDataString(oauthtoken) & """,")
        authorizationHeaderParams.Append("oauth_signature=" & """" + Uri.EscapeDataString(oauthsignature) & """,")
        authorizationHeaderParams.Append("oauth_version=" & """" + Uri.EscapeDataString(oauthversion) & """")
        wRequest.Headers.Add("Authorization", authorizationHeaderParams.ToString)
        wRequest.Method = "GET"
        wRequest.ContentType = "application/json"
        wRequest.Accept = "application/json"
        Try
            Dim wResponse As WebResponse = wRequest.GetResponse()
            Dim dataStream As Stream = wResponse.GetResponseStream()
            Dim reader As StreamReader = New StreamReader(dataStream)
            Dim responseFromServer As String = reader.ReadToEnd()
            If responseFromServer = Nothing Then
                TextBox1.Text = "No response from server"
            Else
                Dim json As String = responseFromServer
                Dim ser As JObject = JObject.Parse(json)
                Dim data As List(Of JToken) = ser.Children().ToList
                Dim output As String = ""
                Dim successReq As Boolean = False
                Dim avDom As String = ""
                For Each item As JProperty In data
                    item.CreateReader()
                    output += "|-" & item.Name.ToString & " :  " & item.Value.ToString & "-"
                    output += Environment.NewLine
                Next
                TextBox1.Text = output
            End If
        Catch ex As Exception
            TextBox1.Text = ex.Message.ToString
        End Try

Private Function EncodeCharacters(ByVal data As String) As String
    If data.Contains("!") Then data = data.Replace("!", "%21")
    If data.Contains("'") Then data = data.Replace("'", "%27")
    If data.Contains("(") Then data = data.Replace("(", "%28")
    If data.Contains(")") Then data = data.Replace(")", "%29")
    If data.Contains("*") Then data = data.Replace("*", "%2A")
    If data.Contains(",") Then data = data.Replace(",", "%2C")
    Return data
End Function
</code>```

This example is working

Title: how to add filters on vb HttpWebRequest

Body:
This code, is working perfectly (getting data with web request) :

 Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim oauth_token = "8e269b44b2d7d73eb0b46112af5f4xxx"
    Dim oauth_token_secret = "80da1edadcba1e66e47d2e20f075cxxx"
    Dim oauth_consumer_key = "3626311748bcf2072da2bd475fccfxxx"
    Dim oauth_consumer_secret = "0cbb0df8d840e22b96d4f80449e7exxx"
    Dim oauth_version = "1.0"
    Dim oauth_signature_method = "HMAC-SHA1"
    Dim oauth_nonce = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
    Dim timeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
    Dim oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
    Dim resource_url = "http://www.inart.com/api/rest/products/store/1"
    Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}"
    Dim baseString = String.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, oauth_version)
    baseString = String.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString))
    Dim compositeKey = String.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret))
    Dim oauth_signature As String
    Using hasher As New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))
        oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
    End Using
    Dim headerFormat = "OAuth oauth_nonce=""{0}"", oauth_signature_method=""{1}"", " + "oauth_timestamp=""{2}"", oauth_consumer_key=""{3}"",
                        " + "oauth_token=""{4}"", oauth_signature=""{5}"", " + "oauth_version=""{6}"""
    Dim authHeader = String.Format(headerFormat, Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp),
                     Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_version))
    ServicePointManager.Expect100Continue = True
    Dim request As HttpWebRequest = DirectCast(WebRequest.Create(resource_url), HttpWebRequest)
    request.Headers.Add("Authorization", authHeader)
    request.Method = "GET"
    request.ContentType = "application/json"
    request.Accept = "application/json"
    Try
        Dim response As WebResponse = request.GetResponse()
        Dim datastream As Stream = response.GetResponseStream
        Dim reader As StreamReader = New StreamReader(datastream)
        Dim responsefromserver As String = reader.ReadToEnd
        If responsefromserver = Nothing Then
            TextBox1.Text = "No response from server"
        Else
            Dim json As String = responsefromserver
            Dim ser As JObject = JObject.Parse(json)
            Dim data As List(Of JToken) = ser.Children().ToList
            Dim output As String = ""
            Dim successReq As Boolean = False
            Dim avDom As String = ""
            Dim counter As Integer = 0
            For Each item As JProperty In data
                item.CreateReader()
                output += "|-" & item.Name.ToString & " :  " & item.Value.ToString & "-"
                output += Environment.NewLine
                counter += 1
            Next
            TextBox1.Text = output
            TextBox1.Text += Environment.NewLine + counter.ToString
            reader.Close()
            response.Close()
        End If
    Catch ex As Exception
        TextBox1.Text = ex.Message.ToString
    End Try
End Sub

When i try to add some filters, it fails. for example, I try to add the limit filter this way : Dim resource_url = "http://www.inart.com/api/rest/products/store/1?limit=1".

I am sure that the filter is ok because i tried at postman application and it is working! see print screen

What should I change or add?
Thank you.

Body:
 Dim url As String = "http://www.inart.com/api/rest/products/store/1?limit=1&page=2"
        Dim oauthconsumerkey As String = "3626311748bcf2072da2bd475fccssss"
        Dim oauthconsumersecret As String = "0cbb0df8d840e22b96d4f80449sssss"
        Dim oauthtoken As String = "8e269b44b2d7d73essss2af5f454e"
        Dim oauthtokensecret As String = "80da1edadcba1e66e47d2e2sssss"
        Dim oauthsignaturemethod As String = "HMAC-SHA1"
        Dim oauthversion As String = "1.0"
        Dim oauthnonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
        Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
        Dim oauthtimestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
        Dim basestringParameters As SortedDictionary(Of String, String) = New SortedDictionary(Of String, String)()
        basestringParameters.Add("limit", "1")
        basestringParameters.Add("page", "2")
        basestringParameters.Add("oauth_version", oauthversion)
        basestringParameters.Add("oauth_consumer_key", oauthconsumerkey)
        basestringParameters.Add("oauth_nonce", oauthnonce)
        basestringParameters.Add("oauth_signature_method", oauthsignaturemethod)
        basestringParameters.Add("oauth_timestamp", oauthtimestamp)
        basestringParameters.Add("oauth_token", oauthtoken)
        Dim baseString As StringBuilder = New StringBuilder()
        baseString.Append("GET" & "&")
        baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split("?"c)(0)) & "&"))
        For Each entry As KeyValuePair(Of String, String) In basestringParameters
            baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key & "=" + entry.Value & "&")))
        Next
        Dim finalBaseString As String = baseString.ToString().Substring(0, baseString.Length - 3)
        Dim signingKey As String = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) & "&" + EncodeCharacters(Uri.EscapeDataString(oauthtokensecret))
        Dim hasher As HMACSHA1 = New HMACSHA1(New ASCIIEncoding().GetBytes(signingKey))
        Dim oauthsignature As String = Convert.ToBase64String(hasher.ComputeHash(New ASCIIEncoding().GetBytes(finalBaseString)))
        ServicePointManager.Expect100Continue = False
        Dim wRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
        Dim authorizationHeaderParams As StringBuilder = New StringBuilder()
        authorizationHeaderParams.Append("OAuth ")
        authorizationHeaderParams.Append("oauth_nonce=" & """" + Uri.EscapeDataString(oauthnonce) & """,")
        authorizationHeaderParams.Append("oauth_signature_method=" & """" + Uri.EscapeDataString(oauthsignaturemethod) & """,")
        authorizationHeaderParams.Append("oauth_timestamp=" & """" + Uri.EscapeDataString(oauthtimestamp) & """,")
        authorizationHeaderParams.Append("oauth_consumer_key=" & """" + Uri.EscapeDataString(oauthconsumerkey) & """,")
        If Not String.IsNullOrEmpty(oauthtoken) Then authorizationHeaderParams.Append("oauth_token=" & """" + Uri.EscapeDataString(oauthtoken) & """,")
        authorizationHeaderParams.Append("oauth_signature=" & """" + Uri.EscapeDataString(oauthsignature) & """,")
        authorizationHeaderParams.Append("oauth_version=" & """" + Uri.EscapeDataString(oauthversion) & """")
        wRequest.Headers.Add("Authorization", authorizationHeaderParams.ToString)
        wRequest.Method = "GET"
        wRequest.ContentType = "application/json"
        wRequest.Accept = "application/json"
        Try
            Dim wResponse As WebResponse = wRequest.GetResponse()
            Dim dataStream As Stream = wResponse.GetResponseStream()
            Dim reader As StreamReader = New StreamReader(dataStream)
            Dim responseFromServer As String = reader.ReadToEnd()
            If responseFromServer = Nothing Then
                TextBox1.Text = "No response from server"
            Else
                Dim json As String = responseFromServer
                Dim ser As JObject = JObject.Parse(json)
                Dim data As List(Of JToken) = ser.Children().ToList
                Dim output As String = ""
                Dim successReq As Boolean = False
                Dim avDom As String = ""
                For Each item As JProperty In data
                    item.CreateReader()
                    output += "|-" & item.Name.ToString & " :  " & item.Value.ToString & "-"
                    output += Environment.NewLine
                Next
                TextBox1.Text = output
            End If
        Catch ex As Exception
            TextBox1.Text = ex.Message.ToString
        End Try

Private Function EncodeCharacters(ByVal data As String) As String
    If data.Contains("!") Then data = data.Replace("!", "%21")
    If data.Contains("'") Then data = data.Replace("'", "%27")
    If data.Contains("(") Then data = data.Replace("(", "%28")
    If data.Contains(")") Then data = data.Replace(")", "%29")
    If data.Contains("*") Then data = data.Replace("*", "%2A")
    If data.Contains(",") Then data = data.Replace(",", "%2C")
    Return data
End Function

This example is working


问:
MIkrotik backup script
I need your help, I am trying to create a backup file on mikrotik, but it always fail to create a backup can you help me please?

```<code>/system backup save name=([/system identity get name]"_"[/system clock get date]"log")
</code>```

Format  should be Hostname_MonthDaybackup.backup. For example Mikrotik_1205Log.backup

Can you help me please? Thank you.

Adrian

答:
Export fails because the "date" part contains / ("dec/06/2017"), which I think is not allowed in file names. You have to extract day and month with the :pick command.

```<code>:local name [/system identity get name];
:local date [/system clock get date];
:local day [ :pick $date 4 6 ]
:local month [ :pick $date 0 3 ]
:local backupName ($name."_".$day."-".$month."_log");
:put $backupName

/system backup save name=$backupName
</code>```

And by the way I would not use the "backup" command, rather use the "export" command which is more portable (but doesn't save certificates and passwords).

Title: MIkrotik backup script

Body:
I need your help, I am trying to create a backup file on mikrotik, but it always fail to create a backup can you help me please?

/system backup save name=([/system identity get name]"_"[/system clock get date]"log")

Format  should be Hostname_MonthDaybackup.backup. For example Mikrotik_1205Log.backup

Can you help me please? Thank you.

Adrian

Body:
Export fails because the "date" part contains / ("dec/06/2017"), which I think is not allowed in file names. You have to extract day and month with the :pick command.

:local name [/system identity get name];
:local date [/system clock get date];
:local day [ :pick $date 4 6 ]
:local month [ :pick $date 0 3 ]
:local backupName ($name."_".$day."-".$month."_log");
:put $backupName

/system backup save name=$backupName

And by the way I would not use the "backup" command, rather use the "export" command which is more portable (but doesn't save certificates and passwords).