问:
Spring Scheduling - Cron expression for everyday at midnight not working?
I am trying to schedule a task in Spring which is to be run everyday at midnight. I followed the official guide from Spring and made the scheduler class as below:

```<code>@Component
public class OverduePaymentScheduler {
    @Scheduled(cron = "0 0 0 * * *")
    public void trackOverduePayments() {
        System.out.println("Scheduled task running");
    }
}
</code>```

However the task does not run when the clock hits 12am. I got the cron expression from the documentation for quartz scheduler at this link.

The scheduler is executed fine if I change the cron expression to "*/10 * * * * *" which runs every ten seconds.

So what am I doing wrong?

答:
I finally got it to work with this cron expression 0 0 0 * * * but I had to set the time zone in the scheduler class like this.
@Scheduled(cron = "0 0 0 * * *",zone = "Indian/Maldives")

Body:
I am trying to schedule a task in Spring which is to be run everyday at midnight. I followed the official guide from Spring and made the scheduler class as below:

@Component
public class OverduePaymentScheduler {
    @Scheduled(cron = "0 0 0 * * *")
    public void trackOverduePayments() {
        System.out.println("Scheduled task running");
    }
}

However the task does not run when the clock hits 12am. I got the cron expression from the documentation for quartz scheduler at this link.

The scheduler is executed fine if I change the cron expression to "*/10 * * * * *" which runs every ten seconds.

So what am I doing wrong?


来源: stackexchange

问:
In what situation should the built-in 'operator' module be used in python?
I'm speaking of this module:
http://docs.python.org/library/operator.html

From the article:

The operator module exports a set of
  functions implemented in C
  corresponding to the intrinsic
  operators of Python. For example,
  operator.add(x, y) is equivalent to
  the expression x+y. The function names
  are those used for special class
  methods; variants without leading and
  trailing __ are also provided for
  convenience.

I'm not sure I understand the benefit or purpose of this module.

答:
for example get column in list whose member is tuple, sort sequence by column:

```<code>def item_ope():
    s = ['h', 'e', 'l', 'l', 'o']
    print operator.getitem(s, 1)
    # e
    print operator.itemgetter(1, 4)(s)
    # ('e', 'o')

    inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
    get_count = operator.itemgetter(1)
    print map(get_count, inventory)
    # [3, 2, 5, 1]

    print sorted(inventory, key=get_count)
    # [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]
</code>```

see a more practical example, we want to sort a dict by key or value:

```<code>def dict_sort_by_value():
    dic_num = {'first': 11, 'second': 2, 'third': 33, 'Fourth': 4}

    # print all the keys
    print dic_num.keys()
    # ['second', 'Fourth', 'third', 'first']

    # sorted by value
    sorted_val = sorted(dic_num.items(), key=operator.itemgetter(1))
    # [('second', 2), ('Fourth', 4), ('first', 11), ('third', 33)]
    print sorted_val

    # sorted by key
    sorted_key = sorted(dic_num.items(), key=operator.itemgetter(0))
    print sorted_key
    # [('Fourth', 4), ('first', 11), ('second', 2), ('third', 33)]
</code>```

another example when we want get the max value and it's index in list:

```<code>def get_max_val_idx():
    lst = [1, 7, 3, 5, 6]
    max_val = max(lst)
    print max_val
    # 7
    max_idx = lst.index(max_val)
    print max_idx
    # 1

    # simplify it by use operator
    index, value = max(enumerate(lst), key=operator.itemgetter(1))
    print index, value
    # 1 7
</code>```

More demos like below:

```<code>import operator

def cmp_fun():
    a, b = 5, 3
    print operator.le(a, b)
    # False
    print operator.gt(a, b)
    # True

def lst_ope():
    lst = [1, 2, 3]
    print operator.indexOf(lst, 2)
    # 1
    lst1 = [1, 2, 3, 2]
    print operator.countOf(lst1, 2)
    # 2

def cal_ope():
    lst1 = [0, 1, 2, 3]
    lst2 = [10, 20, 30, 40]
    print map(operator.mul, lst1, lst2)
    # [0, 20, 60, 120]

    print sum(map(operator.mul, lst1, lst2))
    # 200

    a, b = 1, 3
    print operator.iadd(a, b)
    # 4
</code>```

see more from python doc

OwnerDisplayName: Bjorn Tipling

ContentLicense: CC BY-SA 2.5

Body:
for example get column in list whose member is tuple, sort sequence by column:

def item_ope():
    s = ['h', 'e', 'l', 'l', 'o']
    print operator.getitem(s, 1)
    # e
    print operator.itemgetter(1, 4)(s)
    # ('e', 'o')

    inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
    get_count = operator.itemgetter(1)
    print map(get_count, inventory)
    # [3, 2, 5, 1]

    print sorted(inventory, key=get_count)
    # [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]

see a more practical example, we want to sort a dict by key or value:

def dict_sort_by_value():
    dic_num = {'first': 11, 'second': 2, 'third': 33, 'Fourth': 4}

    # print all the keys
    print dic_num.keys()
    # ['second', 'Fourth', 'third', 'first']

    # sorted by value
    sorted_val = sorted(dic_num.items(), key=operator.itemgetter(1))
    # [('second', 2), ('Fourth', 4), ('first', 11), ('third', 33)]
    print sorted_val

    # sorted by key
    sorted_key = sorted(dic_num.items(), key=operator.itemgetter(0))
    print sorted_key
    # [('Fourth', 4), ('first', 11), ('second', 2), ('third', 33)]

another example when we want get the max value and it's index in list:

def get_max_val_idx():
    lst = [1, 7, 3, 5, 6]
    max_val = max(lst)
    print max_val
    # 7
    max_idx = lst.index(max_val)
    print max_idx
    # 1

    # simplify it by use operator
    index, value = max(enumerate(lst), key=operator.itemgetter(1))
    print index, value
    # 1 7

More demos like below:

import operator

def cmp_fun():
    a, b = 5, 3
    print operator.le(a, b)
    # False
    print operator.gt(a, b)
    # True

def lst_ope():
    lst = [1, 2, 3]
    print operator.indexOf(lst, 2)
    # 1
    lst1 = [1, 2, 3, 2]
    print operator.countOf(lst1, 2)
    # 2

def cal_ope():
    lst1 = [0, 1, 2, 3]
    lst2 = [10, 20, 30, 40]
    print map(operator.mul, lst1, lst2)
    # [0, 20, 60, 120]

    print sum(map(operator.mul, lst1, lst2))
    # 200

    a, b = 1, 3
    print operator.iadd(a, b)
    # 4

see more from python doc

ContentLicense: CC BY-SA 4.0


问:
How to extract substring using regex into multiple column using data.table
I have the following process done using dplyr without any problem:

```<code>library(tidyverse)
my_dplyr_dat  <- structure(list(chrn = c("chr20", "chr6", "chr5"), start = c(52447674L,
12962440L, 66453982L), end = c(52447689L, 12962455L, 66453997L
), motif_name_binned = c("ZNF263/MA0528.1/Jaspar.instid_chr20:52447338-52447738.bin22",
"Klf12/MA0742.1/Jaspar.instid_chr6:12962360-12962760.bin6", "Hoxc9/MA0485.1/Jaspar.instid_chr5:66453806-66454206.bin12"
), motif_score = c(6.728401, -0.979777, 6.091471), strand = c("+",
"+", "+"), read_count = c(0L, 0L, 0L)), .Names = c("chrn", "start",
"end", "motif_name_binned", "motif_score", "strand", "read_count"
), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
))
</code>```

That looks like this:

```<code># A tibble: 3 x 7
   chrn    start      end                                           motif_name_binned motif_score strand read_count
  <chr>    <int>    <int>                                                       <chr>       <dbl>  <chr>      <int>
1 chr20 52447674 52447689 ZNF263/MA0528.1/Jaspar.instid_chr20:52447338-52447738.bin22    6.728401      +          0
2  chr6 12962440 12962455    Klf12/MA0742.1/Jaspar.instid_chr6:12962360-12962760.bin6   -0.979777      +          0
3  chr5 66453982 66453997   Hoxc9/MA0485.1/Jaspar.instid_chr5:66453806-66454206.bin12    6.091471      +          0
</code>```

The main task I wish to achieve there is to extract motif_name_binned column using regex and spread it into 3 colums c('motif', 'inst', 'binno'), using dplyr it can be done this way:

```<code>my_dplyr_dat %>%
  extract(motif_name_binned, c('motif', 'inst', 'binno'), regex = "^(.*?\\/.*?)\\.instid_(.*?)\\.bin(\\d+)", remove = FALSE) %>%
  select(-motif_name_binned)
</code>```

Which produces this:

```<code># A tibble: 3 x 9
   chrn    start      end                  motif                    inst binno motif_score strand read_count
* <chr>    <int>    <int>                  <chr>                   <chr> <chr>       <dbl>  <chr>      <int>
1 chr20 52447674 52447689 ZNF263/MA0528.1/Jaspar chr20:52447338-52447738    22    6.728401      +          0
2  chr6 12962440 12962455  Klf12/MA0742.1/Jaspar  chr6:12962360-12962760     6   -0.979777      +          0
3  chr5 66453982 66453997  Hoxc9/MA0485.1/Jaspar  chr5:66453806-66454206    12    6.091471      +          0
</code>```

How can I do it with data.table?

This is the original data in data.table format I have (i.e. before string extraction etc):

```<code>library(data.table)
my_data_table <- structure(list(chrn = c("chr20", "chr6", "chr5"), start = c(52447674L,
12962440L, 66453982L), end = c(52447689L, 12962455L, 66453997L
), motif_name_binned = c("ZNF263/MA0528.1/Jaspar.instid_chr20:52447338-52447738.bin22",
"Klf12/MA0742.1/Jaspar.instid_chr6:12962360-12962760.bin6", "Hoxc9/MA0485.1/Jaspar.instid_chr5:66453806-66454206.bin12"
), motif_score = c(6.728401, -0.979777, 6.091471), strand = c("+",
"+", "+"), read_count = c(0L, 0L, 0L)), .Names = c("chrn", "start",
"end", "motif_name_binned", "motif_score", "strand", "read_count"
), class = c("data.table", "data.frame"), row.names = c(NA, -3L
))
</code>```

Which looks like this:

```<code>    chrn    start      end                                           motif_name_binned motif_score strand read_count
1: chr20 52447674 52447689 ZNF263/MA0528.1/Jaspar.instid_chr20:52447338-52447738.bin22    6.728401      +          0
2:  chr6 12962440 12962455    Klf12/MA0742.1/Jaspar.instid_chr6:12962360-12962760.bin6   -0.979777      +          0
3:  chr5 66453982 66453997   Hoxc9/MA0485.1/Jaspar.instid_chr5:66453806-66454206.bin12    6.091471      +          0
</code>```

答:
We create a unique splitting character with gsub and with tstrsplit split based on the character into 3 columns

