问:
Print characters as a Matrix
Below problem has a list of characters and number of columns as the input. Number of columns is not a constant and can vary with every input.
Output should have all the rows fully occupied except for the last one.

```<code>list: a b c d e f g
colums: 3

Wrong:
a b c
d e f
g

Wrong:
a d g
b e
c f

Correct:
a d f
b e g
c
</code>```

I have tried below:

```<code>public static void printPatern(List<Character> list, int cols) {

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

        for (int j = i; j < list.size(); j += cols) {
            System.out.print(list.get(j));

        }
        System.out.println();
    }
}
</code>```

It gives output as (which is wrong):

```<code>a d g
b e
c f
</code>```

I am trying to come with an algorithm to print the correct output. I want to know what are the different ways to solve this problem. Time and Space complexity doesn't matter. Also above method which I tried is wrong because it takes columns as the parameter but that's actually acting as the number of rows.

FYI: This is not a HOMEWORK problem.

答:
This is probably homework; so I am not going to do it for you, but give you some hints to get going. There are two points here:

computing the correct number of rows

computing the "pattern" that you need when looping your list so that you print the expected result

For the first part, you can look into the modulo operation; and for the second part: start iterating your list "on paper" and observe how you are printing the correct result manually.

Obviously, that second part is the more complicated one. It might help if you realize that printing "column by column" is straight forward. So when we take your correct example and print the indexes instead of values, you get:

```<code>0 3 6
1 4 7
2 5
</code>```

Do that repeatedly for different input; and you will soon discover the pattern of indexes that you need to print "row by row".

Title: Print characters as a Matrix

Body:
Below problem has a list of characters and number of columns as the input. Number of columns is not a constant and can vary with every input.
Output should have all the rows fully occupied except for the last one.

list: a b c d e f g
colums: 3

Wrong:
a b c
d e f
g

Wrong:
a d g
b e
c f

Correct:
a d f
b e g
c

I have tried below:

public static void printPatern(List<Character> list, int cols) {

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

        for (int j = i; j < list.size(); j += cols) {
            System.out.print(list.get(j));

        }
        System.out.println();
    }
}

It gives output as (which is wrong):

a d g
b e
c f

I am trying to come with an algorithm to print the correct output. I want to know what are the different ways to solve this problem. Time and Space complexity doesn't matter. Also above method which I tried is wrong because it takes columns as the parameter but that's actually acting as the number of rows.

FYI: This is not a HOMEWORK problem.

Body:
This is probably homework; so I am not going to do it for you, but give you some hints to get going. There are two points here:

computing the correct number of rows

computing the "pattern" that you need when looping your list so that you print the expected result

For the first part, you can look into the modulo operation; and for the second part: start iterating your list "on paper" and observe how you are printing the correct result manually.

Obviously, that second part is the more complicated one. It might help if you realize that printing "column by column" is straight forward. So when we take your correct example and print the indexes instead of values, you get:

0 3 6
1 4 7
2 5

Do that repeatedly for different input; and you will soon discover the pattern of indexes that you need to print "row by row".


来源: stackexchange

问:
How does the Visual Studio debugger know where the source is when loading an assembly at runtime?
Consider the following code:

```<code>private static void Main(string[] args)
{
    var exe = new MemoryStream(File.ReadAllBytes(args[0]));
    var assembly = AssemblyLoadContext.Default.LoadFromStream(exe);
    assembly.EntryPoint.Invoke(null, new object[] { new string[0] });
}
</code>```

This program was compiled in a .net core 1.1 application, and args contains the path to the dll of a generic hello world in .net core in it's debug output directory.

When I run this program, it loads the assembly from an in-memory copy of the dll and then calls the entry point. Visual Studio seems to successfully recognise that this dll is the same as the hello world project I have open in the solution and I can step through and debug this invoked program.

How does the VS Debugger know where to find the source when I loaded from an in-memory copy of the assembly?

答:
The answer is in this MSD page:

To use the full features of the Visual Studio debugger (like hitting
  breakpoints) when attaching to a process, the executable must exactly
  match your local source and symbols (that is, the debugger must be
  able to load the correct symbol (.pbd) files). By default, this
  requires a debug build.

Also,

A program database (.pdb) file, also called a symbol file, maps the
  identifiers that you create in source files for classes, methods, and
  other code to the identifiers that are used in the compiled
  executables of your project. The .pdb file also maps the statements in
  the source code to the execution instructions in the executables. The
  debugger uses this information to determine two key pieces of
  information: the source file and line number that are displayed in the
  Visual Studio IDE and the location in the executable to stop at when
  you set a breakpoint. A symbol file also contains the original
  location of the source files, and optionally, the location of a source
  server where the source files can be retrieved from.

Where the debugger searches for .pdb files

The location that is specified inside the DLL or the executable
file.

.pdb files that could be present in the same folder as the DLL
or executable file.

Any local symbol cache folders.

Any network,internet, or local symbol servers and locations that are specified on, such as the Microsoft symbol server if enabled.

ContentLicense: CC BY-SA 3.0

Body:
Consider the following code:

private static void Main(string[] args)
{
    var exe = new MemoryStream(File.ReadAllBytes(args[0]));
    var assembly = AssemblyLoadContext.Default.LoadFromStream(exe);
    assembly.EntryPoint.Invoke(null, new object[] { new string[0] });
}

This program was compiled in a .net core 1.1 application, and args contains the path to the dll of a generic hello world in .net core in it's debug output directory.

When I run this program, it loads the assembly from an in-memory copy of the dll and then calls the entry point. Visual Studio seems to successfully recognise that this dll is the same as the hello world project I have open in the solution and I can step through and debug this invoked program.

How does the VS Debugger know where to find the source when I loaded from an in-memory copy of the assembly?


问:
Pythonic way to avoid "if x: return x" statements
I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy.

```<code>def check_all_conditions():
    x = check_size()
    if x:
        return x

    x = check_color()
    if x:
        return x

    x = check_tone()
    if x:
        return x

    x = check_flavor()
    if x:
        return x
    return None
</code>```

This seems like a lot of baggage code. Instead of each 2-line if statement, I'd rather do something like:

```<code>x and return x
</code>```

But that is invalid Python. Am I missing a simple, elegant solution here? Incidentally, in this situation, those four check methods may be expensive, so I do not want to call them multiple times.

答:
I like @timgeb's. In the meantime I would like to add that expressing None in the return statement is not needed as the collection of or separated statements are evaluated and the first none-zero, none-empty, none-None is returned and if there isn't any then None is returned whether there is a None or not!

So my check_all_conditions() function looks like this:

```<code>def check_all_conditions():
    return check_size() or check_color() or check_tone() or check_flavor()
</code>```

Using timeit with number=10**7 I looked at the running time of a number of the suggestions. For the sake of comparison I just used the random.random() function to return a string or None based on random numbers. Here is the whole code:

```<code>import random
import timeit

def check_size():
    if random.random() < 0.25: return "BIG"

def check_color():
    if random.random() < 0.25: return "RED"

def check_tone():
    if random.random() < 0.25: return "SOFT"

def check_flavor():
    if random.random() < 0.25: return "SWEET"

def check_all_conditions_Bernard():
    x = check_size()
    if x:
        return x

    x = check_color()
    if x:
        return x

    x = check_tone()
    if x:
        return x

    x = check_flavor()
    if x:
        return x
    return None

def check_all_Martijn_Pieters():
    conditions = (check_size, check_color, check_tone, check_flavor)
    for condition in conditions:
        result = condition()
        if result:
            return result

def check_all_conditions_timgeb():
    return check_size() or check_color() or check_tone() or check_flavor() or None

def check_all_conditions_Reza():
    return check_size() or check_color() or check_tone() or check_flavor()

def check_all_conditions_Phinet():
    x = check_size()
    x = x if x else check_color()
    x = x if x else check_tone()
    x = x if x else check_flavor()

    return x if x else None

def all_conditions():
    yield check_size()
    yield check_color()
    yield check_tone()
    yield check_flavor()

def check_all_conditions_Phil_Frost():
    for condition in all_conditions():
        if condition:
            return condition

def main():
    num = 10000000
    random.seed(20)
    print("Bernard:", timeit.timeit('check_all_conditions_Bernard()', 'from __main__ import check_all_conditions_Bernard', number=num))
    random.seed(20)
    print("Martijn Pieters:", timeit.timeit('check_all_Martijn_Pieters()', 'from __main__ import check_all_Martijn_Pieters', number=num))
    random.seed(20)
    print("timgeb:", timeit.timeit('check_all_conditions_timgeb()', 'from __main__ import check_all_conditions_timgeb', number=num))
    random.seed(20)
    print("Reza:", timeit.timeit('check_all_conditions_Reza()', 'from __main__ import check_all_conditions_Reza', number=num))
    random.seed(20)
    print("Phinet:", timeit.timeit('check_all_conditions_Phinet()', 'from __main__ import check_all_conditions_Phinet', number=num))
    random.seed(20)
    print("Phil Frost:", timeit.timeit('check_all_conditions_Phil_Frost()', 'from __main__ import check_all_conditions_Phil_Frost', number=num))

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

And here are the results:

```<code>Bernard: 7.398444877040768
Martijn Pieters: 8.506569201346597
timgeb: 7.244275416364456
Reza: 6.982133448743038
Phinet: 7.925932800076634
Phil Frost: 11.924794811353031
</code>```

Body:
I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy.

def check_all_conditions():
    x = check_size()
    if x:
        return x

    x = check_color()
    if x:
        return x

    x = check_tone()
    if x:
        return x

    x = check_flavor()
    if x:
        return x
    return None

This seems like a lot of baggage code. Instead of each 2-line if statement, I'd rather do something like:

x and return x

But that is invalid Python. Am I missing a simple, elegant solution here? Incidentally, in this situation, those four check methods may be expensive, so I do not want to call them multiple times.

Body:
I like @timgeb's. In the meantime I would like to add that expressing None in the return statement is not needed as the collection of or separated statements are evaluated and the first none-zero, none-empty, none-None is returned and if there isn't any then None is returned whether there is a None or not!

So my check_all_conditions() function looks like this:

def check_all_conditions():
    return check_size() or check_color() or check_tone() or check_flavor()

Using timeit with number=10**7 I looked at the running time of a number of the suggestions. For the sake of comparison I just used the random.random() function to return a string or None based on random numbers. Here is the whole code:

import random
import timeit

def check_size():
    if random.random() < 0.25: return "BIG"

def check_color():
    if random.random() < 0.25: return "RED"

def check_tone():
    if random.random() < 0.25: return "SOFT"

def check_flavor():
    if random.random() < 0.25: return "SWEET"

def check_all_conditions_Bernard():
    x = check_size()
    if x:
        return x

    x = check_color()
    if x:
        return x

    x = check_tone()
    if x:
        return x

    x = check_flavor()
    if x:
        return x
    return None

def check_all_Martijn_Pieters():
    conditions = (check_size, check_color, check_tone, check_flavor)
    for condition in conditions:
        result = condition()
        if result:
            return result

def check_all_conditions_timgeb():
    return check_size() or check_color() or check_tone() or check_flavor() or None

def check_all_conditions_Reza():
    return check_size() or check_color() or check_tone() or check_flavor()

def check_all_conditions_Phinet():
    x = check_size()
    x = x if x else check_color()
    x = x if x else check_tone()
    x = x if x else check_flavor()

    return x if x else None

def all_conditions():
    yield check_size()
    yield check_color()
    yield check_tone()
    yield check_flavor()

def check_all_conditions_Phil_Frost():
    for condition in all_conditions():
        if condition:
            return condition

def main():
    num = 10000000
    random.seed(20)
    print("Bernard:", timeit.timeit('check_all_conditions_Bernard()', 'from __main__ import check_all_conditions_Bernard', number=num))
    random.seed(20)
    print("Martijn Pieters:", timeit.timeit('check_all_Martijn_Pieters()', 'from __main__ import check_all_Martijn_Pieters', number=num))
    random.seed(20)
    print("timgeb:", timeit.timeit('check_all_conditions_timgeb()', 'from __main__ import check_all_conditions_timgeb', number=num))
    random.seed(20)
    print("Reza:", timeit.timeit('check_all_conditions_Reza()', 'from __main__ import check_all_conditions_Reza', number=num))
    random.seed(20)
    print("Phinet:", timeit.timeit('check_all_conditions_Phinet()', 'from __main__ import check_all_conditions_Phinet', number=num))
    random.seed(20)
    print("Phil Frost:", timeit.timeit('check_all_conditions_Phil_Frost()', 'from __main__ import check_all_conditions_Phil_Frost', number=num))

if __name__ == '__main__':
    main()

And here are the results:

Bernard: 7.398444877040768
Martijn Pieters: 8.506569201346597
timgeb: 7.244275416364456
Reza: 6.982133448743038
Phinet: 7.925932800076634
Phil Frost: 11.924794811353031


问:
Insert comma delimited string to table in SQL
I found a similar questions are regarding this but I couldn't get it to for for my issue..

Lets say I have the string compiled of many many lines:

```<code>1,Users,2015-01-20\n
1,System,2015-01-18\n
....
....
</code>```

I need to put it into existing table:

```<code>╔══════════╦═══════════╦══════════╗
║ SomeNum  ║ SystemType║ Date     ║
╠══════════╬═══════════╬══════════╣

enter code here
</code>```

So it would look like:

```<code>╔══════════╦═══════════╦══════════╗
║ SomeNum  ║ SystemType║ Date     ║
╠══════════╬═══════════╬══════════╣
║ 1        ║     Users ║2015-01-20║
║ 1        ║    System ║2015-01-18║
</code>```

How do I do that? I must say I know little to nothing about SQL so forgive me for any stupid Q that will follow, thank you :)

答:
You can user Bulk Insert functionality of sql server.
first create text or csv file of the data

```<code>BULK INSERT table_name
FROM @filepath
WITH
  (
     FIELDTERMINATOR =',',
     ROWTERMINATOR ='\n'
  );
</code>```

Where table_name is your table name and @filepath is your csvfile path

For more information on bulk insert click here

Body:
I found a similar questions are regarding this but I couldn't get it to for for my issue..

Lets say I have the string compiled of many many lines:

1,Users,2015-01-20\n
1,System,2015-01-18\n
....
....

I need to put it into existing table:

╔══════════╦═══════════╦══════════╗
║ SomeNum  ║ SystemType║ Date     ║
╠══════════╬═══════════╬══════════╣

enter code here

So it would look like:

╔══════════╦═══════════╦══════════╗
║ SomeNum  ║ SystemType║ Date     ║
╠══════════╬═══════════╬══════════╣
║ 1        ║     Users ║2015-01-20║
║ 1        ║    System ║2015-01-18║

How do I do that? I must say I know little to nothing about SQL so forgive me for any stupid Q that will follow, thank you :)

Body:
You can user Bulk Insert functionality of sql server.
first create text or csv file of the data

BULK INSERT table_name
FROM @filepath
WITH
  (
     FIELDTERMINATOR =',',
     ROWTERMINATOR ='\n'
  );

Where table_name is your table name and @filepath is your csvfile path

For more information on bulk insert click here


问:
Raw Update Query inside a while loop in Django Python
Ok im new to python especially django so please be easy on me.

i just want to iterate through my resultset per row, then use its values for update query inside the while loop. so far i have this code.

```<code>def orprocesspost(request, pk):

cursor = connection.cursor()
#this query returns 2 rows
cursor.execute('select ord_recno, orm_recno, account_code, debit, credit, created_by, posted, remarks, origin, sort_order from or_details where orm_recno=%s', [pk])

row = cursor.fetchone()

while row is not None:

    cursor.execute('update general_ledger set dr_bal = dr_bal + %s, cr_bal = cr_bal + %s where gl_code = %s',[row[3],row[4],row[2]])
    row = cursor.fetchone()
</code>```

if i remove this line cursor.execute('update general_ledger set dr_bal = dr_bal + %s, cr_bal = cr_bal + %s where gl_code = %s',[row[3],row[4],row[2]])

the loop executes fine and i can see the second row being read

but when i try to use the update query it only updates 1 row... i don't know whats happening here. i've been searching for the solution for hours..

by the way i followed this tutorial Fetching row by row from MySQL in Python

Thanks and regards

答:
You can try using Django ORM to query database.
Its very easy to understand.</p>

```<code>def orprocesspost(request, pk):
  try:
     obj = or_details.objects.filter(orm_recno=pk)
     for i in obj:
        new_obj = general_ledger.objects.get(gl_code=i.xyz)
        #xyz : name of your model field.
        newobj.dr_bal = newobj.dr_bal + <new value>
        newobj.cr_bal = newobj.cr_bal + <new value>
        newobj.save()

  exept or_details.DoesNotExist:
    print "object does not exist"