```<code>my_data_table[, c('motif', 'inst', 'binno') := tstrsplit(
   gsub("^(.*?\\/.*?)\\.instid_(.*?)\\.bin(\\d+)", "\\1$\\2$\\3", motif_name_binned), '$',
       fixed = TRUE)][, setdiff(names(my_data_table), "motif_name_binned"), with = FALSE]
#    chrn    start      end motif_score strand read_count                  motif                    inst binno
#1: chr20 52447674 52447689    6.728401      +          0 ZNF263/MA0528.1/Jaspar chr20:52447338-52447738    22
#2:  chr6 12962440 12962455   -0.979777      +          0  Klf12/MA0742.1/Jaspar  chr6:12962360-12962760     6
#3:  chr5 66453982 66453997    6.091471      +          0  Hoxc9/MA0485.1/Jaspar  chr5:66453806-66454206    12
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following process done using dplyr without any problem:

library(tidyverse)
my_dplyr_dat  <- structure(list(chrn = c("chr20", "chr6", "chr5"), start = c(52447674L,
12962440L, 66453982L), end = c(52447689L, 12962455L, 66453997L
), motif_name_binned = c("ZNF263/MA0528.1/Jaspar.instid_chr20:52447338-52447738.bin22",
"Klf12/MA0742.1/Jaspar.instid_chr6:12962360-12962760.bin6", "Hoxc9/MA0485.1/Jaspar.instid_chr5:66453806-66454206.bin12"
), motif_score = c(6.728401, -0.979777, 6.091471), strand = c("+",
"+", "+"), read_count = c(0L, 0L, 0L)), .Names = c("chrn", "start",
"end", "motif_name_binned", "motif_score", "strand", "read_count"
), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
))

That looks like this:

# A tibble: 3 x 7
   chrn    start      end                                           motif_name_binned motif_score strand read_count
  <chr>    <int>    <int>                                                       <chr>       <dbl>  <chr>      <int>
1 chr20 52447674 52447689 ZNF263/MA0528.1/Jaspar.instid_chr20:52447338-52447738.bin22    6.728401      +          0
2  chr6 12962440 12962455    Klf12/MA0742.1/Jaspar.instid_chr6:12962360-12962760.bin6   -0.979777      +          0
3  chr5 66453982 66453997   Hoxc9/MA0485.1/Jaspar.instid_chr5:66453806-66454206.bin12    6.091471      +          0

The main task I wish to achieve there is to extract motif_name_binned column using regex and spread it into 3 colums c('motif', 'inst', 'binno'), using dplyr it can be done this way:

my_dplyr_dat %>%
  extract(motif_name_binned, c('motif', 'inst', 'binno'), regex = "^(.*?\\/.*?)\\.instid_(.*?)\\.bin(\\d+)", remove = FALSE) %>%
  select(-motif_name_binned)

Which produces this:

# A tibble: 3 x 9
   chrn    start      end                  motif                    inst binno motif_score strand read_count
* <chr>    <int>    <int>                  <chr>                   <chr> <chr>       <dbl>  <chr>      <int>
1 chr20 52447674 52447689 ZNF263/MA0528.1/Jaspar chr20:52447338-52447738    22    6.728401      +          0
2  chr6 12962440 12962455  Klf12/MA0742.1/Jaspar  chr6:12962360-12962760     6   -0.979777      +          0
3  chr5 66453982 66453997  Hoxc9/MA0485.1/Jaspar  chr5:66453806-66454206    12    6.091471      +          0

How can I do it with data.table?

This is the original data in data.table format I have (i.e. before string extraction etc):

library(data.table)
my_data_table <- structure(list(chrn = c("chr20", "chr6", "chr5"), start = c(52447674L,
12962440L, 66453982L), end = c(52447689L, 12962455L, 66453997L
), motif_name_binned = c("ZNF263/MA0528.1/Jaspar.instid_chr20:52447338-52447738.bin22",
"Klf12/MA0742.1/Jaspar.instid_chr6:12962360-12962760.bin6", "Hoxc9/MA0485.1/Jaspar.instid_chr5:66453806-66454206.bin12"
), motif_score = c(6.728401, -0.979777, 6.091471), strand = c("+",
"+", "+"), read_count = c(0L, 0L, 0L)), .Names = c("chrn", "start",
"end", "motif_name_binned", "motif_score", "strand", "read_count"
), class = c("data.table", "data.frame"), row.names = c(NA, -3L
))

Which looks like this:

    chrn    start      end                                           motif_name_binned motif_score strand read_count
1: chr20 52447674 52447689 ZNF263/MA0528.1/Jaspar.instid_chr20:52447338-52447738.bin22    6.728401      +          0
2:  chr6 12962440 12962455    Klf12/MA0742.1/Jaspar.instid_chr6:12962360-12962760.bin6   -0.979777      +          0
3:  chr5 66453982 66453997   Hoxc9/MA0485.1/Jaspar.instid_chr5:66453806-66454206.bin12    6.091471      +          0

Body:
We create a unique splitting character with gsub and with tstrsplit split based on the character into 3 columns

my_data_table[, c('motif', 'inst', 'binno') := tstrsplit(
   gsub("^(.*?\\/.*?)\\.instid_(.*?)\\.bin(\\d+)", "\\1$\\2$\\3", motif_name_binned), '$',
       fixed = TRUE)][, setdiff(names(my_data_table), "motif_name_binned"), with = FALSE]
#    chrn    start      end motif_score strand read_count                  motif                    inst binno
#1: chr20 52447674 52447689    6.728401      +          0 ZNF263/MA0528.1/Jaspar chr20:52447338-52447738    22
#2:  chr6 12962440 12962455   -0.979777      +          0  Klf12/MA0742.1/Jaspar  chr6:12962360-12962760     6
#3:  chr5 66453982 66453997    6.091471      +          0  Hoxc9/MA0485.1/Jaspar  chr5:66453806-66454206    12


问:
how can I get just a single div to refresh on submit as apposed to the entire page?
I am working  with a dynamically  generated page written in PHP. The divon the page contain contents listed  FancyBox  links that open editing screens.
Once editing is complete and the user closes the FancyBox modal the changes
need to be reflected on the parent page.

Right, so I was able to find a solution that refreshes the entire page on submit
using

```<code>  parent.location.reload (true);
</code>```

to refresh the entire parent page. But, that causes a browser prompt
that is confusing to users and a bit of over kill as I really only
need the information edited to refresh.

how can I get just a single div to refresh on submit  as
apposed to the entire page??????

答:
You need to submit the form through AJAX. Since your using something that uses jQuery, you can use it to do it.

Here you can find a tutorial on how to do it

Body:
I am working  with a dynamically  generated page written in PHP. The divon the page contain contents listed  FancyBox  links that open editing screens.
Once editing is complete and the user closes the FancyBox modal the changes
need to be reflected on the parent page.

Right, so I was able to find a solution that refreshes the entire page on submit
using

  parent.location.reload (true);

to refresh the entire parent page. But, that causes a browser prompt
that is confusing to users and a bit of over kill as I really only
need the information edited to refresh.

how can I get just a single div to refresh on submit  as
apposed to the entire page??????


问:
Why does C# infer this type as dynamic?
I have the following code.

```<code>public static void GuessTheType()
{
    dynamic hasValue = true;
    dynamic value = "true";

    var whatami1 = hasValue ? (string)value : null;
    var whatami2 = hasValue ? bool.Parse(value) : true;
    var whatami3 = hasValue ? (bool)bool.Parse(value) : true;
}
</code>```

The type inferred by the compiler for whatami1 is string.

The type inferred by the compiler for whatami2 is dynamic.

The type inferred by the compiler for whatami3 is bool.

Why is the second type not bool?

答:
To expand on PetSerAl's comment, which explains why it's treated as dynamic, you can avoid having your call to bool.Parse treated as dynamic by casting the value to a string:

```<code>var whatami2 = hasValue ? bool.Parse((string)value) : true;
</code>```

Title: Why does C# infer this type as dynamic?

Body:
I have the following code.

public static void GuessTheType()
{
    dynamic hasValue = true;
    dynamic value = "true";

    var whatami1 = hasValue ? (string)value : null;
    var whatami2 = hasValue ? bool.Parse(value) : true;
    var whatami3 = hasValue ? (bool)bool.Parse(value) : true;
}

The type inferred by the compiler for whatami1 is string.

The type inferred by the compiler for whatami2 is dynamic.

The type inferred by the compiler for whatami3 is bool.

Why is the second type not bool?

Body:
To expand on PetSerAl's comment, which explains why it's treated as dynamic, you can avoid having your call to bool.Parse treated as dynamic by casting the value to a string:

var whatami2 = hasValue ? bool.Parse((string)value) : true;


问:
SQL Query to select from multiple nested subqueries
I am having a bit of trouble with this SQL query and I can't wrap my head around it. I have a site where users which have a moderator-like role can make changes to the user's account type below them, now I do have a working changelog, but I have problems displaying the correct information. I have these three tables:

Roles: Role_ID, Role_Type

Users: User_ID, Firstname, Lastname, Role_ID

Changelogs: Log_ID, Moderator_ID, User_ID, Prev_Role_ID, New_Role_ID, Logtime

To explain, the changelogs have a unique Log_ID, and then the Moderator_ID is the User_ID of the person making changes, User_ID is then the ID of user's account that hs been changed. And the Role_ID's are just what it was to what is has changed to.

So I want to display the Log ID, the first name and last name of the moderator, the first name and last name of the user, and the previous role as well as new role.

I am using nested selects, but I think my problem is with the joining of tables, because everything displays fine, except I have a LOT of records, and when I group by Log_ID at then end, it just ends up showing my records but with the incorrect changes to roles. It returns all the combinations, so I think I need a few JOINS but I am not sure what or where to put them.

```<code>SELECT changelogs.log_id, a.lastname AS mlastname, a.firstname AS mfirstname,
b.lastname AS ulastname, b.firstname AS ufirstname, c.role_type AS
pre_role, d.role_type AS new_role, changelogs.logtime

FROM (SELECT log_id, lastname, firstname FROM users, changelogs
      WHERE users.user_id = changelogs.mod_id) a,

     (SELECT log_id, lastname, firstname FROM users, changelogs
      WHERE users.user_id = changelogs.user_id) b,

     (SELECT log_id, role_type FROM roles, changelogs
      WHERE changelogs.prev_role_id = roles.role_id) c,

     (SELECT log_id, role_type FROM roles, changelogs
      WHERE roles.role_id = changelogs.role_id) d, changelogs;
</code>```

I basically just want to view my Changelogs table exactly as it is, just with the names in the place of their ID's and the roles in the place of their ID's.

RESULT: Log_ID, mLastname, mFirstname, uLastname, uFirstname, Pre_Role, New_Role, Time

Sorry for this silly question but it has been bugging me for quite a while.

答:
Try this solution.. It should work.</p>

```<code>SELECT a.log_id, c.lastname  AS mlastname, c.firstname AS mfirstname, b.lastname  AS ulastname
    , b.firstname AS ufirstname, e.role_type AS pre_role, d.role_type AS new_role, a.logtime
FROM Changelogs a
JOIN Users b ON a.user_id = b.user_id
JOIN Users c ON a.moderator_id = c.user_id
JOIN Role d ON a.New_Role_id = d.Role_ID
JOIN Role e ON a.prev_role_id = e.Role_ID
</code>```

Body:
I am having a bit of trouble with this SQL query and I can't wrap my head around it. I have a site where users which have a moderator-like role can make changes to the user's account type below them, now I do have a working changelog, but I have problems displaying the correct information. I have these three tables:

Roles: Role_ID, Role_Type

Users: User_ID, Firstname, Lastname, Role_ID

Changelogs: Log_ID, Moderator_ID, User_ID, Prev_Role_ID, New_Role_ID, Logtime

To explain, the changelogs have a unique Log_ID, and then the Moderator_ID is the User_ID of the person making changes, User_ID is then the ID of user's account that hs been changed. And the Role_ID's are just what it was to what is has changed to.

So I want to display the Log ID, the first name and last name of the moderator, the first name and last name of the user, and the previous role as well as new role.

I am using nested selects, but I think my problem is with the joining of tables, because everything displays fine, except I have a LOT of records, and when I group by Log_ID at then end, it just ends up showing my records but with the incorrect changes to roles. It returns all the combinations, so I think I need a few JOINS but I am not sure what or where to put them.

SELECT changelogs.log_id, a.lastname AS mlastname, a.firstname AS mfirstname,
b.lastname AS ulastname, b.firstname AS ufirstname, c.role_type AS
pre_role, d.role_type AS new_role, changelogs.logtime

FROM (SELECT log_id, lastname, firstname FROM users, changelogs
      WHERE users.user_id = changelogs.mod_id) a,

     (SELECT log_id, lastname, firstname FROM users, changelogs
      WHERE users.user_id = changelogs.user_id) b,

     (SELECT log_id, role_type FROM roles, changelogs
      WHERE changelogs.prev_role_id = roles.role_id) c,

     (SELECT log_id, role_type FROM roles, changelogs
      WHERE roles.role_id = changelogs.role_id) d, changelogs;

I basically just want to view my Changelogs table exactly as it is, just with the names in the place of their ID's and the roles in the place of their ID's.

RESULT: Log_ID, mLastname, mFirstname, uLastname, uFirstname, Pre_Role, New_Role, Time

Sorry for this silly question but it has been bugging me for quite a while.

Body:
Try this solution.. It should work.

SELECT a.log_id, c.lastname  AS mlastname, c.firstname AS mfirstname, b.lastname  AS ulastname
    , b.firstname AS ufirstname, e.role_type AS pre_role, d.role_type AS new_role, a.logtime
FROM Changelogs a
JOIN Users b ON a.user_id = b.user_id
JOIN Users c ON a.moderator_id = c.user_id
JOIN Role d ON a.New_Role_id = d.Role_ID
JOIN Role e ON a.prev_role_id = e.Role_ID


问:
Empty textfield produces multiple asterisks
I have this code that adds a red asterisk if a text field is left empty. I want it so that the asterisk goes away once the document detects input in said text field. I also want to prevent more asterisks getting added IF one is already there and text field is still empty. I have tried running IF ELSE statements to make it happen but get errors. Thank you for any help.

const button = document.getElementById('button')
const listdiv = document.querySelector('.listdiv')
var urlinput = document.getElementById('text').value

button.addEventListener('click', function() {
  // Get URL and add it into a link
  let createA = document.createElement('a')
  createA.href = urlinput
  createA.textContent = urlinput

  // Get description and add it to the link
  let descrInput = document.getElementById('description').value
  let strong = document.createElement('strong')
  strong.textContent = descrInput

  if (urlinput.trim() !== '') {
    listdiv.appendChild(strong)
    listdiv.appendChild(createA)
  } else {
    var ast = document.querySelector('.ast')
    var createAst = document.createTextNode('*')
    text.style.border = '1px solid #ff0000'
    ast.style.color = '#ff0000'
    ast.appendChild(createAst)
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="style.css" rel="stylesheet" type="text/css">
  <title>Meine Testseite</title>
</head>

<body>

  <div class="formdiv">
    <form>
      <input type="text" name="" placeholder="Enter URL" id="text" autofocus>
      <div class="ast"></div>
      <input type="text" name="" placeholder="Link description" id="description">
      <input type="button" value="Add" class="button" id="button">
    </form>
  </div>

  <div class="listdiv">

  </div>

  <script src="js.js"></script>
</body>

</html></code>```

答:
Just a personal preference, but I might turn around your if statements to get a better handle on the problem:

If the field is blank and if there are no asterisks already showing, then add an asterisk; (optional) else if the field is blank and there is an asterisk; else if the field is not blank.

You can get the value of the asterisk div using something like document.querySelector('.ast').innerHTML and then include it in your if statement:

```<code>if (urlinput.trim() === '' && document.querySelector('.ast').innerHTML === "") {
  add an asterisk
} else if (urlinput.trim() === '' && document.querySelector('.ast').innerHTML === "*" {
  don't add an asterisk
} else {
  appendChild as you've already got them
}
</code>```

The trick with this solution is that it'll really only work if there's 1 asterisk field on the page.  Based on your question, that assumption holds up.  If that's a bad assumption, let me know.

Body:
I have this code that adds a red asterisk if a text field is left empty. I want it so that the asterisk goes away once the document detects input in said text field. I also want to prevent more asterisks getting added IF one is already there and text field is still empty. I have tried running IF ELSE statements to make it happen but get errors. Thank you for any help.

const button = document.getElementById('button')
const listdiv = document.querySelector('.listdiv')
var urlinput = document.getElementById('text').value

button.addEventListener('click', function() {
  // Get URL and add it into a link
  let createA = document.createElement('a')
  createA.href = urlinput
  createA.textContent = urlinput

  // Get description and add it to the link
  let descrInput = document.getElementById('description').value
  let strong = document.createElement('strong')
  strong.textContent = descrInput

  if (urlinput.trim() !== '') {
    listdiv.appendChild(strong)
    listdiv.appendChild(createA)
  } else {
    var ast = document.querySelector('.ast')
    var createAst = document.createTextNode('*')
    text.style.border = '1px solid #ff0000'
    ast.style.color = '#ff0000'
    ast.appendChild(createAst)
  }
})

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="style.css" rel="stylesheet" type="text/css">
  <title>Meine Testseite</title>

    <form>
      <input type="text" name="" placeholder="Enter URL" id="text" autofocus>

      <input type="text" name="" placeholder="Link description" id="description">
      <input type="button" value="Add" class="button" id="button">
    </form>

Body:
Just a personal preference, but I might turn around your if statements to get a better handle on the problem:

If the field is blank and if there are no asterisks already showing, then add an asterisk; (optional) else if the field is blank and there is an asterisk; else if the field is not blank.

You can get the value of the asterisk div using something like document.querySelector('.ast').innerHTML and then include it in your if statement:

if (urlinput.trim() === '' && document.querySelector('.ast').innerHTML === "") {
  add an asterisk
} else if (urlinput.trim() === '' && document.querySelector('.ast').innerHTML === "*" {
  don't add an asterisk
} else {
  appendChild as you've already got them
}

The trick with this solution is that it'll really only work if there's 1 asterisk field on the page.  Based on your question, that assumption holds up.  If that's a bad assumption, let me know.


问:
Android Studio not committing to GitHub
I am trying to use git in Android Studio. If I choose commit changes, it says that it has successfully committed the changed files but those changes do not appear on the GitHub. Instead, if I delete the repository from GitHub and choose Share Project on GitHub, it successfully creates a new repository and uploads the files into it. This means that the connection is fine. Also, I have checked the gitignore file, the java files are not in that list. What could be the problem? </p>

答: For my case it's a different - I uncheck Perform code analysis in commit changes dialog and it worked. Hope it will help some one.

Title: Android Studio not committing to GitHub


问:
Putting multiple elements in array through loop
I have multiple inputs in a file like this:

<form action="card_generate.php">
<input type="text" name="tZero">
        <input type="text" name="tOne">
        <input type="text" name="tTwo">
        <input type="text" name="tThree">
</form>```
</div>
</div>

in the file card_generate.php this have to go in an array i have wrote:</p>

<pre class="lang-php prettyprint-override"><code>$tabs = array($_POST["tZero"], $_POST["tOne"], $_POST["tTwo"], $_POST["tThree"]);
</code>```

Is there a way I can put these values in an array through a loop or something instead of putting each value in an array one by one, there can be more values than four values.

答:
You can also use a foreach loop as shown in the example:

HTML

```<code><form method="POST">
<input type="text" name="tZero">
        <input type="text" name="tOne">
        <input type="text" name="tTwo">
        <input type="text" name="tThree">
<input type="submit" name="">
</form>
</code>```

PHP

```<code><?php

if ( isset($_POST) ) {
    foreach ($_POST as $key => $value) {
        echo "Name: $key, value: $value";
        echo "<br>";
    }
}

?>
</code>```

RESULT

```<code>Name: tZero, value: first
Name: tOne, value: hi
Name: tTwo, value: firthfds
Name: tThree, value: fourth value
</code>```

P.S. Don't forget method="POST" in your <form>.

Body:
I have multiple inputs in a file like this:

<form action="card_generate.php">
<input type="text" name="tZero">
        <input type="text" name="tOne">
        <input type="text" name="tTwo">
        <input type="text" name="tThree">
</form>

in the file card_generate.php this have to go in an array i have wrote:

$tabs = array($_POST["tZero"], $_POST["tOne"], $_POST["tTwo"], $_POST["tThree"]);

Is there a way I can put these values in an array through a loop or something instead of putting each value in an array one by one, there can be more values than four values.

Body:
You can also use a foreach loop as shown in the example:

HTML

<form method="POST">
<input type="text" name="tZero">
        <input type="text" name="tOne">
        <input type="text" name="tTwo">
        <input type="text" name="tThree">
<input type="submit" name="">
</form>

PHP

<?php

if ( isset($_POST) ) {
    foreach ($_POST as $key => $value) {
        echo "Name: $key, value: $value";
        echo "<br>";
    }
}

?>

RESULT

Name: tZero, value: first
Name: tOne, value: hi
Name: tTwo, value: firthfds
Name: tThree, value: fourth value

P.S. Don't forget method="POST" in your <form>.


问:
GRID items right aligned
I'm playing with "grid layout" and I have a "section" with 100% width. This is display: grid.

Inside it there are 4 other divs that I would like to appear on the right side instead of the left side.

Here is my code:

.fullWidth {
  display: grid;
  grid-template: "it01 it02 it03 it04 it05";
  grid-template-rows: 40px;
  grid-template-columns: 40px 40px 40px 200px 40px;
  background: orange;
}

.item01 {
  grid-area: it01;
  background: lime;
}

.item02 {
  grid-area: it02;
  background: blue;
}

.item03 {
  grid-area: it03;
  background: red;
}

.item04 {
  grid-area: it04;
  background: yellow;
}

.item05 {
  grid-area: it05;
  background: tomato;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="fullWidth">
  <div class="item01"> </div>
  <div class="item02"> </div>
  <div class="item03"> </div>
  <div class="item04"> </div>
  <div class="item05"> </div>
</section></code>```

Here's the fiddle:
https://jsfiddle.net/2mpsuc7c/

答:
You can make use of the direction property with direction: rtl:

.fullWidth {
  display: grid;
  grid-template: "it01 it02 it03 it04 it05";
  grid-template-rows: 40px;
  grid-template-columns: 40px 40px 40px 200px 40px;
  background: orange;
  direction: rtl;
}

.item01 {
  grid-area: it01;
  background: lime;
}

.item02 {
  grid-area: it02;
  background: blue;
}

.item03 {
  grid-area: it03;
  background: red;
}

.item04 {
  grid-area: it04;
  background: yellow;
}

.item05 {
  grid-area: it05;
  background: tomato;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="fullWidth">
  <div class="item01"></div>
  <div class="item02"></div>
  <div class="item03"></div>
  <div class="item04"></div>
  <div class="item05"></div>
</section></code>```

Hope this helps! :)

Title: GRID items right aligned

Body:
I'm playing with "grid layout" and I have a "section" with 100% width. This is display: grid.

Inside it there are 4 other divs that I would like to appear on the right side instead of the left side.

Here is my code:

.fullWidth {
  display: grid;
  grid-template: "it01 it02 it03 it04 it05";
  grid-template-rows: 40px;
  grid-template-columns: 40px 40px 40px 200px 40px;
  background: orange;
}

.item01 {
  grid-area: it01;
  background: lime;
}

.item02 {
  grid-area: it02;
  background: blue;
}

.item03 {
  grid-area: it03;
  background: red;
}

.item04 {
  grid-area: it04;
  background: yellow;
}

.item05 {
  grid-area: it05;
  background: tomato;
}

Here's the fiddle:
https://jsfiddle.net/2mpsuc7c/

Body:
You can make use of the direction property with direction: rtl:

.fullWidth {
  display: grid;
  grid-template: "it01 it02 it03 it04 it05";
  grid-template-rows: 40px;
  grid-template-columns: 40px 40px 40px 200px 40px;
  background: orange;
  direction: rtl;
}

.item01 {
  grid-area: it01;
  background: lime;
}

.item02 {
  grid-area: it02;
  background: blue;
}

.item03 {
  grid-area: it03;
  background: red;
}

.item04 {
  grid-area: it04;
  background: yellow;
}

.item05 {
  grid-area: it05;
  background: tomato;
}

<section class="fullWidth">
  <div class="item01"></div>
  <div class="item02"></div>
  <div class="item03"></div>
  <div class="item04"></div>
  <div class="item05"></div>
</section>

Hope this helps! :)