</code>```

Body:
Ok im new to python especially django so please be easy on me.

i just want to iterate through my resultset per row, then use its values for update query inside the while loop. so far i have this code.

def orprocesspost(request, pk):

cursor = connection.cursor()
#this query returns 2 rows
cursor.execute('select ord_recno, orm_recno, account_code, debit, credit, created_by, posted, remarks, origin, sort_order from or_details where orm_recno=%s', [pk])

row = cursor.fetchone()

while row is not None:

    cursor.execute('update general_ledger set dr_bal = dr_bal + %s, cr_bal = cr_bal + %s where gl_code = %s',[row[3],row[4],row[2]])
    row = cursor.fetchone()

if i remove this line cursor.execute('update general_ledger set dr_bal = dr_bal + %s, cr_bal = cr_bal + %s where gl_code = %s',[row[3],row[4],row[2]])

the loop executes fine and i can see the second row being read

but when i try to use the update query it only updates 1 row... i don't know whats happening here. i've been searching for the solution for hours..

by the way i followed this tutorial Fetching row by row from MySQL in Python

Thanks and regards

Body:
You can try using Django ORM to query database.
Its very easy to understand.

def orprocesspost(request, pk):
  try:
     obj = or_details.objects.filter(orm_recno=pk)
     for i in obj:
        new_obj = general_ledger.objects.get(gl_code=i.xyz)
        #xyz : name of your model field.
        newobj.dr_bal = newobj.dr_bal + <new value>
        newobj.cr_bal = newobj.cr_bal + <new value>
        newobj.save()

  exept or_details.DoesNotExist:
    print "object does not exist"


答:
First it locates the .pdb and then from there it can locate the source files.

How does it locate the .pdb? From Specify Symbol (.pdb) and Source Files in the Visual Studio Debugger:

When you debug a project in the Visual Studio IDE, the debugger knows the default location for the .pdb and source files for your code.

...

(By default, if you have built a DLL or an executable file on your computer, the linker places the full path and file name of the associated .pdb file inside the DLL or the executable file. The debugger first checks to see if the symbol file exists in the location that is specified inside the DLL or the executable file. This is helpful, because you always have symbols available for code that you have compiled on your computer.)

There are other locations where it will also search for .pdbs but this one seems like the most likely source when you've tried to dissociate the assembly from its file on disk.

Title: How does the Visual Studio debugger know where the source is when loading an assembly at runtime?


问:
What is the meaning of 'No bundle URL present' in react-native?
When I run a react-native project, I get a error no bundle URL present , but I don't know what mistakes I do, I was very confused.

答:
Close your simulator and the terminal. Open new one and go to your project, then upgrade your react-native like this:

```<code>react-native upgrade
</code>```

Issue in: Infinite recursion in RCTFatal when the bundle fails to execute.

ContentLicense: CC BY-SA 4.0

Body:
Close your simulator and the terminal. Open new one and go to your project, then upgrade your react-native like this:

react-native upgrade

Issue in: Infinite recursion in RCTFatal when the bundle fails to execute.


问:
treating allocated memory as a different type
Suppose I allocate some memory.

```<code>char* buffer = (char*)my_malloc(2062);
</code>```

I assign char values to the first 14 bytes from a previously defined array named header.

```<code>memcpy(buffer, header, 14);
</code>```

Then I want to treat the rest of the allocated space as pointers to float.

```<code>float* float_buffer = (float*)(buffer + 14);
some_function(float_buffer);
</code>```

Then at some point later on I need to send all the data out.

```<code>transmit(buffer);
my_free(buffer);
</code>```

Is this correct way to treat memory?  Is the float* cast ok?  I am having issues where I am losing values and not getting the correct results.
My question is:
If you have to treat allocated memory as different types but then send it as char* at the end of the processing.....is this the correct way to do it?

I checked the ptr values and they are the same when they are float* and char* but I am not getting the correct result.

One of my restrictions is that I can only initially allocate one block of memory from a static buffer.  So calling another malloc as a different type (float*) is not allowed.

答:
I am speculating here, but since the prototype for malloc is

```<code>void *malloc(size_t size);
</code>```

you are essentially casting the buffer of type void* to char*, so later casting another chunk of the buffer to float* would be fine, so long as you take care of the pointer accounting properly.

ContentLicense: CC BY-SA 2.5

Body:
Suppose I allocate some memory.

char* buffer = (char*)my_malloc(2062);

I assign char values to the first 14 bytes from a previously defined array named header.

memcpy(buffer, header, 14);

Then I want to treat the rest of the allocated space as pointers to float.

float* float_buffer = (float*)(buffer + 14);
some_function(float_buffer);

Then at some point later on I need to send all the data out.

transmit(buffer);
my_free(buffer);

Is this correct way to treat memory?  Is the float* cast ok?  I am having issues where I am losing values and not getting the correct results.
My question is:
If you have to treat allocated memory as different types but then send it as char* at the end of the processing.....is this the correct way to do it?

I checked the ptr values and they are the same when they are float* and char* but I am not getting the correct result.

One of my restrictions is that I can only initially allocate one block of memory from a static buffer.  So calling another malloc as a different type (float*) is not allowed.

Body:
I am speculating here, but since the prototype for malloc is

void *malloc(size_t size);

you are essentially casting the buffer of type void* to char*, so later casting another chunk of the buffer to float* would be fine, so long as you take care of the pointer accounting properly.


问:
subscript out of bounds error when I use R to do an regression analysis
When I run the code below I receive:

```<code>"Error in coef(summary(linear))[6, 1] : subscript out of bounds
</code>```

Here is the code I run:

```<code>setwd("E:/test_analysis/TNBC")

data=read.table("gene_snp_regression.csv",header=T,sep=",")
result <- NULL
for (i in 10:708){
  linear <- lm(data[, 6] ~
                 data[,2]+data[,3]+data[,4]+data[,5]+data[,i], data = data)

  x.inv <- try(solve(coef(summary(linear))[6,4]),silent = TRUE)
  if ("try-error" %in% class(x.inv)) pvalue <- "NA"
  else pvalue <- coef(summary(linear))[6,4]

  beta <-  coef(summary(linear))[6,1]

  X <- cbind(beta, pvalue)

  result <- rbind(result, X)
}
write.csv(result,"sig1_genesnp.csv",row.names = T, quote = F)
</code>```

I wanna get the Estimate value "data[, i]"

```<code>                   Estimate Std. Error    t value     Pr(>|t|)
       (Intercept) 158.98784   54.67884  2.9076665 3.959462e-03
       data[, 2]    11.72500   14.42698  0.8127131 4.171348e-01
       data[, 3]    14.22904   14.53601  0.9788822 3.285587e-01
       data[, 4]   -52.44000   13.25313 -3.9567994 9.832974e-05
       data[, 5]   -23.63112   13.88214 -1.7022681 8.991430e-02
       data[, i]    12.74142   10.06581  1.2658112 2.067270e-01
</code>```

but after I run the code I  receive: "Error in coef(summary(linear))[6, 1] : subscript out of bounds.

Here is the structure of coef(summary(linear))

```<code>str(coef(summary(linear)))
num [1:6, 1:4] 159 11.7 14.2 -52.4 -23.6 ...
- attr(*, "dimnames")=List of 2
  ..$ : chr [1:6] "(Intercept)" "data[, 2]" "data[, 3]" "data[, 4]" ...
  ..$ : chr [1:4] "Estimate" "Std. Error" "t value" "Pr(>|t|)"
</code>```

答:
[6, 1] should pick up sixth element in column one. This leads me to believe that something is going wrong within the loop. There are many debugging options of how to handle this.

Inside for loop you can:

(1) Inserting print statements

```<code>print (i) # it will let you know where the problem occurs
print(dim(coef(summary(linear)))) # see dimensions of the result
</code>```

(2) Insert browser()

```<code>browser()
</code>```

and then manually step through the code by pressing n (or enter) to execute a line or c to run the whole loop once.

In your R sessions, you can set

```<code>options(error = recovery)
</code>```

and R will stop when an error occurs and will offer you to inspect various environments. At this point, you can determine the root cause of your errors by inspecting all the elements.

The pedestrian way of going about this would be to set i manually and step through the code, inspecting each element.

Body:
When I run the code below I receive:

"Error in coef(summary(linear))[6, 1] : subscript out of bounds

Here is the code I run:

setwd("E:/test_analysis/TNBC")

data=read.table("gene_snp_regression.csv",header=T,sep=",")
result <- NULL
for (i in 10:708){
  linear <- lm(data[, 6] ~
                 data[,2]+data[,3]+data[,4]+data[,5]+data[,i], data = data)

  x.inv <- try(solve(coef(summary(linear))[6,4]),silent = TRUE)
  if ("try-error" %in% class(x.inv)) pvalue <- "NA"
  else pvalue <- coef(summary(linear))[6,4]

  beta <-  coef(summary(linear))[6,1]

  X <- cbind(beta, pvalue)

  result <- rbind(result, X)
}
write.csv(result,"sig1_genesnp.csv",row.names = T, quote = F)

I wanna get the Estimate value "data[, i]"

                   Estimate Std. Error    t value     Pr(>|t|)
       (Intercept) 158.98784   54.67884  2.9076665 3.959462e-03
       data[, 2]    11.72500   14.42698  0.8127131 4.171348e-01
       data[, 3]    14.22904   14.53601  0.9788822 3.285587e-01
       data[, 4]   -52.44000   13.25313 -3.9567994 9.832974e-05
       data[, 5]   -23.63112   13.88214 -1.7022681 8.991430e-02
       data[, i]    12.74142   10.06581  1.2658112 2.067270e-01

but after I run the code I  receive: "Error in coef(summary(linear))[6, 1] : subscript out of bounds.

Here is the structure of coef(summary(linear))

str(coef(summary(linear)))
num [1:6, 1:4] 159 11.7 14.2 -52.4 -23.6 ...
- attr(*, "dimnames")=List of 2
  ..$ : chr [1:6] "(Intercept)" "data[, 2]" "data[, 3]" "data[, 4]" ...
  ..$ : chr [1:4] "Estimate" "Std. Error" "t value" "Pr(>|t|)"

Body:
[6, 1] should pick up sixth element in column one. This leads me to believe that something is going wrong within the loop. There are many debugging options of how to handle this.

Inside for loop you can:

(1) Inserting print statements

print (i) # it will let you know where the problem occurs
print(dim(coef(summary(linear)))) # see dimensions of the result

(2) Insert browser()

browser()

and then manually step through the code by pressing n (or enter) to execute a line or c to run the whole loop once.

In your R sessions, you can set

options(error = recovery)

and R will stop when an error occurs and will offer you to inspect various environments. At this point, you can determine the root cause of your errors by inspecting all the elements.

The pedestrian way of going about this would be to set i manually and step through the code, inspecting each element.


问:
Unexpected behavior around recursive regex
I am trying to match C++ argument type which can contain balanced <and > characters.

With this regex:
(\<(?>[^<>]|(?R))*\>)

On this string: QMap<QgsFeatureId, QPair<QMap<Something, Complex> >>

It matches all expect the first 4 characters (QMap).

Now, if I add \w+ at the start of my regex, it now only matches the end of it (QPair<QMap<Something, Complex> >>) and not the whole string.

What is the explanation and how to solve this?

You can try it online here.

This is intented to use in Perl 5.10+ (5.24).

答:
The (?R) construct recurses the entire pattern. When you add \w+ at the start, it is also accounted for when the recursion takes place. However, what you want to recurse is the Group 1 subpattern.

You need a subroutine call that will recurse the capturing group subpattern:

```<code>(\w+)(<(?:[^<>]++|(?2))*>)
</code>```

See the regex demo

Details

(\w+) - Group 1 capturing the identifier (you may change it to [a-zA-Z]\w*)

(<(?:[^<>]++|(?2))*>) - Group 2 (that will be recursed)

< - a literal <

(?:[^<>]++|(?2))* - either 1+ chars other than < and > (possessively, to make it faster) or (|) the whole Group 2 pattern ((?2)).

> - a literal >

Results:

```<code>Match:   QMap<QgsFeatureId, QPair<QMfap<Something, Complex> >>
Group 1: QMap
Group 2: <QgsFeatureId, QPair<QMfap<Something, Complex> >>
</code>```

Body:
The (?R) construct recurses the entire pattern. When you add \w+ at the start, it is also accounted for when the recursion takes place. However, what you want to recurse is the Group 1 subpattern.

You need a subroutine call that will recurse the capturing group subpattern:

(\w+)(<(?:[^<>]++|(?2))*>)

See the regex demo

Details

(\w+) - Group 1 capturing the identifier (you may change it to [a-zA-Z]\w*)

(<(?:[^<>]++|(?2))*>) - Group 2 (that will be recursed)

< - a literal <

(?:[^<>]++|(?2))* - either 1+ chars other than < and > (possessively, to make it faster) or (|) the whole Group 2 pattern ((?2)).

> - a literal >

Results:

Match:   QMap<QgsFeatureId, QPair<QMfap<Something, Complex> >>
Group 1: QMap
Group 2: <QgsFeatureId, QPair<QMfap<Something, Complex> >>


问:
PHP: Standards of class constructors preventing instantiation
Just a question on standards.

I've created a wrapper class for PHP session management, that helps automatically organize session data based on certain internal modules accessing it. It's designed as a singleton, using a getInstance() method to instantiate, since there will only be a single session at a given time. Also, this came as a benefit to me, as I am able to prevent instantiation of the session object in the (albeit probably limited) chance that session_start() fails. As for an example:

```<code>    public static function getInstance(){
        if(!self::$_instance || !session_id()){
            if(session_start()){
                self::$_instance = new self(session_id());
            }else{
                return;
            }

        }
        return self::$_instance;
    }
</code>```

My question is; although the use of a gateway getInstance() method works naturally here for a few reasons, is it common/good practice to implement public static getInstance() or create() methods in classes to control object creation if the object is reliant on external conditions?

I just find myself sticking to a convention of providing getInstance() in the case of singletons, and create() in the case of multiple instance objects.

TL;DR: I keep using getInstance() and create() methods to control all object instantiation. Am I doing it wrong?

EDIT: Refining my question a bit; Aside from using getInstance() for singletons, is my constructor wrapping with create() methods serving less purpose and more leaning towards bad convention? Should I be throwing Exceptions from the true constructor, or continue returning false from a create()?

答:
You should user __construct method then using create method.
As __construct is called by itself you can do initialization and other things in constructor .
Another benefit is you can forget to call create() method and your object can be in inconsistent state

Body:
Just a question on standards.

I've created a wrapper class for PHP session management, that helps automatically organize session data based on certain internal modules accessing it. It's designed as a singleton, using a getInstance() method to instantiate, since there will only be a single session at a given time. Also, this came as a benefit to me, as I am able to prevent instantiation of the session object in the (albeit probably limited) chance that session_start() fails. As for an example:

    public static function getInstance(){
        if(!self::$_instance || !session_id()){
            if(session_start()){
                self::$_instance = new self(session_id());
            }else{
                return;
            }

        }
        return self::$_instance;
    }

My question is; although the use of a gateway getInstance() method works naturally here for a few reasons, is it common/good practice to implement public static getInstance() or create() methods in classes to control object creation if the object is reliant on external conditions?

I just find myself sticking to a convention of providing getInstance() in the case of singletons, and create() in the case of multiple instance objects.

TL;DR: I keep using getInstance() and create() methods to control all object instantiation. Am I doing it wrong?

EDIT: Refining my question a bit; Aside from using getInstance() for singletons, is my constructor wrapping with create() methods serving less purpose and more leaning towards bad convention? Should I be throwing Exceptions from the true constructor, or continue returning false from a create()?


问:
how to assign a function return value in storedprocedure?
I have a function  ufnGetTVP  and needs to assign the return value to a table variable in stored procedure.

I have tried the below code but getting error. I couldnt find any relevant articles to fix this issue.

```<code>create proc testfunc( @input varchar(50))
as
begin
DECLARE @mt TABLE
set  @mt = select * from ufnGetTVP(@input)

end
</code>```

It will be helpful , if someone could identify what goes wrong here.

答:
You can use Temp tables also, You don't have to worry about column definitions.</p>

```<code>create proc testfunc( @input varchar(50))
as
begin

    select * into #temp from ufnGetTVP(@input)

    select * from #temp

    IF OBJECT_ID('tempdb..#temp') IS NOT NULL drop table #temp

end
</code>```

Body:
I have a function  ufnGetTVP  and needs to assign the return value to a table variable in stored procedure.

I have tried the below code but getting error. I couldnt find any relevant articles to fix this issue.

create proc testfunc( @input varchar(50))
as
begin
DECLARE @mt TABLE
set  @mt = select * from ufnGetTVP(@input)

end

It will be helpful , if someone could identify what goes wrong here.

Body:
You can use Temp tables also, You don't have to worry about column definitions.

create proc testfunc( @input varchar(50))
as
begin

    select * into #temp from ufnGetTVP(@input)

    select * from #temp

    IF OBJECT_ID('tempdb..#temp') IS NOT NULL drop table #temp

end


问:
Adding Events to Full Calendar using ASP.NET, C# and JSON
Ok, so I know this may be a bit of a duplicate of this question: fullCalendar events not showing even though correct JSON feed
But after trying the code to no avail I thought I would post another question to see if any body could help

Basically I'm trying to add events dynamically to the Full Calendar JQuery plugin with ASP.NET C# using data from an SQL Server Database.

Here is the code I have used in my web method in the code behind file

```<code>[WebMethod]
public static String TestOnWebService()
{

    String connectionString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString;
    SqlConnection myConnection = new SqlConnection(connectionString);

    myConnection.Open();

    String query = "SELECT * FROM timetable";

    SqlCommand cmd = new SqlCommand(query, myConnection);

    SqlDataReader reader = cmd.ExecuteReader();

    string myJsonString = "";
    List<object> myList = new List<object>();

    if (reader.HasRows)
    {
        var indexOfId = reader.GetOrdinal("id");
        var indexOfLecture = reader.GetOrdinal("lecture");
        var indexOfStartDate = reader.GetOrdinal("start_date");
        var indexOfEndDate = reader.GetOrdinal("end_date");
        var indexOfTimeStart = reader.GetOrdinal("start_time");
        var indexOfTimeEnd = reader.GetOrdinal("end_time");

        while (reader.Read())
        {

            var Id = reader.GetValue(indexOfId).ToString();
            var Lecture = reader.GetValue(indexOfLecture).ToString();
            var DateStart = reader.GetValue(indexOfStartDate).ToString();
            var DateEnd = reader.GetValue(indexOfEndDate).ToString();
            var StartTime = reader.GetValue(indexOfTimeStart);
            var EndTime = reader.GetValue(indexOfTimeEnd);

            //Convert Implicity typed var to Date Time
            DateTime RealStartDate = Convert.ToDateTime(DateStart);
            DateTime RealEndDate = Convert.ToDateTime(DateEnd);

            //Convert Date Time to ISO
            String SendStartDate = RealStartDate.ToString("s");
            String SendEndDate = RealEndDate.ToString("s");

            timeTable t_table = new timeTable(Id, Lecture, SendStartDate, SendEndDate);

            myList.Add(t_table);

        }
        myJsonString = (new JavaScriptSerializer()).Serialize(myList);

        myConnection.Close();
    }

    return myJsonString;

}
</code>```

}

and here is my AJAX call which I use to grab the JSON data via POST method:

```<code>$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function() {
        alert('a day has been clicked!');
    },
    events: function (start, end, callback) {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                alert(doc.d);
                var obj = $.parseJSON(doc.d);
                console.log(obj);
                $(obj.event).each(function () {
                    events.push({
                        title: $(this).attr('title'),
                        start: $(this).attr('start'),
                        end: $(this).attr('end'),
                        id: $(this).attr('id')
                    });
                });
                //callback(events);
                callback && callback(events);
            },
            error: function(xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})
</code>```

})

The AJAX call seems to succeed as I can alert out a success message and I can also alert out the JSON data, which looks like this:

I can also output the parsed object of the JSON Data in the console which looks like this:

I get no errors in the console when I do this but the events don't seem to add to the Full Calendar UI (which also appears fine on my page).

I think I might be going wrong somewhere with the following code but I can't seem to put my finger on it:

```<code>$(obj.event).each(function () {
  events.push({
  title: $(this).attr('title'),
  start: $(this).attr('start'),
  end: $(this).attr('end'),
  id: $(this).attr('id')
});
</code>```

Also I get an the error "Callback is not a function" when I use this code:

```<code>callback(events);
</code>```

But not when I use this:

```<code>callback && callback(events);
</code>```

I'm not sure if this has anything to do with the problems I'm experiencing but I thought I would add it in just in case.

Thanks in advance for any of your responses, they are much appreciated.

EDIT:

Apologies, I forgot to add the code for my timeTable class. It is as follows:

```<code>public class timeTable
{
public String id { get; set; }
public String title { get; set; }
public String start { get; set; }
public String end { get; set; }

public timeTable(String I, String t, String ds, String de)
{
    this.id = I;
    this.title = t;
    this.start = ds;
    this.end = de;
}

}
</code>```

My HTML is literally just one line:

```<code><div id="calendar"></div>
</code>```

Here is the javascript files I have linked in the head of my page

```<code>        <!-- Javascript -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src='js/moment.js'></script>
<script src='js/fullcalendar.js'></script>
<script src="js/script.js"></script>
</code>```

Update:

So another thing I've tried is looping through the object I have created using my JSON string and pushing it into the events array, however this doesn't seem to work either. See code below:

```<code>$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function () {
        alert('a day has been clicked!');
    },
    events: function (start, end, callback) {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                alert(doc.d);
                var obj = $.parseJSON(doc.d);
                console.log(obj);

                for (var k in obj) {// k represents the id keys 1,2,3
                    var d = obj[k]; // We assign a the reference to each id object to the d variable
                      for (var p in d) { //Next we access the nested objects by using the p variable
                          if (p.hasOwnProperty) { //Check to make sure p has its own properties
                              //alert(p + ":" + d[p]); //We alert the key (d) and the keys value (d[p])
                              events.push(p + ": " + d[p]);
                              }

                            }
                     }
                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})
</code>```

})

It outputs the array to the console but still doesn't show any events on the Full Calendar UI :-(

Update 2

Here's my next code edit which doesn't seem to have worked either, I unsure why as it populates the events array fine with the values needed, I also added a addDay = "false" attribute as well but still no joy, Any body at all got any idea's, I'm stumped:

```<code>$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function () {
        alert('a day has been clicked!');
    },
    events: function () {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                //console.log(doc.d);
                var obj = $.parseJSON(doc.d);
                //console.log(obj);

                $.each(obj, function (index) {

                    $.each(obj[index], function (key, value) {

                        events.push(key + ": " + value)

                    });

                });

                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})