问:
Loop through JS object to return matching result of value
I have an object, full of salmon. I want to loop through and check whether salmon is fresh or frozen. If frozen, put in no pile, if fresh, put in yes pile. If ounces is less than 2 and more than 6, no pile, and if it matches 2-6, yes pile.

Then, with the yes pile, I want to loop through those keys and values to find the cheapest one, and print that out.

Here is what I have so far, but I seem to be stuck on looping through the big object in order to run the checks.

How do I do this?

```<code>function findSalmon(salmonInStore){
  var noPile,
      yesPile;
      var salmon = Object.keys(salmonInStore));
  for(var key in salmonInStore){

    if(salmonInStore.key.freshness !== 'fresh'){
      noPile.push(salmonInStore.key);
    } else {
      yesPile.push(salmonInStore.key);
    }
    if(salmonInStore.key.ounces < 2 && salmonInStore.key.ounces > 6){
      noPile.push(key);
    }else {
      yesPile.push(salmonInStore.key);
    }
  }
  return yesPile;
}

var salmonInStore = {
  salmon1 : {
    ounces: 1,
    freshness: 'frozen',
    price: 16
  },

 salmon2 : {
    ounces: 6,
    freshness: 'fresh',
    price: 10
  },

  salmon3 : {
    ounces: 2,
    freshness: 'frozen',
    price: 20
  },

  salmon4 : {
    ounces: 5,
    freshness: 'fresh',
    price: 1
  },

  salmon5 : {
    ounces: 3,
    freshness: 'frozen',
    price: 12
  }
}

findSalmon(salmonInStore);
</code>```

答:
I seem to be stuck on looping through the big object in order to run the checks.

Objects are also known as key/value pairs.

You can use Object.keys to get the keys of an object. From then on you need nested loops and dynamic value access using bracket notation to get the value of a k/v pair based on the key you got when you used Object.keys.

Here's an example:

var salmonInStore = {
  salmon1 : {
    ounces: 1,
    freshness: 'frozen',
    price: 16
  },

 salmon2 : {
    ounces: 6,
    freshness: 'fresh',
    price: 10
  }
}

Object.keys(salmonInStore).forEach(storeKey => {
  var salmon = salmonInStore[storeKey]
  // put per salmon logic here...

  Object.keys(salmon).forEach(salmonKey => {
    var value = salmon[salmonKey] // value for each key
    console.log(value)
    // put per salmon value logic here...
  })
})```

However if you plan on having arbitrary nesting levels - not just 1 level, you would need a recursive function to walk your salmons.

The above can be made more 'functional' by using reduce instead of forEach but that's another story.

The gist of the above is that you need Object.keys and someObj[key]. I've substituted your for.. loops with forEach just for brevity.

Body:
I have an object, full of salmon. I want to loop through and check whether salmon is fresh or frozen. If frozen, put in no pile, if fresh, put in yes pile. If ounces is less than 2 and more than 6, no pile, and if it matches 2-6, yes pile.

Then, with the yes pile, I want to loop through those keys and values to find the cheapest one, and print that out.

Here is what I have so far, but I seem to be stuck on looping through the big object in order to run the checks.

How do I do this?

function findSalmon(salmonInStore){
  var noPile,
      yesPile;
      var salmon = Object.keys(salmonInStore));
  for(var key in salmonInStore){

    if(salmonInStore.key.freshness !== 'fresh'){
      noPile.push(salmonInStore.key);
    } else {
      yesPile.push(salmonInStore.key);
    }
    if(salmonInStore.key.ounces < 2 && salmonInStore.key.ounces > 6){
      noPile.push(key);
    }else {
      yesPile.push(salmonInStore.key);
    }
  }
  return yesPile;
}

var salmonInStore = {
  salmon1 : {
    ounces: 1,
    freshness: 'frozen',
    price: 16
  },

 salmon2 : {
    ounces: 6,
    freshness: 'fresh',
    price: 10
  },

  salmon3 : {
    ounces: 2,
    freshness: 'frozen',
    price: 20
  },

  salmon4 : {
    ounces: 5,
    freshness: 'fresh',
    price: 1
  },

  salmon5 : {
    ounces: 3,
    freshness: 'frozen',
    price: 12
  }
}

findSalmon(salmonInStore);

Body:
I seem to be stuck on looping through the big object in order to run the checks.

Objects are also known as key/value pairs.

You can use Object.keys to get the keys of an object. From then on you need nested loops and dynamic value access using bracket notation to get the value of a k/v pair based on the key you got when you used Object.keys.

Here's an example:

var salmonInStore = {
  salmon1 : {
    ounces: 1,
    freshness: 'frozen',
    price: 16
  },

 salmon2 : {
    ounces: 6,
    freshness: 'fresh',
    price: 10
  }
}

Object.keys(salmonInStore).forEach(storeKey => {
  var salmon = salmonInStore[storeKey]
  // put per salmon logic here...

  Object.keys(salmon).forEach(salmonKey => {
    var value = salmon[salmonKey] // value for each key
    console.log(value)
    // put per salmon value logic here...
  })
})

However if you plan on having arbitrary nesting levels - not just 1 level, you would need a recursive function to walk your salmons.

The above can be made more 'functional' by using reduce instead of forEach but that's another story.

The gist of the above is that you need Object.keys and someObj[key]. I've substituted your for.. loops with forEach just for brevity.


问:
Combine UIPageViewController swipes with iOS 7 UINavigationController back-swipe gesture
I have a navigation controller that pushes a view-controller (PARENT) that contains an UIPageViewController (PAGES). Now I used pan/swipe gestures to switch between the children of the page-view-controller. However, I can no longer pop the PARENT-view controller using the swipe gesture from the left border of the screen, because it is interpreted as a gesture in PAGES.

Is it possible to accomplish that swipe-to-pop when the left-most view-controller is shown?

Two ideas:

Return nil in pageViewController:viewControllerBeforeViewController -> doesn't work.

Restrict the touch area, as described here.

Or is there a more straightforward way?

答:
First, find UIPageViewController's scrollView

```<code>extension UIPageViewController {
    var bk_scrollView: UIScrollView? {
        if let v = view as? UIScrollView {
            return v
        }
        // view.subviews 只有一个元素，其类型是 _UIQueuingScrollView，是 UIScrollView 的子类
        // view.subviews have only one item of which the type is _UIQueuingScrollView, which is kind of UIScrollView's subclass.
        for v in view.subviews where v is UIScrollView {
            return v as? UIScrollView
        }
        return nil
    }
}
</code>```

Second, set gestureRecognizer's dependence.

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    if let ges = navigationController?.interactivePopGestureRecognizer {
        pageViewController.bk_scrollView?.panGestureRecognizer.require(toFail: ges)
    }
}
</code>```

Body:
First, find UIPageViewController's scrollView

extension UIPageViewController {
    var bk_scrollView: UIScrollView? {
        if let v = view as? UIScrollView {
            return v
        }
        // view.subviews 只有一个元素，其类型是 _UIQueuingScrollView，是 UIScrollView 的子类
        // view.subviews have only one item of which the type is _UIQueuingScrollView, which is kind of UIScrollView's subclass.
        for v in view.subviews where v is UIScrollView {
            return v as? UIScrollView
        }
        return nil
    }
}

Second, set gestureRecognizer's dependence.

override func viewDidLoad() {
    super.viewDidLoad()
    if let ges = navigationController?.interactivePopGestureRecognizer {
        pageViewController.bk_scrollView?.panGestureRecognizer.require(toFail: ges)
    }
}


问:
Why "C:\Program Files" used as default. Is there any violations or degradation in performance if we change it?
Why does Microsoft recommend "C:\Program Files" for default installation destination? Are there any specific reason for that? And if I change the location is that going to effect the performance of the system and the application?</p>

答: That's the location that most users, and admins, expect to find their applications installed in.  It's really more of a convention than anything else.  I would suggest that it's a reasonable default, but you could allow the user the ability to change the location during the installation if they desire.  In any event you should write your application to work without a dependence on a fixed installation directory if at all possible (and generally it is).  You shouldn't see any performance differences from another install location unless it happens to be on a slower or more heavily accessed drive.</p>

OwnerDisplayName: Maharajan

LastEditorDisplayName: bdukes

OwnerDisplayName: tvanfosson


问:
Detect space/singlequote/double quote
I am trying to detect either a space, single quote or double quote