</code>```

})

答:
Well this worked for me</p>

```<code><script>

    $(document).ready(function () {
        var something = "";
        $.ajax({
            type: "POST",
            url: "../04_Entries/04_42_ReservationCalander.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                var docd = doc.d;
                something = docd;

                var obj = $.parseJSON(doc.d);
                console.log(obj);

                for (var k in obj) {// k represents the id keys 1,2,3
                    var d = obj[k]; // We assign a the reference to each id object to the d variable
                    for (var p in d) { //Next we access the nested objects by using the p variable
                        if (p.hasOwnProperty) { //Check to make sure p has its own properties
                            //alert(p + ":" + d[p]); //We alert the key (d) and the keys value (d[p])
                            events.push(p + ": " + d[p]);
                        }

                    }
                }
                  $('#calendar').fullCalendar({
                    header: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,agendaWeek,agendaDay'
                    },
                    eventClick: function () {
                        alert('a day has been clicked!');
                    },
                    events: obj
                })
                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });

    });

</script>
</code>```

Body:
Ok, so I know this may be a bit of a duplicate of this question: fullCalendar events not showing even though correct JSON feed
But after trying the code to no avail I thought I would post another question to see if any body could help

Basically I'm trying to add events dynamically to the Full Calendar JQuery plugin with ASP.NET C# using data from an SQL Server Database.

Here is the code I have used in my web method in the code behind file

[WebMethod]
public static String TestOnWebService()
{

    String connectionString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString;
    SqlConnection myConnection = new SqlConnection(connectionString);

    myConnection.Open();

    String query = "SELECT * FROM timetable";

    SqlCommand cmd = new SqlCommand(query, myConnection);

    SqlDataReader reader = cmd.ExecuteReader();

    string myJsonString = "";
    List<object> myList = new List<object>();

    if (reader.HasRows)
    {
        var indexOfId = reader.GetOrdinal("id");
        var indexOfLecture = reader.GetOrdinal("lecture");
        var indexOfStartDate = reader.GetOrdinal("start_date");
        var indexOfEndDate = reader.GetOrdinal("end_date");
        var indexOfTimeStart = reader.GetOrdinal("start_time");
        var indexOfTimeEnd = reader.GetOrdinal("end_time");

        while (reader.Read())
        {

            var Id = reader.GetValue(indexOfId).ToString();
            var Lecture = reader.GetValue(indexOfLecture).ToString();
            var DateStart = reader.GetValue(indexOfStartDate).ToString();
            var DateEnd = reader.GetValue(indexOfEndDate).ToString();
            var StartTime = reader.GetValue(indexOfTimeStart);
            var EndTime = reader.GetValue(indexOfTimeEnd);

            //Convert Implicity typed var to Date Time
            DateTime RealStartDate = Convert.ToDateTime(DateStart);
            DateTime RealEndDate = Convert.ToDateTime(DateEnd);

            //Convert Date Time to ISO
            String SendStartDate = RealStartDate.ToString("s");
            String SendEndDate = RealEndDate.ToString("s");

            timeTable t_table = new timeTable(Id, Lecture, SendStartDate, SendEndDate);

            myList.Add(t_table);

        }
        myJsonString = (new JavaScriptSerializer()).Serialize(myList);

        myConnection.Close();
    }

    return myJsonString;

}

}

and here is my AJAX call which I use to grab the JSON data via POST method:

$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function() {
        alert('a day has been clicked!');
    },
    events: function (start, end, callback) {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                alert(doc.d);
                var obj = $.parseJSON(doc.d);
                console.log(obj);
                $(obj.event).each(function () {
                    events.push({
                        title: $(this).attr('title'),
                        start: $(this).attr('start'),
                        end: $(this).attr('end'),
                        id: $(this).attr('id')
                    });
                });
                //callback(events);
                callback && callback(events);
            },
            error: function(xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})

})

The AJAX call seems to succeed as I can alert out a success message and I can also alert out the JSON data, which looks like this:

I can also output the parsed object of the JSON Data in the console which looks like this:

I get no errors in the console when I do this but the events don't seem to add to the Full Calendar UI (which also appears fine on my page).

I think I might be going wrong somewhere with the following code but I can't seem to put my finger on it:

$(obj.event).each(function () {
  events.push({
  title: $(this).attr('title'),
  start: $(this).attr('start'),
  end: $(this).attr('end'),
  id: $(this).attr('id')
});

Also I get an the error "Callback is not a function" when I use this code:

callback(events);

But not when I use this:

callback && callback(events);

I'm not sure if this has anything to do with the problems I'm experiencing but I thought I would add it in just in case.

Thanks in advance for any of your responses, they are much appreciated.

EDIT:

Apologies, I forgot to add the code for my timeTable class. It is as follows:

public class timeTable
{
public String id { get; set; }
public String title { get; set; }
public String start { get; set; }
public String end { get; set; }

public timeTable(String I, String t, String ds, String de)
{
    this.id = I;
    this.title = t;
    this.start = ds;
    this.end = de;
}

}

My HTML is literally just one line:

Here is the javascript files I have linked in the head of my page

Update:

So another thing I've tried is looping through the object I have created using my JSON string and pushing it into the events array, however this doesn't seem to work either. See code below:

$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function () {
        alert('a day has been clicked!');
    },
    events: function (start, end, callback) {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                alert(doc.d);
                var obj = $.parseJSON(doc.d);
                console.log(obj);

                for (var k in obj) {// k represents the id keys 1,2,3
                    var d = obj[k]; // We assign a the reference to each id object to the d variable
                      for (var p in d) { //Next we access the nested objects by using the p variable
                          if (p.hasOwnProperty) { //Check to make sure p has its own properties
                              //alert(p + ":" + d[p]); //We alert the key (d) and the keys value (d[p])
                              events.push(p + ": " + d[p]);
                              }

                            }
                     }
                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})

})

It outputs the array to the console but still doesn't show any events on the Full Calendar UI :-(

Update 2

Here's my next code edit which doesn't seem to have worked either, I unsure why as it populates the events array fine with the values needed, I also added a addDay = "false" attribute as well but still no joy, Any body at all got any idea's, I'm stumped:

$(document).ready(function () {

$('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    eventClick: function () {
        alert('a day has been clicked!');
    },
    events: function () {
        $.ajax({
            type: "POST",
            url: "webserv.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                //console.log(doc.d);
                var obj = $.parseJSON(doc.d);
                //console.log(obj);

                $.each(obj, function (index) {

                    $.each(obj[index], function (key, value) {

                        events.push(key + ": " + value)

                    });

                });

                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
})

})

Body:
Well this worked for me

<script>

    $(document).ready(function () {
        var something = "";
        $.ajax({
            type: "POST",
            url: "../04_Entries/04_42_ReservationCalander.aspx/TestOnWebService",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (doc) {
                alert("Success");
                var events = [];
                var docd = doc.d;
                something = docd;

                var obj = $.parseJSON(doc.d);
                console.log(obj);

                for (var k in obj) {// k represents the id keys 1,2,3
                    var d = obj[k]; // We assign a the reference to each id object to the d variable
                    for (var p in d) { //Next we access the nested objects by using the p variable
                        if (p.hasOwnProperty) { //Check to make sure p has its own properties
                            //alert(p + ":" + d[p]); //We alert the key (d) and the keys value (d[p])
                            events.push(p + ": " + d[p]);
                        }

                    }
                }
                  $('#calendar').fullCalendar({
                    header: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,agendaWeek,agendaDay'
                    },
                    eventClick: function () {
                        alert('a day has been clicked!');
                    },
                    events: obj
                })
                console.log(events);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });

    });

</script>


问:
How to sort the elements of a recycler view in order of time that has implemented Firebase?
I am trying to order the elements of my recycler view that these photos are uploaded but they go in order from the oldest and to the last of the list are the most recent ones I found out but I do not know how to solve it

My recycler class this a fragment:

```<code> public class PostFragment extends Fragment {

private View mRootView;
private FirebaseRecyclerAdapter<Post, PostHolder> mPostAdapter;
private RecyclerView mPostRecyclerView;

public PostFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    mRootView = inflater.inflate(R.layout.fragment_post, container, false);
    FloatingActionButton fab = (FloatingActionButton) mRootView.findViewById(R.id.fabM);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PostCreateDialog dialog = new PostCreateDialog();
            dialog.show(getFragmentManager(), null);
        }
    });
    init();
    return mRootView;
}

private void init() {
    mPostRecyclerView = (RecyclerView) mRootView.findViewById(R.id.recyclerview_post);
    mPostRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    setupAdapter();
    mPostRecyclerView.setAdapter(mPostAdapter);

}

private void setupAdapter() {
    mPostAdapter = new FirebaseRecyclerAdapter<Post, PostHolder>(
            Post.class,
            R.layout.row_post,
            PostHolder.class,
            FirebaseUtils.getPostRef()
    ) {
        @Override
        protected void populateViewHolder(final PostHolder viewHolder, final Post model, int position) {
            viewHolder.setNumComments(String.valueOf(model.getNumComments()));
            viewHolder.setNumLikes(String.valueOf(model.getNumLikes()));
            viewHolder.setTime(DateUtils.getRelativeTimeSpanString(model.getTimeCreated()));
            viewHolder.postOwnerUsernameTextView.setText(model.getUsername());
            if(viewHolder.postOwnerUsernameTextView == null){
                viewHolder.postOwnerUsernameTextView.setText("Anonymous");
            }
            viewHolder.setPostText(model.getPostText());

                final StorageReference storageReference = FirebaseStorage.getInstance()
                        .getReference(model.getPostImageUrl());

            Glide.with(getActivity())
                    .using(new FirebaseImageLoader())
                    .load(storageReference).crossFade().fitCenter().into(viewHolder.postDisplayImageView);

            viewHolder.postLikeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onLikeClick(model.getPostId());
                }
            });

            viewHolder.postCommentLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), CommentActivity.class);
                    intent.putExtra(Constants.EXTRA_POST, model);
                    startActivity(intent);
                }
            });

        }
    };
}

private void onLikeClick(final String postId) {
    FirebaseUtils.getPostLikedRef(postId)
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.getValue() != null) {
                        //user liked
                        FirebaseUtils.getPostRef()
                                .child(postId)
                                .child("numLikes")
                                .runTransaction(new Transaction.Handler() {
                                    @Override
                                    public Transaction.Result doTransaction(MutableData mutableData) {
                                        long num = mutableData.getValue(Long.class);
                                        mutableData.setValue(num - 1);
                                        return Transaction.success(mutableData);
                                    }

                                    @Override
                                    public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
                                        FirebaseUtils.getPostLikedRef(postId)
                                                .setValue(null);
                                    }
                                });
                    } else {
                        FirebaseUtils.getPostRef()
                                .child(postId)
                                .child("numLikes")
                                .runTransaction(new Transaction.Handler() {
                                    @Override
                                    public Transaction.Result doTransaction(MutableData mutableData) {
                                        long num = mutableData.getValue(Long.class);
                                        mutableData.setValue(num + 1);
                                        return Transaction.success(mutableData);
                                    }

                                    @Override
                                    public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
                                        FirebaseUtils.getPostLikedRef(postId)
                                                .setValue(true);
                                    }
                                });
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
}

public static class PostHolder extends RecyclerView.ViewHolder {
    TextView postOwnerUsernameTextView;
    TextView postTimeCreatedTextView;

    ImageView postDisplayImageView;
    TextView postTextTextView;

    LinearLayout postLikeLayout;
    TextView postNumLikesTextView;

    LinearLayout postCommentLayout;
    TextView postNumCommentsTextView;

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

        postOwnerUsernameTextView = (TextView) itemView.findViewById(R.id.tv_post_username);
        postTimeCreatedTextView = (TextView) itemView.findViewById(R.id.tv_time);
        postDisplayImageView = (ImageView) itemView.findViewById(R.id.iv_post_display);
        postLikeLayout = (LinearLayout) itemView.findViewById(R.id.like_layout);
        postCommentLayout = (LinearLayout) itemView.findViewById(R.id.comment_layout);
        postNumLikesTextView = (TextView) itemView.findViewById(R.id.tv_likes);
        postNumCommentsTextView = (TextView) itemView.findViewById(R.id.tv_comments);
        postTextTextView = (TextView) itemView.findViewById(R.id.tv_post_text);

    }

    public void setUsername(String username) {
        postOwnerUsernameTextView.setText(username);
    }

    public void setTime(CharSequence time) {
        postTimeCreatedTextView.setText(time);
    }

    public void setNumLikes(String numLikes) {
        postNumLikesTextView.setText(numLikes);
    }

    public void setNumComments(String numComments) {
        postNumCommentsTextView.setText(numComments);
    }

    public void setPostText(String text) {
        postTextTextView.setText(text);
    }

}

}
</code>```

and the post dialog Here is where you select the photos to upload:

```<code>    public class PostCreateDialog extends DialogFragment implements          View.OnClickListener {
private static final int RC_PHOTO_PICKER = 1;
private View mRootView;
private Post mPost;

private ProgressDialog mProgressDialog;
private Uri mSelectedImageUri;
private ImageView mPostDisplay;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    mPost = new Post();
    mProgressDialog = new ProgressDialog(getContext());

    mRootView = getActivity().getLayoutInflater().inflate(R.layout.post_create_dialog, null);
    mPostDisplay = (ImageView) mRootView.findViewById(R.id.post_dialog_display);
    mRootView.findViewById(R.id.post_dialog_select_imageview).setOnClickListener(this);
    mRootView.findViewById(R.id.post_dialog_send_imageview).setOnClickListener(this);
    builder.setView(mRootView);
    return builder.create();
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.post_dialog_send_imageview:
            sendPost();
            break;
        case R.id.post_dialog_select_imageview:
            selectImage();
            break;
    }
}

private void selectImage() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/jpeg");
    intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}

private void sendPost() {
    mProgressDialog.setMessage("Sending post...");
    mProgressDialog.setCancelable(false);
    mProgressDialog.setIndeterminate(true);
    mProgressDialog.show();

    FirebaseUtils.getUserRef(FirebaseUtils.getCurrentUser().getEmail().replace(".", ","))
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User user = dataSnapshot.getValue(User.class);
                    final String postUid = FirebaseUtils.getUid();
                    TextView postDialogTextView = (TextView) mRootView.findViewById(R.id.post_dialog_edittext);
                    String text = postDialogTextView.getText().toString();
                    RegisterActivity r = new RegisterActivity();

                    mPost.setNumComments(0);
                    mPost.setNumLikes(0);
                    mPost.setTimeCreated(System.currentTimeMillis());
                    mPost.setPostId(postUid);
                    mPost.setPostText(text);

                    if (mSelectedImageUri != null) {
                        FirebaseUtils.getImagesSRef()
                                .child(mSelectedImageUri.getLastPathSegment())
                                .putFile(mSelectedImageUri)
                                .addOnSuccessListener(getActivity(),
                                        new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                            @Override
                                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                                String url = Constants.POST_IMAGES + "/" + mSelectedImageUri.getLastPathSegment();
                                                //String downloadUrl = taskSnapshot.getDownloadUrl().toString();
                                                mPost.setPostImageUrl(url);
                                                addToMyPostList(postUid);
                                            }

                                        });
                    } else {
                        Toast.makeText(getContext(), "No puedes postear sin imagen", Toast.LENGTH_LONG).show();
                        mProgressDialog.dismiss();
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    mProgressDialog.dismiss();
                }
            });
}

private void addToMyPostList(final String postUid) {
    FirebaseUtils.getPostRef().child(postUid)
            .setValue(mPost);
    FirebaseUtils.getMyPostRef().child(postUid).setValue(true)
            .addOnCompleteListener(getActivity(), new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    mProgressDialog.dismiss();
                    dismiss();
                }
            });

    FirebaseUtils.addToMyRecord(Constants.POSTS_KEY, postUid);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_PHOTO_PICKER) {
        if (resultCode == RESULT_OK) {
            mSelectedImageUri = data.getData();
            mPostDisplay.setImageURI(mSelectedImageUri);
        }
    }
}
}
</code>```

and the utlis:

```<code>   public static DatabaseReference getUserRef(String email) {
    return FirebaseDatabase.getInstance()
            .getReference(Constants.USERS_KEYS)
            .child(email);
}
public static FirebaseUser getCurrentUser() {
    return FirebaseAuth.getInstance().getCurrentUser();
}

// POST REFERENCE
public static DatabaseReference getPostRef() {
    return FirebaseDatabase.getInstance()
            .getReference(Constants.POSTS_KEY);
}
public static Query getPostQuery() {
    return getPostRef().orderByChild(Constants.TIME_CREATED_KEY);
}
public static DatabaseReference getMyPostRef() {
    return FirebaseDatabase.getInstance().getReference(Constants.MY_POSTS)
            .child(getCurrentUser().getEmail().replace(".", ","));
}

// POST LIKED REFERENCE
public static DatabaseReference getPostLikedRef() {
    return FirebaseDatabase.getInstance()
            .getReference(Constants.POSTS_LIKED_KEY);
}
public static DatabaseReference getPostLikedRef(String postId) {
    return getPostLikedRef().child(getCurrentUser().getEmail()
            .replace(".", ","))
            .child(postId);
}

// USER ID
public static String getUid() {
    String path = FirebaseDatabase.getInstance().getReference().push().toString();
    return path.substring(path.lastIndexOf("/") + 1);
}

// POST IMAGE REFERENCE
public static StorageReference getImagesSRef() {
    return FirebaseStorage.getInstance().getReference(Constants.POST_IMAGES);
}

// COMMENT REFERENCE
public static DatabaseReference getCommentRef(String postId) {
    return FirebaseDatabase.getInstance().getReference(Constants.COMMENTS_KEY)
            .child(postId);
}

// RECORD

public static DatabaseReference getMyRecordRef() {
    return FirebaseDatabase.getInstance().getReference(Constants.USER_RECORD)
            .child(getCurrentUser().getEmail().replace(".", ","));
}