Note:  this answer does not work for single quote (unless it's the very first character, I need to detect either in front of, inside of or after a string):  HTML5 input pattern search for quote

I have tried pattern="[^'\x20\x22]+"  and also pattern="[^\x20\x22\x27]+"

Could someone give me a regex that detects all of them please.

答:
To match the strings that contain a space or ' or ", use this regex:

^(?=.*['\x20\x22]).+$

Click for Demo

Explanation:

^ - asserts the start of the string

(?=.*['\x20\x22]) - positive lookahead to detect the presence of either a space or a ' or a "

.+ - matches 1+ occurrences of any character but a newline character

$ - asserts the end of the string

Title: Detect space/singlequote/double quote


问:
PHP MySQL pagination data using mysqli_fetch_all
I'm using PHP pagination for my table on ORACLE database

```<code>$strSQL = oci_parse($c1, "
    SELECT
    L.LINEID,
    L.LINENAME,
    L.ACTIVE,
    TO_CHAR(L.DATEADDED, 'DD-MON-YYYY HH24:MI:SS') AS DATEADDEDS,
    L.ADDEDBY,
    L.SECTIONID_FK,
    S.SECTIONID,
    S.SECTIONNAME
    FROM
    WA_GA_TBL_LINES L,
    WA_GA_TBL_SECTION S
    WHERE
    L.SECTIONID_FK = S.SECTIONID
    ORDER BY L.DATEADDED DESC
");
oci_execute ($strSQL,OCI_DEFAULT);
$Num_Rows = oci_fetch_all($strSQL, $dData);
</code>```

On ORACLE database, it worked OK.

And now I've moved to MySQL database

```<code>$strSQL = mysqli_query($c1, "
    SELECT * FROM tb_slides ORDER BY date_added DESC
");
$Num_Rows = mysqli_num_rows($strSQL);
$dData = mysqli_fetch_array($strSQL);
var_dump($dData);
</code>```

But got error:

```<code>Notice: Undefined variable: dData in
</code>```

and

```<code>Warning: mysqli_fetch_array(): The result type should be either MYSQLI_NUM, MYSQLI_ASSOC or MYSQLI_BOTH in
</code>```

Is there any way to fix it?

UPDATE with table data show, as you can see I'm using loop on below code to show the data.

```<code>if($Num_Rows > 0)
{
    if($Page > 0)
    {
        if(is_numeric($Page))
        {
            for($i=$Page_Start;$i<$Page_End;$i++)
            {
            ?>
               <td class="spanSlide<?php echo $dData['slide_id'][$i]; ?>"><?php echo htmlspecialchars($dData['slide_content'][$i]); ?></td><input type="hidden" class="slideValue<?php echo $dData['slide_id'][$i]; ?>" id="slideValue" value="<?php echo htmlspecialchars($dData['slide_content'][$i]); ?>"/>
            <?php
            }
        }
    }
}
</code>```

var_dump

```<code>array(12) { [0]=> string(1) "4" ["slide_id"]=> string(1) "4" [1]=> string(346) "Melaksanakan shalat tahiyatul masjid sebelum duduk, sabda Rasulullah saw: Tatkala di antara kamu ke masjid maka bersalatlah dua rakaat sebelum duduk. Tidak boleh mengeraskan suara yang dapat mengganggu orang yang sedang melakukan shalat, meskipun dalam bentuk membaca al-Quran. Tidak boleh berjalan di depan orang yang sedang melaksanakan shalat." ["slide_content"]=> string(346) "Melaksanakan shalat tahiyatul masjid sebelum duduk, sabda Rasulullah saw: Tatkala di antara kamu ke masjid maka bersalatlah dua rakaat sebelum duduk. Tidak boleh mengeraskan suara yang dapat mengganggu orang yang sedang melakukan shalat, meskipun dalam bentuk membaca al-Quran. Tidak boleh berjalan di depan orang yang sedang melaksanakan shalat." [2]=> string(6) "hadits" ["slide_category"]=> string(6) "hadits" [3]=> string(1) "Y" ["active"]=> string(1) "Y" [4]=> string(19) "2017-11-09 00:00:00" ["date_added"]=> string(19) "2017-11-09 00:00:00" [5]=> string(1) "1" ["user_idfk"]=> string(1) "1" }
</code>```

答:
It's because you wrote the syntax wrong.

```<code> $Num_Rows = mysqli_fetch_all($strSQL, $dData);
</code>```

should be

```<code> $Num_Rows = mysqli_num_rows($strSQL);
 $dData = mysqli_fetch_all($strSQL);
</code>```

Mysql needs two steps for that

Body:
I'm using PHP pagination for my table on ORACLE database

$strSQL = oci_parse($c1, "
    SELECT
    L.LINEID,
    L.LINENAME,
    L.ACTIVE,
    TO_CHAR(L.DATEADDED, 'DD-MON-YYYY HH24:MI:SS') AS DATEADDEDS,
    L.ADDEDBY,
    L.SECTIONID_FK,
    S.SECTIONID,
    S.SECTIONNAME
    FROM
    WA_GA_TBL_LINES L,
    WA_GA_TBL_SECTION S
    WHERE
    L.SECTIONID_FK = S.SECTIONID
    ORDER BY L.DATEADDED DESC
");
oci_execute ($strSQL,OCI_DEFAULT);
$Num_Rows = oci_fetch_all($strSQL, $dData);

On ORACLE database, it worked OK.

And now I've moved to MySQL database

$strSQL = mysqli_query($c1, "
    SELECT * FROM tb_slides ORDER BY date_added DESC
");
$Num_Rows = mysqli_num_rows($strSQL);
$dData = mysqli_fetch_array($strSQL);
var_dump($dData);

But got error:

Notice: Undefined variable: dData in

and

Warning: mysqli_fetch_array(): The result type should be either MYSQLI_NUM, MYSQLI_ASSOC or MYSQLI_BOTH in

Is there any way to fix it?

UPDATE with table data show, as you can see I'm using loop on below code to show the data.

if($Num_Rows > 0)
{
    if($Page > 0)
    {
        if(is_numeric($Page))
        {
            for($i=$Page_Start;$i<$Page_End;$i++)
            {
            ?>
               <td class="spanSlide<?php echo $dData['slide_id'][$i]; ?>"><?php echo htmlspecialchars($dData['slide_content'][$i]); ?>	<input type="hidden" class="slideValue<?php echo $dData['slide_id'][$i]; ?>" id="slideValue" value="<?php echo htmlspecialchars($dData['slide_content'][$i]); ?>"/>
            <?php
            }
        }
    }
}

var_dump

array(12) { [0]=> string(1) "4" ["slide_id"]=> string(1) "4" [1]=> string(346) "Melaksanakan shalat tahiyatul masjid sebelum duduk, sabda Rasulullah saw: Tatkala di antara kamu ke masjid maka bersalatlah dua rakaat sebelum duduk. Tidak boleh mengeraskan suara yang dapat mengganggu orang yang sedang melakukan shalat, meskipun dalam bentuk membaca al-Quran. Tidak boleh berjalan di depan orang yang sedang melaksanakan shalat." ["slide_content"]=> string(346) "Melaksanakan shalat tahiyatul masjid sebelum duduk, sabda Rasulullah saw: Tatkala di antara kamu ke masjid maka bersalatlah dua rakaat sebelum duduk. Tidak boleh mengeraskan suara yang dapat mengganggu orang yang sedang melakukan shalat, meskipun dalam bentuk membaca al-Quran. Tidak boleh berjalan di depan orang yang sedang melaksanakan shalat." [2]=> string(6) "hadits" ["slide_category"]=> string(6) "hadits" [3]=> string(1) "Y" ["active"]=> string(1) "Y" [4]=> string(19) "2017-11-09 00:00:00" ["date_added"]=> string(19) "2017-11-09 00:00:00" [5]=> string(1) "1" ["user_idfk"]=> string(1) "1" }

Body:
It's because you wrote the syntax wrong.

 $Num_Rows = mysqli_fetch_all($strSQL, $dData);

should be

 $Num_Rows = mysqli_num_rows($strSQL);
 $dData = mysqli_fetch_all($strSQL);

Mysql needs two steps for that


问:
Python split on brackets with regular expressions
If I have a string "4[ab]" and I want to split this string such that I get an array ["4", "ab"], how would I use a regular expression in python for this?

I've used the following regular expressions with no luck:

```<code>"\[\["
"\]\["
"[\[\]]"
"[\]\[]"
</code>```

From what I understand with python syntax you have to escape characters like square brackets because it will compute the values inside the brackets as the regular expression.

What else is required?

Edit, sorry for the delay:

Here's the code though I doubt it's anything special:

```<code>import re
re.split("[\[\]]","4[ab]")
</code>```

This returns the correct output I'm looking for but does not work for

```<code>"4[ab]".split("[\[\]]")
</code>```

答:
This gives you the list form:

```<code>import re
m = "4[ab]"
n = re.findall('(\w+)\[', m)
n.extend(re.findall('(\w+)\]', m))
print(n)
</code>```

Result:

```<code>['4','ab']
</code>```

Body:
If I have a string "4[ab]" and I want to split this string such that I get an array ["4", "ab"], how would I use a regular expression in python for this?

I've used the following regular expressions with no luck:

"\[\["
"\]\["
"[\[\]]"
"[\]\[]"

From what I understand with python syntax you have to escape characters like square brackets because it will compute the values inside the brackets as the regular expression.

What else is required?

Edit, sorry for the delay:

Here's the code though I doubt it's anything special:

import re
re.split("[\[\]]","4[ab]")

This returns the correct output I'm looking for but does not work for

"4[ab]".split("[\[\]]")

Body:
This gives you the list form:

import re
m = "4[ab]"
n = re.findall('(\w+)\[', m)
n.extend(re.findall('(\w+)\]', m))
print(n)

Result:

['4','ab']


问:
How to make a wavy effect in Unity3D
In the game Super Luigi Galaxy, when the player falls into cold water, the screen waves. Is there a possible way to do this effect in Unity?

The effect looks like this: https://youtu.be/uj3TWvUlLqs?t=4m19s

https://i.imgur.com/1oR9ZFk.png

I do not know the name of this effect, sorry for my lack of details.

答:
Sorry for being stupid.

1) Add a new shader, material, and C# script

2) The scripting.

Shader (add to bottom, and remove the color inversion):

```<code>        uniform float _waveLength;
        uniform float _waveNumber;

        fixed4 frag (v2f IN) : SV_Target
        {
            fixed4 col = tex2D(_MainTex, IN.uv + float2(sin(IN.vertex.y / _waveLength + _Time[1]*50) / _waveNumber, 0));

            return col;
        }
</code>```

C#:

```<code>using UnityEngine;

public class testscript : MonoBehaviour {

    public Material mat;

    public float waveNumber;
    public float waveLength;

    void Update()
    {
        Shader.SetGlobalFloat("_waveLength", waveNumber); // I know I switched the variables on accident. It still works though.
        Shader.SetGlobalFloat("_waveNumber", waveLength);
    }

    void OnRenderImage( RenderTexture src, RenderTexture dest)
    {
        Graphics.Blit(src, dest, mat);
    }
}
</code>```

3) Attach the C# script to the Camera, attach the shader to the material, and attach the material to the C# script. Add a cube to the scene to view the effect. Go to playing mode on Unity, and adjust the settings on the script.

4) What to the variables do?

a) Wave Number:
The amount of waves,
1 = a lot of waves
30 = very few waves

b) Wave Length:
How far to offset the x of the waves,
1 = VERY wide waves
1000 = VERY short waves

I recommend the wave number at 1, and the wave length at 100.

Title: How to make a wavy effect in Unity3D

Body:
Sorry for being stupid.

1) Add a new shader, material, and C# script

2) The scripting.

Shader (add to bottom, and remove the color inversion):

        uniform float _waveLength;
        uniform float _waveNumber;

        fixed4 frag (v2f IN) : SV_Target
        {
            fixed4 col = tex2D(_MainTex, IN.uv + float2(sin(IN.vertex.y / _waveLength + _Time[1]*50) / _waveNumber, 0));

            return col;
        }

C#:

using UnityEngine;

public class testscript : MonoBehaviour {

    public Material mat;

    public float waveNumber;
    public float waveLength;

    void Update()
    {
        Shader.SetGlobalFloat("_waveLength", waveNumber); // I know I switched the variables on accident. It still works though.
        Shader.SetGlobalFloat("_waveNumber", waveLength);
    }

    void OnRenderImage( RenderTexture src, RenderTexture dest)
    {
        Graphics.Blit(src, dest, mat);
    }
}

3) Attach the C# script to the Camera, attach the shader to the material, and attach the material to the C# script. Add a cube to the scene to view the effect. Go to playing mode on Unity, and adjust the settings on the script.

4) What to the variables do?

a) Wave Number:
The amount of waves,
1 = a lot of waves
30 = very few waves

b) Wave Length:
How far to offset the x of the waves,
1 = VERY wide waves
1000 = VERY short waves

I recommend the wave number at 1, and the wave length at 100.


问:
TFS/Eclipse/Selenium: When I import project from TFS to Eclipse it will not be UFT8 encoding which leads to infinite errors
I have a project that is exported to TFS using Eclipse TFS plug-in when I re import the the project from TFS to eclipse into another machine it will not take the UFT8 encoding.

Note: My eclipse is configured to have UFT8 encoding from the text editor

答:
You can follow below steps to set the default file encoding in Eclipse:

Window > Preferences > General > Content Types, set UTF-8 as the
default encoding for all content types.

Window > Preferences > General > Workspace, set "Text file encoding"
to "Other : UTF-8".

You can also set the default encoding in eclipse.ini: Open
eclipse.ini in your eclipse home directory --> put the line
-Dfile.encoding=UTF-8 at the end of the file --> Save

Then import the project again.

For the projects which already imported, you can right click the Project --> Properties and select Resource on the left side menu. You can now change the Text-file encoding to whatever you wish.

This article for your reference : Unicode/UTF-8 in your Eclipse Java projects


问:
Reach only a specific html tag as an object value
I'm working on Angular js (1.6) and for the first time I have to deal with an API which contain several objects like this:

```<code>{
  "description": " <p><a href=\"url">link</a>text</p><p><a href=\"other
  url"><img src=\"another url" width=\"240\" height=\"160\" alt=\"text\" />
  </a></p> <p>text</p>"
}
</code>```

I found a way how to display the entire value with "ng-bind-html" but for some place in the webapp I only need the a tag or the img tag or the p tag.

My question is: Is it possible to display dynamically only a specific html tag of an object value like above?

Thank you for your time and your answers.

答:
Well, it's a string. So, as any string, you can do this.</p>

```<code>var str = "<p><a href=\'url'>link</a>text</p><p><a href=\'otherurl'><img src=\'another url' width=\'240\' height=\'160\' alt=\'text\' /></a></p> <p>text</p>";

var start = str.indexOf("<img");
var end = str.indexOf("/>", (start));
var embed = str.substring(start, end) + "/>";
</code>```

Body:
I'm working on Angular js (1.6) and for the first time I have to deal with an API which contain several objects like this:

{
  "description": "
linktext

text
"
}

I found a way how to display the entire value with "ng-bind-html" but for some place in the webapp I only need the a tag or the img tag or the p tag.

My question is: Is it possible to display dynamically only a specific html tag of an object value like above?

Thank you for your time and your answers.

Body:
Well, it's a string. So, as any string, you can do this.

var str = "<p><a href=\'url'>link</a>text</p><p><a href=\'otherurl'><img src=\'another url' width=\'240\' height=\'160\' alt=\'text\' /></a></p> <p>text</p>";

var start = str.indexOf("<img");
var end = str.indexOf("/>", (start));
var embed = str.substring(start, end) + "/>";


答:
```<code>function findSalmon(salmonInStore){
var yesPile = [];
var noPile = [];
Object.keys(salmonInStore).forEach( (key)=> {
  var salmon = salmonInStore[key]

  if (salmon.freshness !== 'fresh' || salmon.ounces < 2 && salmon.ounces > 6){
    noPile.push(key);
  } else {
    yesPile.push(key);
  }
})
return yesPile;
}
</code>```

Title: Loop through JS object to return matching result of value


问:
How to documenting an argument object's function definition
How can I document a class's argument, when that argument is a property which contains a property which is a function (whoah).

Example:

```<code>class MyClass {
    /**
     * @param {Object} options - configuration for the class
     * @param {Function} options.onSuccess - a callback function which has two arguments A and B
     * @memberof MyClass
     */
    constructor(options) {...}
}
</code>```

How can I define that someone should use this class like this, where onSuccess passes two arguments, A and B (where A might be an object with other properties, etc.)

```<code>var instance = new MyClass({
    onSuccess: (A, B) => {...}
});
</code>```

I'm using Visual Studio Code and it's showing no definition found. Is this possible or is it too many levels deep?

答:
I'm not sure what the types for a and b are, or whether the function returns void. But here are some options:

```<code>interface MyClassArgs {
    onSuccess: (a, b) => void;
}

class MyClass {
    constructor(options: MyClassArgs) { }
}
</code>```

Or

```<code>class MyClass {
    constructor(options: { onSuccess: (a, b) => void }) { }
}
</code>```

Body:
How can I document a class's argument, when that argument is a property which contains a property which is a function (whoah).

Example:

class MyClass {
    /**
     * @param {Object} options - configuration for the class
     * @param {Function} options.onSuccess - a callback function which has two arguments A and B
     * @memberof MyClass
     */
    constructor(options) {...}
}

How can I define that someone should use this class like this, where onSuccess passes two arguments, A and B (where A might be an object with other properties, etc.)

var instance = new MyClass({
    onSuccess: (A, B) => {...}
});

I'm using Visual Studio Code and it's showing no definition found. Is this possible or is it too many levels deep?

Body:
I'm not sure what the types for a and b are, or whether the function returns void. But here are some options:

interface MyClassArgs {
    onSuccess: (a, b) => void;
}

class MyClass {
    constructor(options: MyClassArgs) { }
}

Or

class MyClass {
    constructor(options: { onSuccess: (a, b) => void }) { }
}


答:
Since you are familiar with pivot tables in Excel, I'll give you the Pandas pivot_table method also:

```<code>df.pivot_table('id','value','movie',aggfunc='count').fillna(0).astype(int)
</code>```

Output:

```<code>movie     a        b        c
value
 0             4        2        0
 10            1        1        0
 20            2        0        0
 30            0        3        0
 40            0        0        2
</code>```

Title: python pivot table of counts

Body:
I have a dataframe df as follows:

| id | movie | value |
|----|-------|-------|
| 1  | a     | 0     |
| 2  | a     | 0     |
| 3  | a     | 20    |
| 4  | a     | 0     |
| 5  | a     | 10    |
| 6  | a     | 0     |
| 7  | a     | 20    |
| 8  | b     | 0     |
| 9  | b     | 0     |
| 10 | b     | 30    |
| 11 | b     | 30    |
| 12 | b     | 30    |
| 13 | b     | 10    |
| 14 | c     | 40    |
| 15 | c     | 40    |

I want to create a 2X2 pivot table of counts as follows:

| Value | count(a) | count(b) | count ( C ) |
|-------|----------|----------|-------------|
| 0     | 4        | 2        | 0           |
| 10    | 1        | 1        | 0           |
| 20    | 2        | 0        | 0           |
| 30    | 0        | 3        | 0           |
| 40    | 0        | 0        | 2           |

I can do this very easily in Excel using Row and Column Labels. How can I do this using Python?

Body:
Since you are familiar with pivot tables in Excel, I'll give you the Pandas pivot_table method also:

df.pivot_table('id','value','movie',aggfunc='count').fillna(0).astype(int)

Output:

movie     a        b        c
value
 0             4        2        0
 10            1        1        0
 20            2        0        0
 30            0        3        0
 40            0        0        2


答:
Casting is our assertion (to the compiler) that an object really is something else - for example:

```<code>var whatami1 = hasValue ? (string)value : null;
var whatami3 = hasValue ? (bool)bool.Parse(value) : true;
</code>```

Finally, parsing is interpreting a value from a form with no intrinsic relationship - i.e. there is no direct relationship between a dynamic ( i.e. value) and var (i.e. whatami2), but we can parse:

```<code>var whatami2 = hasValue ? bool.Parse(value) : true;
</code>```

Title: Why does C# infer this type as dynamic?

Body:
I have the following code.

public static void GuessTheType()
{
    dynamic hasValue = true;
    dynamic value = "true";

    var whatami1 = hasValue ? (string)value : null;
    var whatami2 = hasValue ? bool.Parse(value) : true;
    var whatami3 = hasValue ? (bool)bool.Parse(value) : true;
}

The type inferred by the compiler for whatami1 is string.

The type inferred by the compiler for whatami2 is dynamic.

The type inferred by the compiler for whatami3 is bool.

Why is the second type not bool?

Body:
Casting is our assertion (to the compiler) that an object really is something else - for example:

var whatami1 = hasValue ? (string)value : null;
var whatami3 = hasValue ? (bool)bool.Parse(value) : true;

Finally, parsing is interpreting a value from a form with no intrinsic relationship - i.e. there is no direct relationship between a dynamic ( i.e. value) and var (i.e. whatami2), but we can parse:

var whatami2 = hasValue ? bool.Parse(value) : true;


问:
Linux sed command
Can anyone help me understand what the following command does in Linux.</p>

```<code>sed -i file.c -e "s/  __attribute__ ((__unused__))$$/# ifndef __cplusplus\n  __attribute__ ((__unused__));\n# endif/"
</code>```

答:
As Greg says in a comment, the $$ will expand to the PID of the shell which doesn't make sense in the context. If it was a single dollar sign, or wasn't there, the command could be shortened to:

```<code>sed -i file.c -e "s/  __attribute__ ((__unused__))$/# ifndef __cplusplus\n&;\n# endif/"
</code>```

since & brings forward what was matched between the first pair of delimiters (slashes in this example). The single dollar sign causes the match to only be made if the string is at the end of the line.

Title: Linux sed command

Body:
Can anyone help me understand what the following command does in Linux.

sed -i file.c -e "s/  __attribute__ ((__unused__))$$/# ifndef __cplusplus\n  __attribute__ ((__unused__));\n# endif/"

Body:
As Greg says in a comment, the $$ will expand to the PID of the shell which doesn't make sense in the context. If it was a single dollar sign, or wasn't there, the command could be shortened to:

sed -i file.c -e "s/  __attribute__ ((__unused__))$/# ifndef __cplusplus\n&;\n# endif/"

since & brings forward what was matched between the first pair of delimiters (slashes in this example). The single dollar sign causes the match to only be made if the string is at the end of the line.


问:
How to access a form control for another form?
I have two Form classes, one of which has a ListBox. I need a setter for the SelectedIndex property of the ListBox, which I want to call from the second Form.

At the moment I am doing the following:

Form 1

```<code>public int MyListBoxSelectedIndex
{
     set { lsbMyList.SelectedIndex = value; }
}
</code>```

Form 2

```<code>private ControlForm mainForm; // form 1

public AddNewObjForm()
{
     InitializeComponent();
     mainForm = new ControlForm();
}

public void SomeMethod()
{
     mainForm.MyListBoxSelectedIndex = -1;
}
</code>```

Is this the best way to do this?

答:
There is one more way, in case you don't want to loop through "ALL" controls like Joe Dabones suggested.
Make a function in Form2 and call it from Form1.</p>

```<code>public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public void SetIndex(int value)
    {
        lsbMyList.SelectedIndex = value;
    }
}

public partial class Form1 : Form
{
    public Form2 frm;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        frm=new Form2();
        frm.Show();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        frm.SetIndex(Int.Parse(textBox1.Text));
    }
}
</code>```

Body:
I have two Form classes, one of which has a ListBox. I need a setter for the SelectedIndex property of the ListBox, which I want to call from the second Form.

At the moment I am doing the following:

Form 1

public int MyListBoxSelectedIndex
{
     set { lsbMyList.SelectedIndex = value; }
}

Form 2

private ControlForm mainForm; // form 1

public AddNewObjForm()
{
     InitializeComponent();
     mainForm = new ControlForm();
}

public void SomeMethod()
{
     mainForm.MyListBoxSelectedIndex = -1;
}

Is this the best way to do this?

Body:
There is one more way, in case you don't want to loop through "ALL" controls like Joe Dabones suggested.
Make a function in Form2 and call it from Form1.

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public void SetIndex(int value)
    {
        lsbMyList.SelectedIndex = value;
    }
}

public partial class Form1 : Form
{
    public Form2 frm;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        frm=new Form2();
        frm.Show();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        frm.SetIndex(Int.Parse(textBox1.Text));
    }
}


问:
Most efficient way to find the index of the only '1' bit in a char variable (in C)
This is an interview question:

You are given a char variable named ch, when you know that it represents a number that in its binary form, only one of its eight bits will be equal to '1'. I.E. , the only possible values for ch are: 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80.

Given the variable ch, I need to write the most efficient code to get the index of that '1' bit. For example: if ch == 0x1 -> result is 0. if ch == 0x4 -> result is 2.

The obvious way is to use switch-case, but I need something more efficient.

Is there any bit manipulation you can do here for efficient implementation?

答:
An unsigned char variable is supposedly only 8 bit wide. In order to encode the position of the bit we need only 3 bits. That means that we can build a 24-bit "table" that contains all 8 of possible 3-bit answers in their natural order