public static void addToMyRecord(String node,final String id) {
    FirebaseUtils.getMyRecordRef().child(node).runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            ArrayList<String> myPostCollection;
            if (mutableData.getValue() == null) {
                myPostCollection = new ArrayList<>(1);
                myPostCollection.add(id);
                mutableData.setValue(myPostCollection);
            } else {
                myPostCollection = (ArrayList<String>) mutableData.getValue();
                myPostCollection.add(id);
                mutableData.setValue(myPostCollection);
            }
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {

        }
    });
}
}
</code>```

答:
Try this:</p>

```<code>private void setupAdapter() {
    mPostAdapter = new FirebaseRecyclerAdapter<Post, PostHolder>(
        Post.class,
        R.layout.row_post,
        PostHolder.class,
       FirebaseDatabase.getInstance().getReference(Constants.POSTS_KEY).orderByChild("TimeCreated")
    )
}
</code>```

Body:
I am trying to order the elements of my recycler view that these photos are uploaded but they go in order from the oldest and to the last of the list are the most recent ones I found out but I do not know how to solve it

My recycler class this a fragment:

 public class PostFragment extends Fragment {

private View mRootView;
private FirebaseRecyclerAdapter<Post, PostHolder> mPostAdapter;
private RecyclerView mPostRecyclerView;

public PostFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    mRootView = inflater.inflate(R.layout.fragment_post, container, false);
    FloatingActionButton fab = (FloatingActionButton) mRootView.findViewById(R.id.fabM);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PostCreateDialog dialog = new PostCreateDialog();
            dialog.show(getFragmentManager(), null);
        }
    });
    init();
    return mRootView;
}

private void init() {
    mPostRecyclerView = (RecyclerView) mRootView.findViewById(R.id.recyclerview_post);
    mPostRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    setupAdapter();
    mPostRecyclerView.setAdapter(mPostAdapter);

}

private void setupAdapter() {
    mPostAdapter = new FirebaseRecyclerAdapter<Post, PostHolder>(
            Post.class,
            R.layout.row_post,
            PostHolder.class,
            FirebaseUtils.getPostRef()
    ) {
        @Override
        protected void populateViewHolder(final PostHolder viewHolder, final Post model, int position) {
            viewHolder.setNumComments(String.valueOf(model.getNumComments()));
            viewHolder.setNumLikes(String.valueOf(model.getNumLikes()));
            viewHolder.setTime(DateUtils.getRelativeTimeSpanString(model.getTimeCreated()));
            viewHolder.postOwnerUsernameTextView.setText(model.getUsername());
            if(viewHolder.postOwnerUsernameTextView == null){
                viewHolder.postOwnerUsernameTextView.setText("Anonymous");
            }
            viewHolder.setPostText(model.getPostText());

                final StorageReference storageReference = FirebaseStorage.getInstance()
                        .getReference(model.getPostImageUrl());

            Glide.with(getActivity())
                    .using(new FirebaseImageLoader())
                    .load(storageReference).crossFade().fitCenter().into(viewHolder.postDisplayImageView);

            viewHolder.postLikeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onLikeClick(model.getPostId());
                }
            });

            viewHolder.postCommentLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), CommentActivity.class);
                    intent.putExtra(Constants.EXTRA_POST, model);
                    startActivity(intent);
                }
            });

        }
    };
}

private void onLikeClick(final String postId) {
    FirebaseUtils.getPostLikedRef(postId)
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if (dataSnapshot.getValue() != null) {
                        //user liked
                        FirebaseUtils.getPostRef()
                                .child(postId)
                                .child("numLikes")
                                .runTransaction(new Transaction.Handler() {
                                    @Override
                                    public Transaction.Result doTransaction(MutableData mutableData) {
                                        long num = mutableData.getValue(Long.class);
                                        mutableData.setValue(num - 1);
                                        return Transaction.success(mutableData);
                                    }

                                    @Override
                                    public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
                                        FirebaseUtils.getPostLikedRef(postId)
                                                .setValue(null);
                                    }
                                });
                    } else {
                        FirebaseUtils.getPostRef()
                                .child(postId)
                                .child("numLikes")
                                .runTransaction(new Transaction.Handler() {
                                    @Override
                                    public Transaction.Result doTransaction(MutableData mutableData) {
                                        long num = mutableData.getValue(Long.class);
                                        mutableData.setValue(num + 1);
                                        return Transaction.success(mutableData);
                                    }

                                    @Override
                                    public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
                                        FirebaseUtils.getPostLikedRef(postId)
                                                .setValue(true);
                                    }
                                });
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
}

public static class PostHolder extends RecyclerView.ViewHolder {
    TextView postOwnerUsernameTextView;
    TextView postTimeCreatedTextView;

    ImageView postDisplayImageView;
    TextView postTextTextView;

    LinearLayout postLikeLayout;
    TextView postNumLikesTextView;

    LinearLayout postCommentLayout;
    TextView postNumCommentsTextView;

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

        postOwnerUsernameTextView = (TextView) itemView.findViewById(R.id.tv_post_username);
        postTimeCreatedTextView = (TextView) itemView.findViewById(R.id.tv_time);
        postDisplayImageView = (ImageView) itemView.findViewById(R.id.iv_post_display);
        postLikeLayout = (LinearLayout) itemView.findViewById(R.id.like_layout);
        postCommentLayout = (LinearLayout) itemView.findViewById(R.id.comment_layout);
        postNumLikesTextView = (TextView) itemView.findViewById(R.id.tv_likes);
        postNumCommentsTextView = (TextView) itemView.findViewById(R.id.tv_comments);
        postTextTextView = (TextView) itemView.findViewById(R.id.tv_post_text);

    }

    public void setUsername(String username) {
        postOwnerUsernameTextView.setText(username);
    }

    public void setTime(CharSequence time) {
        postTimeCreatedTextView.setText(time);
    }

    public void setNumLikes(String numLikes) {
        postNumLikesTextView.setText(numLikes);
    }

    public void setNumComments(String numComments) {
        postNumCommentsTextView.setText(numComments);
    }

    public void setPostText(String text) {
        postTextTextView.setText(text);
    }

}

}

and the post dialog Here is where you select the photos to upload:

    public class PostCreateDialog extends DialogFragment implements          View.OnClickListener {
private static final int RC_PHOTO_PICKER = 1;
private View mRootView;
private Post mPost;

private ProgressDialog mProgressDialog;
private Uri mSelectedImageUri;
private ImageView mPostDisplay;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    mPost = new Post();
    mProgressDialog = new ProgressDialog(getContext());

    mRootView = getActivity().getLayoutInflater().inflate(R.layout.post_create_dialog, null);
    mPostDisplay = (ImageView) mRootView.findViewById(R.id.post_dialog_display);
    mRootView.findViewById(R.id.post_dialog_select_imageview).setOnClickListener(this);
    mRootView.findViewById(R.id.post_dialog_send_imageview).setOnClickListener(this);
    builder.setView(mRootView);
    return builder.create();
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.post_dialog_send_imageview:
            sendPost();
            break;
        case R.id.post_dialog_select_imageview:
            selectImage();
            break;
    }
}

private void selectImage() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/jpeg");
    intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
    startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}

private void sendPost() {
    mProgressDialog.setMessage("Sending post...");
    mProgressDialog.setCancelable(false);
    mProgressDialog.setIndeterminate(true);
    mProgressDialog.show();

    FirebaseUtils.getUserRef(FirebaseUtils.getCurrentUser().getEmail().replace(".", ","))
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User user = dataSnapshot.getValue(User.class);
                    final String postUid = FirebaseUtils.getUid();
                    TextView postDialogTextView = (TextView) mRootView.findViewById(R.id.post_dialog_edittext);
                    String text = postDialogTextView.getText().toString();
                    RegisterActivity r = new RegisterActivity();

                    mPost.setNumComments(0);
                    mPost.setNumLikes(0);
                    mPost.setTimeCreated(System.currentTimeMillis());
                    mPost.setPostId(postUid);
                    mPost.setPostText(text);

                    if (mSelectedImageUri != null) {
                        FirebaseUtils.getImagesSRef()
                                .child(mSelectedImageUri.getLastPathSegment())
                                .putFile(mSelectedImageUri)
                                .addOnSuccessListener(getActivity(),
                                        new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                            @Override
                                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                                String url = Constants.POST_IMAGES + "/" + mSelectedImageUri.getLastPathSegment();
                                                //String downloadUrl = taskSnapshot.getDownloadUrl().toString();
                                                mPost.setPostImageUrl(url);
                                                addToMyPostList(postUid);
                                            }

                                        });
                    } else {
                        Toast.makeText(getContext(), "No puedes postear sin imagen", Toast.LENGTH_LONG).show();
                        mProgressDialog.dismiss();
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    mProgressDialog.dismiss();
                }
            });
}

private void addToMyPostList(final String postUid) {
    FirebaseUtils.getPostRef().child(postUid)
            .setValue(mPost);
    FirebaseUtils.getMyPostRef().child(postUid).setValue(true)
            .addOnCompleteListener(getActivity(), new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    mProgressDialog.dismiss();
                    dismiss();
                }
            });

    FirebaseUtils.addToMyRecord(Constants.POSTS_KEY, postUid);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_PHOTO_PICKER) {
        if (resultCode == RESULT_OK) {
            mSelectedImageUri = data.getData();
            mPostDisplay.setImageURI(mSelectedImageUri);
        }
    }
}
}

and the utlis:

   public static DatabaseReference getUserRef(String email) {
    return FirebaseDatabase.getInstance()
            .getReference(Constants.USERS_KEYS)
            .child(email);
}
public static FirebaseUser getCurrentUser() {
    return FirebaseAuth.getInstance().getCurrentUser();
}

// POST REFERENCE
public static DatabaseReference getPostRef() {
    return FirebaseDatabase.getInstance()
            .getReference(Constants.POSTS_KEY);
}
public static Query getPostQuery() {
    return getPostRef().orderByChild(Constants.TIME_CREATED_KEY);
}
public static DatabaseReference getMyPostRef() {
    return FirebaseDatabase.getInstance().getReference(Constants.MY_POSTS)
            .child(getCurrentUser().getEmail().replace(".", ","));
}

// POST LIKED REFERENCE
public static DatabaseReference getPostLikedRef() {
    return FirebaseDatabase.getInstance()
            .getReference(Constants.POSTS_LIKED_KEY);
}
public static DatabaseReference getPostLikedRef(String postId) {
    return getPostLikedRef().child(getCurrentUser().getEmail()
            .replace(".", ","))
            .child(postId);
}

// USER ID
public static String getUid() {
    String path = FirebaseDatabase.getInstance().getReference().push().toString();
    return path.substring(path.lastIndexOf("/") + 1);
}

// POST IMAGE REFERENCE
public static StorageReference getImagesSRef() {
    return FirebaseStorage.getInstance().getReference(Constants.POST_IMAGES);
}

// COMMENT REFERENCE
public static DatabaseReference getCommentRef(String postId) {
    return FirebaseDatabase.getInstance().getReference(Constants.COMMENTS_KEY)
            .child(postId);
}

// RECORD

public static DatabaseReference getMyRecordRef() {
    return FirebaseDatabase.getInstance().getReference(Constants.USER_RECORD)
            .child(getCurrentUser().getEmail().replace(".", ","));
}

public static void addToMyRecord(String node,final String id) {
    FirebaseUtils.getMyRecordRef().child(node).runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(MutableData mutableData) {
            ArrayList<String> myPostCollection;
            if (mutableData.getValue() == null) {
                myPostCollection = new ArrayList<>(1);
                myPostCollection.add(id);
                mutableData.setValue(myPostCollection);
            } else {
                myPostCollection = (ArrayList<String>) mutableData.getValue();
                myPostCollection.add(id);
                mutableData.setValue(myPostCollection);
            }
            return Transaction.success(mutableData);
        }

        @Override
        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {

        }
    });
}
}

Body:
Try this:

private void setupAdapter() {
    mPostAdapter = new FirebaseRecyclerAdapter<Post, PostHolder>(
        Post.class,
        R.layout.row_post,
        PostHolder.class,
       FirebaseDatabase.getInstance().getReference(Constants.POSTS_KEY).orderByChild("TimeCreated")
    )
}


问:
pass an objective-c object to javaScript function
Pass an customed Objective-C object to JSContext,so we can call object's method in js,but i want to pass it to a javaScript function then in this function I can call that object's method.

```<code>function myJs(para){
    para.myMethod();
    //this para is an customed objective-c object which had implemented JSExport protocol
}
// call that js function
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"myJs(%@)", para]];
</code>```

However it doesn't work, so is there any way to implement it?

答:
There is no option to call Objective-C methods from javascript directly, but you can achieve this by calling an URL from javascript and capture it using webView:shouldStartLoadWithRequest:navigationType: delegate method.

Just make an URL redirection from javascript and catch it in delegate please check below code

```<code>  // This function is called on all location change :
  - (BOOL)webView:(UIWebView *)webView2
          shouldStartLoadWithRequest:(NSURLRequest *)request
          navigationType:(UIWebViewNavigationType)navigationType {

    // Intercept custom location change, URL begins with "js-call:"
    if ([[[request URL] absoluteString] hasPrefix:@"js-call:"]) {

      // Extract the selector name from the URL
      NSArray *components = [requestString componentsSeparatedByString:@":"];
      NSString *function = [components objectAtIndex:1];

      // Call the given selector
      [self performSelector:NSSelectorFromString(functionName)];

      // Cancel the location change
      return NO;
    }

    // Accept this location change
    return YES;

  }