```<code>111 110 101 100 011 010 001 000 =

0xFAC688
</code>```

If your variable ch is known to contain only one 1 bit, then it is a power of 2. Dividing something by ch will right-shift the original value by the index of your 1 bit. So, if we divide the above "table" by your ch three times the answer will get shifted to the lowest 3 bits of the result

```<code>unsigned position = (0xFAC688 / ch / ch / ch) & 0x7;
</code>```

End of story. The above could probably be rewritten more efficiently, while preserving the general principle.

Note, that this is basically the same principle that's used in the approaches based on De Bruijn sequences. However, the purpose of De Bruijn sequence is to pack the index table in situations when the original "unpacked" table (like my table above) does not fit into an integer. As an "unpleasant" side effect, De Bruijn sequence reorders the index table, breaking the original natural sequence of indices. This requires extra re-mapping efforts to extract the proper result from the De Bruijn sequence.

With only 24 bits we don't have this problem here, which means that there's no need to involve De Bruijn and its accompanying tricks.

On the other hand, a packed table requires a shorter shift, which will simplify (and thus optimize) the calculation of the divisor to achieve the desired shift's length. In case of De Bruijn sequence, there's no need to calculate the divisor at all - your ch is already it. So, De Bruijn sequence might easily end up being more efficient.

Body:
An unsigned char variable is supposedly only 8 bit wide. In order to encode the position of the bit we need only 3 bits. That means that we can build a 24-bit "table" that contains all 8 of possible 3-bit answers in their natural order

111 110 101 100 011 010 001 000 =

0xFAC688

If your variable ch is known to contain only one 1 bit, then it is a power of 2. Dividing something by ch will right-shift the original value by the index of your 1 bit. So, if we divide the above "table" by your ch three times the answer will get shifted to the lowest 3 bits of the result

unsigned position = (0xFAC688 / ch / ch / ch) & 0x7;

End of story. The above could probably be rewritten more efficiently, while preserving the general principle.

Note, that this is basically the same principle that's used in the approaches based on De Bruijn sequences. However, the purpose of De Bruijn sequence is to pack the index table in situations when the original "unpacked" table (like my table above) does not fit into an integer. As an "unpleasant" side effect, De Bruijn sequence reorders the index table, breaking the original natural sequence of indices. This requires extra re-mapping efforts to extract the proper result from the De Bruijn sequence.

With only 24 bits we don't have this problem here, which means that there's no need to involve De Bruijn and its accompanying tricks.

On the other hand, a packed table requires a shorter shift, which will simplify (and thus optimize) the calculation of the divisor to achieve the desired shift's length. In case of De Bruijn sequence, there's no need to calculate the divisor at all - your ch is already it. So, De Bruijn sequence might easily end up being more efficient.


问:
Styling Text inside Android TextView
In my app, each Target Text has a mix of numbers and strings. I want the numbers to be highlighted in Bold and string to be italicised. For e.g.

You have reached 25% of your goal. 30 more days to achieve target

Is there an easier way to do it than create 5 separate textviews for this - 3 for string and 2 for number. Managing layout of 5 textboxes for each target is becoming a nightmare in my layout. I have 9 such rows leading to potentially 45 textviews in one layout.

答:
You can use  and  html tags within your string, like this:

```<code><string name="my_string"><i>You have reached</i> <b>25%</b> <i>of your goal.</i> <b>30</b> <i>more days to achieve target</i></string>
</code>```

You can read more here, under the Styling with HTML markup section: https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

Title: Styling Text inside Android TextView

Body:
You can use <i> and <b> html tags within your string, like this:

<string name="my_string"><i>You have reached</i> <b>25%</b> <i>of your goal.</i> <b>30</b> <i>more days to achieve target</i></string>

You can read more here, under the Styling with HTML markup section: https://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling


问:
Multi-client remote debugging using ChromeDriver and Chrome DevTools protocol
So with Chrome 63 there is now support for Multi-client remote debugging (https://developers.google.com/web/updates/2017/10/devtools-release-notes)

What I want to achieve is use the Chrome DevTools Protocol HeapProfiler with some selenium tests. I'm running version 64 Chrome dev channel and ChromeDriver 2.33.

```<code>ChromeOptions options = newChromeOptions();
options.addArguments("--remote-debugging-port=9222");
WebDriver driver = new ChromeDriver(options);
... selenium stuff
</code>```

A new chrome window will open and hang until it times out. I can confirm that the chrome window opened is chrome 64 by going to help > about google chrome to check the version.
I get this error which appears to be the the webdriver losing connection.

```<code>Exception in thread "main" org.openqa.selenium.WebDriverException: chrome not
reachable
</code>```

The DevTools Protocol is working because I am able to open http://localhost:9222 in another chrome window and see debugging interface.

Has anyone been able to get these two things to work together?

Thanks :)

答:
Here the catch was that if you pass the "remote-debugging-port" switch then chromedriver has a bug where it still internally assigns a randon port and keep trying to connect to it rather than connecting to 9222 port.

options.addArguments("--remote-debugging-port=9222");

We can solve this by skipping this command switch and let chrome decides this random port and extract this port number from chromedriver logs.

I made it work and here I have blogged it in detail.

https://medium.com/@sahajamit/selenium-chrome-dev-tools-makes-a-perfect-browser-automation-recipe-c35c7f6a2360

Body:
So with Chrome 63 there is now support for Multi-client remote debugging (https://developers.google.com/web/updates/2017/10/devtools-release-notes)

What I want to achieve is use the Chrome DevTools Protocol HeapProfiler with some selenium tests. I'm running version 64 Chrome dev channel and ChromeDriver 2.33.

ChromeOptions options = newChromeOptions();
options.addArguments("--remote-debugging-port=9222");
WebDriver driver = new ChromeDriver(options);
... selenium stuff

A new chrome window will open and hang until it times out. I can confirm that the chrome window opened is chrome 64 by going to help > about google chrome to check the version.
I get this error which appears to be the the webdriver losing connection.

Exception in thread "main" org.openqa.selenium.WebDriverException: chrome not
reachable

The DevTools Protocol is working because I am able to open http://localhost:9222 in another chrome window and see debugging interface.

Has anyone been able to get these two things to work together?

Thanks :)


问:
Assessing variables outside scope of a function declaration
I have several functions that work together to accomplish one task. Each of those functions live in their own file. In my main file, I compose these functions to accomplish my task.

Because of this, many functions need access to the same variables. My initial approach was to declare these variables in my main file with the expectation that I could call them within my functions.

However, when I run them I get reference errors inside my functions. My current alternative includes passing these variables into each function but it doesn't seem too elegant. I also considered making a class but I run into the issue of not being able to separate the functions into different files (for organizational purposes).

```<code>// doSomething.ts
declare outerVariable

function doSomething() {
  console.log(outerVariable)
}

// main
import doSomething from './doSomething.ts'

let outerVariable = 5
doSomething() // Reference Error: outerVariable is not defined
</code>```

I don't think variable shadowing is an issue because I never create variables with those names in my functions.

Any idea on what's going on or a better way to structure the code?

答:
Are there ways to accomplish what you are trying to do? Yes, but maybe that's not the way to go.

It seems you need to rethink your program structure as a whole.

First and foremost, polluting the global namespace is never a very good idea (in any programming language probably). If you are writing code using pure functional style, then yes, passing the variables as arguments to all the functions is how it's done. You can read a little about this on wikipedia (first paragraphs should give you a nice overview): https://en.wikipedia.org/wiki/Functional_programming

It also might be the case to minimize creating functions with side-effects as pointed in the comments of your question.

If the number of variables you are passing to theses functions is too large, perhaps you should consider splitting your code into smaller, more specialized functions/classes.

A single file usually contains only closely related functions or a single class.

Now, if you don't mind using objects, then you can pass to the functions one or more objects, grouping all your variables.

Also, the singleton pattern might be handy: https://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript.

Body:
I have several functions that work together to accomplish one task. Each of those functions live in their own file. In my main file, I compose these functions to accomplish my task.

Because of this, many functions need access to the same variables. My initial approach was to declare these variables in my main file with the expectation that I could call them within my functions.

However, when I run them I get reference errors inside my functions. My current alternative includes passing these variables into each function but it doesn't seem too elegant. I also considered making a class but I run into the issue of not being able to separate the functions into different files (for organizational purposes).

// doSomething.ts
declare outerVariable

function doSomething() {
  console.log(outerVariable)
}

// main
import doSomething from './doSomething.ts'

let outerVariable = 5
doSomething() // Reference Error: outerVariable is not defined

I don't think variable shadowing is an issue because I never create variables with those names in my functions.

Any idea on what's going on or a better way to structure the code?


问:
Reason to upgrade to elastic search to 5.x from 2.x
Currently i have a system running elastic search 2.4 with 40-50 indices holding very little data  (may be few hundreds of documents) used for data logging. There is a ask to add additional feature to index upto 50 billion documents. Now as this is new requirement, there is also thinking to update to 5.x but need solid data points as why this cannot be done on 2.4x.

Firstly community support available for 2.x? As 5.x is latest, would users of issues be encouraged to move to 5.x rather than solving in 2.x?

Are there major changes in architectural wise leading to performance improvements on
a) heap
b) CPU consumption
c) Anything else?
d) support for spark or hadoop for batch processing

答:
Yes. Many reasons. Even if you don't care about support , Performance enhancements in 5.x is good reason to migrate.

ES 5  uses newer version of Lucene in addition to several improvements in ES code itself.

Also since you have very few documents now  - this is the right time to upgrade ; It will be much easier / time saving than upgrading a larger index.


问:
Socket error on reading from client
I have a TCP client that gives bad address error. I think is related to this point of the code, but even trying all kind of possibilites, i cannot make it work:

```<code>n=recv(sockfd,&buffer[0],1000,0);
</code>```

buffer is defined as: std::vector<unsigned char> buffer; and it's resized to 1000 before I enter in the read loop. How could i fix it?

-----------EDIT

```<code>newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
</code>```

I'm aware of the error caused by the clilen declaration, so this is how i do it:

```<code>socklen_t clilen= sizeof(cli_addr);
</code>```

----SOLUTION:

I had set NONBLOCKING mode before creating the socket, that was creating a malfunction.

答:
```<code>n=recv(sockfd,&buffer[0],1000,0);
</code>```

The problem is here. You're receiving on the listening socket. It should be:

```<code>n=recv(newsockfd,&buffer[0],1000,0);
</code>```

Title: Socket error on reading from client

Body:
I have a TCP client that gives bad address error. I think is related to this point of the code, but even trying all kind of possibilites, i cannot make it work:

n=recv(sockfd,&buffer[0],1000,0);

buffer is defined as: std::vector<unsigned char> buffer; and it's resized to 1000 before I enter in the read loop. How could i fix it?

-----------EDIT

newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

I'm aware of the error caused by the clilen declaration, so this is how i do it:

socklen_t clilen= sizeof(cli_addr);

----SOLUTION:

I had set NONBLOCKING mode before creating the socket, that was creating a malfunction.

Body:
n=recv(sockfd,&buffer[0],1000,0);

The problem is here. You're receiving on the listening socket. It should be:

n=recv(newsockfd,&buffer[0],1000,0);


问:
Average performance measurements for local IPC
We are now assessing different IPC (or rather RPC) methods for our current project, which is in its very early stages. Performance is a big deal, and so we are making some measurements to aid our choice. Our processes that will be communicating will reside on the same machine.

A separate valid option is to avoid IPC altogether (by encapsulating the features of one of the processes in a .NET DLL and having the other one use it), but this is an option we would really like to avoid, as these two pieces of software are developed by two separate companies and we find it very important to maintain good "fences", which make good neighbors.