</code>```

Here is the excellent tutorial that helps to do it

Body:
Pass an customed Objective-C object to JSContext,so we can call object's method in js,but i want to pass it to a javaScript function then in this function I can call that object's method.

function myJs(para){
    para.myMethod();
    //this para is an customed objective-c object which had implemented JSExport protocol
}
// call that js function
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"myJs(%@)", para]];

However it doesn't work, so is there any way to implement it?

Body:
There is no option to call Objective-C methods from javascript directly, but you can achieve this by calling an URL from javascript and capture it using webView:shouldStartLoadWithRequest:navigationType: delegate method.

Just make an URL redirection from javascript and catch it in delegate please check below code

  // This function is called on all location change :
  - (BOOL)webView:(UIWebView *)webView2
          shouldStartLoadWithRequest:(NSURLRequest *)request
          navigationType:(UIWebViewNavigationType)navigationType {

    // Intercept custom location change, URL begins with "js-call:"
    if ([[[request URL] absoluteString] hasPrefix:@"js-call:"]) {

      // Extract the selector name from the URL
      NSArray *components = [requestString componentsSeparatedByString:@":"];
      NSString *function = [components objectAtIndex:1];

      // Call the given selector
      [self performSelector:NSSelectorFromString(functionName)];

      // Cancel the location change
      return NO;
    }

    // Accept this location change
    return YES;

  }

Here is the excellent tutorial that helps to do it


问:
python3 argparse autocomplete fail
i find some strange thing when i use arparse in python3.

```<code>#!/usr/bin/env python3

import argparse

def create_parser():
    p = argparse.ArgumentParser(add_help=True)
    p.add_argument('-i', help='i parameter', required=True)
    p.add_argument('-m', help='m parameter', required=True)
    return p

if __name__ == '__main__':
    p = create_parser()
    n = p.parse_args()
    print(n)
</code>```

when i try launch it with

```<code>python3 ./script.py -i ./some_folder/some_file -m ./
</code>```

bash autocomplete work with '-i' parameter, but not work with '-m'. If i rename '-m' to '-me' for example, all works good.

In bash i try launch other commands with '-m' parameter, but it not work only with argparse. Where can there be a mistake here?

答:
What happens here is that the autocompletion for the python3 comand kicks in:

$ complete | grep python
complete -F _python python2
complete -F _python python3
complete -F _python python
```

<p>The function <code>_python</code> that handles it should look like this:</p>

<pre class="lang-none prettyprint-override"><code>$ type _python
_python is a function
_python ()
{
    local cur prev words cword;
    _init_completion || return;
    case $prev in
        -'?' | -h | --help | -V | --version | -c)
            return 0
        ;;
        -m)
            _python_modules "$1";
            return 0
        ;;
        -Q)
            COMPREPLY=($( compgen -W "old new warn warnall" -- "$cur" ));
            return 0
        ;;
        -W)
            COMPREPLY=($( compgen -W "ignore default all module once error"                 -- "$cur" ));
            return 0
        ;;
        !(?(*/)python*([0-9.])|-?))
            [[ $cword -lt 2 || ${words[cword-2]} != -@(Q|W) ]] && _filedir
        ;;
    esac;
    local i;
    for ((i=0; i < ${#words[@]}-1; i++ ))
    do
        if [[ ${words[i]} == -c ]]; then
            _filedir;
        fi;
    done;
    if [[ "$cur" != -* ]]; then
        _filedir 'py?([co])';
    else
        COMPREPLY=($( compgen -W '$( _parse_help "$1" -h )' -- "$cur" ));
    fi;
    return 0
}
</code>```

The completion function treats the -m flag the same wheather it shows up as argument to python or to the script, so it tries to complete with a list of module names.

One way around this would be to use an alias for the python3 command that does not trigger the completion, e.g:

$ alias py3=python3
```

<p>To make this persistent you can put it in your <code>~/.bashrc</code>. Then you can use</p>

<pre class="lang-none prettyprint-override"><code>$ py3 ./script.py -i ./some_folder/some_file -m ./[TAB]
</code>```

which will use filename completion.

Or rename the -m flag to something else.

Title: python3 argparse autocomplete fail

Body:
i find some strange thing when i use arparse in python3.

#!/usr/bin/env python3

import argparse

def create_parser():
    p = argparse.ArgumentParser(add_help=True)
    p.add_argument('-i', help='i parameter', required=True)
    p.add_argument('-m', help='m parameter', required=True)
    return p

if __name__ == '__main__':
    p = create_parser()
    n = p.parse_args()
    print(n)

when i try launch it with

python3 ./script.py -i ./some_folder/some_file -m ./

bash autocomplete work with '-i' parameter, but not work with '-m'. If i rename '-m' to '-me' for example, all works good.

In bash i try launch other commands with '-m' parameter, but it not work only with argparse. Where can there be a mistake here?

Body:
What happens here is that the autocompletion for the python3 comand kicks in:

$ complete | grep python
complete -F _python python2
complete -F _python python3
complete -F _python python

The function _python that handles it should look like this:

$ type _python
_python is a function
_python ()
{
    local cur prev words cword;
    _init_completion || return;
    case $prev in
        -'?' | -h | --help | -V | --version | -c)
            return 0
        ;;
        -m)
            _python_modules "$1";
            return 0
        ;;
        -Q)
            COMPREPLY=($( compgen -W "old new warn warnall" -- "$cur" ));
            return 0
        ;;
        -W)
            COMPREPLY=($( compgen -W "ignore default all module once error"                 -- "$cur" ));
            return 0
        ;;
        !(?(*/)python*([0-9.])|-?))
            [[ $cword -lt 2 || ${words[cword-2]} != -@(Q|W) ]] && _filedir
        ;;
    esac;
    local i;
    for ((i=0; i < ${#words[@]}-1; i++ ))
    do
        if [[ ${words[i]} == -c ]]; then
            _filedir;
        fi;
    done;
    if [[ "$cur" != -* ]]; then
        _filedir 'py?([co])';
    else
        COMPREPLY=($( compgen -W '$( _parse_help "$1" -h )' -- "$cur" ));
    fi;
    return 0
}

The completion function treats the -m flag the same wheather it shows up as argument to python or to the script, so it tries to complete with a list of module names.

One way around this would be to use an alias for the python3 command that does not trigger the completion, e.g:

$ alias py3=python3

To make this persistent you can put it in your ~/.bashrc. Then you can use

$ py3 ./script.py -i ./some_folder/some_file -m ./[TAB]

which will use filename completion.

Or rename the -m flag to something else.