Our tests consisted of passing messages (which contain variously sized BLOBs) across process boundaries using each method. These are the figures we get (performance range correlates with message size range):

Web Service (SOAP over HTTP):

25-30 MB/s when binary data is encoded as Base64 (default)

70-100 MB/s when MTOM is utilized

.NET Remoting (BinaryFormatter over TCP): 100-115 MB/s

Control group - DLL method call + mem copy: 800-1000 MB/s

Now, we've been looking all over the place for some average performance figures for these (and other) IPC methods, including performance of raw TCP loopback sockets, but couldn't find any. Do these figures look sane? Why is the performance of these local IPC methods at least 10 times slower than copying memory? I couldn't get better results even when I used raw sockets - is the overhead of TCP that big?

答: Memory-mapped files + synchronization objects is the right way to go (almost the same as shared memory, but with more control). Sockets are way too slow for local communications. Especially it sometimes happens that network drivers are slower with localhost, than over network. </p>


问:
Flattening Nested Observable in object property
I am new to RxJs and trying to use it in my node app. Following code expects to return array of objects and each object should have nested array in one of its property.

Now the problem is it returns expected array of Objects, except the inner observable (that is supposed to be an array) is still not flattened in the subscribe.

```<code>createPlanOffers = (groupPlans) => {
    const groupPlan1 = groupPlans.filter(PREDICATE_1);
    return groupPlans
        .filter(PREDICATE_2)
        .reduce((offers, plan2) => {
            const plans_1 = groupPlan1.filter(PREDICATE_1_1);
            const plan1Details = plans_1.flatMap(plan1 => ({
                id: plan1.ID
            }));
            const offer = {
                groupKey: plan2.KEY,
                plan1Details: plan1Details
            };
            offers.push(offer);
            return offers;
        }, []);
};

const classPlans = query()
    .groupBy(group => group.KEY)
    .flatMap(groupPlans => createPlanOffers(groupPlans))
    .subscribe(group => console.log(group),
        err => console.log(err),
        () => console.log('complete'));
</code>```

Expected Result:

```<code>[
 { groupKey: 1111,
   plan1Details: [{id: xyz}]
 },
 { groupKey: 2222,
   plan1Details: [{id: xyz}]
 },
 { groupKey: 2222,
   plan1Details: [{id: abc}]
 }
]
</code>```

Actual Result :(

```<code>[
 { groupKey: 1111,
   plan1Details:
     Observable {
     _isScalar: false,
     source: [Observable],
     operator: [MergeMapOperator] } },
   { groupKey: 2222,
     plan1Details:
       Observable {
       _isScalar: false,
       source: [Observable],
       operator: [MergeMapOperator] } },
   { groupKey: 2222,
     plan1Details:
       Observable {
       _isScalar: false,
       source: [Observable],
       operator: [MergeMapOperator] } }
]
</code>```

This query will return something like:

```<code>const query = () => Rx.Observable.from([
    { KEY: 1111,
        id: 'xyz',
        category: 'A', // predicates are using these categories for filters
    }
    { GRGR_CK: 2222,
        id: 'xyz',
        category: 'A',
    }
    { GRGR_CK: 2222,
        id: 'ABC',
        category: 'B',
    }
])
</code>```

答:
Your plan1Details will be an Observable, since you return it as an Observable using .flatMap().

Since you have two predicates to filter, of which both are filtered after the grouping, you can use Observable.forkJoin() to combine them and transform them on the fly:

```<code>createPlanOffers = (groupPlans) => {
    const groupPlan1 = groupPlans.filter(PREDICATE_1);
    const groupPlan2 = groupPlans.filter(PREDICATE_2);
    return Observable.forkJoin([groupPlan1,groupPlan2])
        .map(([predicate1,predicate2])=>{
            predicate2.reduce((offers,plan2)=>{
                const offer = {
                    groupKey: plan2.KEY,
                    plan1Details: predicate1.map(plan1=>({id:plan1.ID})) //this map is an JS array.map(), not observable.map()
                };
                offers.push(offer);
                return offers

            },[])
        });
};
</code>```

Note that the .map() of predicate1.map() is a JavaScript's native array.map(), not the Observable one.

Body:
I am new to RxJs and trying to use it in my node app. Following code expects to return array of objects and each object should have nested array in one of its property.

Now the problem is it returns expected array of Objects, except the inner observable (that is supposed to be an array) is still not flattened in the subscribe.

createPlanOffers = (groupPlans) => {
    const groupPlan1 = groupPlans.filter(PREDICATE_1);
    return groupPlans
        .filter(PREDICATE_2)
        .reduce((offers, plan2) => {
            const plans_1 = groupPlan1.filter(PREDICATE_1_1);
            const plan1Details = plans_1.flatMap(plan1 => ({
                id: plan1.ID
            }));
            const offer = {
                groupKey: plan2.KEY,
                plan1Details: plan1Details
            };
            offers.push(offer);
            return offers;
        }, []);
};

const classPlans = query()
    .groupBy(group => group.KEY)
    .flatMap(groupPlans => createPlanOffers(groupPlans))
    .subscribe(group => console.log(group),
        err => console.log(err),
        () => console.log('complete'));

Expected Result:

[
 { groupKey: 1111,
   plan1Details: [{id: xyz}]
 },
 { groupKey: 2222,
   plan1Details: [{id: xyz}]
 },
 { groupKey: 2222,
   plan1Details: [{id: abc}]
 }
]

Actual Result :(

[
 { groupKey: 1111,
   plan1Details:
     Observable {
     _isScalar: false,
     source: [Observable],
     operator: [MergeMapOperator] } },
   { groupKey: 2222,
     plan1Details:
       Observable {
       _isScalar: false,
       source: [Observable],
       operator: [MergeMapOperator] } },
   { groupKey: 2222,
     plan1Details:
       Observable {
       _isScalar: false,
       source: [Observable],
       operator: [MergeMapOperator] } }
]

This query will return something like:

const query = () => Rx.Observable.from([
    { KEY: 1111,
        id: 'xyz',
        category: 'A', // predicates are using these categories for filters
    }
    { GRGR_CK: 2222,
        id: 'xyz',
        category: 'A',
    }
    { GRGR_CK: 2222,
        id: 'ABC',
        category: 'B',
    }
])

Body:
Your plan1Details will be an Observable, since you return it as an Observable using .flatMap().

Since you have two predicates to filter, of which both are filtered after the grouping, you can use Observable.forkJoin() to combine them and transform them on the fly:

createPlanOffers = (groupPlans) => {
    const groupPlan1 = groupPlans.filter(PREDICATE_1);
    const groupPlan2 = groupPlans.filter(PREDICATE_2);
    return Observable.forkJoin([groupPlan1,groupPlan2])
        .map(([predicate1,predicate2])=>{
            predicate2.reduce((offers,plan2)=>{
                const offer = {
                    groupKey: plan2.KEY,
                    plan1Details: predicate1.map(plan1=>({id:plan1.ID})) //this map is an JS array.map(), not observable.map()
                };
                offers.push(offer);
                return offers

            },[])
        });
};

Note that the .map() of predicate1.map() is a JavaScript's native array.map(), not the Observable one.


问:
How to add multiple instances of class in an array loop?
Main class is Zoo, Animal class performs Polymorphism by calling the pinStick method from each different Animal (other classes)

In the zoo array loop, int r's value is decided by Math.random which is 1 or 0 each time, resulting in a squeak, or a roar, depending which animal class is called.

My question is, how can I include an instance of the class Monkey to be printed every time the Mouse or Lion is called (in the if statement)

The aim is add a new instance of the monkey class so that in the result printout you have “OoOoAhAh” together with “Squeak” and “Roar”

```<code>public class Zoo {

private Animal[] animals;

public Zoo() {
    animals = new Animal[10];
}

public void talkAnimals() {
    int r;
    for (int i = 0; i < 10; i++) {

        r = (int) Math.round(Math.random());
        if (r == 0) {
            animals[i] = new Mouse();

        } else{
            animals[i] = new Lion();

        }

       }

    for (int i = 0; i < 10; i++) {

        animals[i].pinStick();

    }
}
public static void main(String[] args) {
    // TODO code application logic here
    new Zoo().talkAnimals();
}
</code>```

}

```<code>public class Animal {

protected String name;

public Animal(){
}

public void pinStick(){

}
</code>```

}

```<code>public class Mouse extends Animal {

public void pinStick(){
    System.out.print("Squeak!");

}
</code>```

}

```<code>public class Monkey extends Animal {

public void pinStick(){
    System.out.print("OoOoOoAhAhAh!");
}
</code>```

}

```<code>public class Lion extends Animal {

public void pinStick(){
    System.out.print("Roar!");

}
</code>```

}

答:
The aim is add a new instance of the monkey class so that in the result printout you have “OoOoAhAh” together with “Squeak” and “Roar”

You can just declare another array for Monkey

```<code>private Animal[] monkeys;
</code>```

constructor

```<code>monkeys = new Monkey[10];
</code>```

and pushes new Monkey object in for loop

```<code>for (int i = 0; i < 10; i++) {

    r = (int) Math.round(Math.random());
    if (r == 0) {
        animals[i] = new Mouse();

    } else{
        animals[i] = new Lion();

    }

        monkeys[i] = new Monkey();

   }
</code>```

then later on in the for loop just do the printing job

```<code>for (int i = 0; i < 10; i++) {

    animals[i].pinStick();
    monkeys[i].pinStick();
}
</code>```

Body:
Main class is Zoo, Animal class performs Polymorphism by calling the pinStick method from each different Animal (other classes)

In the zoo array loop, int r's value is decided by Math.random which is 1 or 0 each time, resulting in a squeak, or a roar, depending which animal class is called.

My question is, how can I include an instance of the class Monkey to be printed every time the Mouse or Lion is called (in the if statement)

The aim is add a new instance of the monkey class so that in the result printout you have “OoOoAhAh” together with “Squeak” and “Roar”

public class Zoo {

private Animal[] animals;

public Zoo() {
    animals = new Animal[10];
}

public void talkAnimals() {
    int r;
    for (int i = 0; i < 10; i++) {

        r = (int) Math.round(Math.random());
        if (r == 0) {
            animals[i] = new Mouse();

        } else{
            animals[i] = new Lion();

        }

       }

    for (int i = 0; i < 10; i++) {

        animals[i].pinStick();

    }
}
public static void main(String[] args) {
    // TODO code application logic here
    new Zoo().talkAnimals();
}

}

public class Animal {

protected String name;

public Animal(){
}

public void pinStick(){

}

}

public class Mouse extends Animal {

public void pinStick(){
    System.out.print("Squeak!");

}

}

public class Monkey extends Animal {

public void pinStick(){
    System.out.print("OoOoOoAhAhAh!");
}

}

public class Lion extends Animal {

public void pinStick(){
    System.out.print("Roar!");

}

}

Body:
The aim is add a new instance of the monkey class so that in the result printout you have “OoOoAhAh” together with “Squeak” and “Roar”

You can just declare another array for Monkey

private Animal[] monkeys;

constructor

monkeys = new Monkey[10];

and pushes new Monkey object in for loop

for (int i = 0; i < 10; i++) {

    r = (int) Math.round(Math.random());
    if (r == 0) {
        animals[i] = new Mouse();

    } else{
        animals[i] = new Lion();

    }

        monkeys[i] = new Monkey();

   }

then later on in the for loop just do the printing job

for (int i = 0; i < 10; i++) {

    animals[i].pinStick();
    monkeys[i].pinStick();
}