问:
Need to add prefix to captured names, based on given lists
I have two arrays @Mister and @Mrs and need to add prefix based on the   values.

```<code>@Mister = qw(Parasuram Raghavan Srivatsan);
@Mrs = qw(Kalai Padmini Maha);

my $str = "I was invited the doctor Parasuram and Kalai and civil Engineer Raghavan and Padmini and finally Advocate Srivatsan and Maha";

#Mr. Parasuram Mr. Raghavan Mr. Srivatsan
if(grep ($_ eq $str), @Mister)
{ $str=~s/($_)/Mr. $1/g; }

#Mrs. Kalai Mrs. Padmini Mrs. Maha`
if(grep ($_ eq $str), @Mrs)
{ $str=~s/($_)/Mrs. $1/g; }
</code>```

Output Should be:

I was invited the doctor Mr. Parasuram and Mrs. Kalai and civil Engineer Mr. Raghavan and Mrs. Padmini and finally Advocate Mr. Srivatsan and Mrs. Maha

Could someone simplify the way I am doing and whats wrong in this code.

答:
@ssr1012 and other readers: Be careful! It's tempting to think there is a universal solution for this problem. But, unfortunately, even @zdim's approach will give undesirable results if the same name appears in both arrays, and it is still tricky if a name in one array is the same as a name in the other array except for a few additional characters at the start or end.
Here's your example using slightly different names:

```<code>my @Mister = qw(Parasuram Mahan Srivatsan);
my @Mrs = qw(Kalai Padmini Maha);
...

# I was invited the doctor Mr. Parasuram and Ms. Kalai and civil Engineer Mr. Ms. Mahan and Ms. Padmini and finally Advocate Mr. Srivatsan and Ms. Maha
</code>```

See the "Mr. Ms. Mahan"? You don't have enough information for a universal solution. This is only reliable if your names are hard-coded and checked first to avoid collisions.

Even if you added first names, you might not have enough information - guessing gender from first names is unreliable in many language cultures.

Body:
I have two arrays @Mister and @Mrs and need to add prefix based on the   values.

@Mister = qw(Parasuram Raghavan Srivatsan);
@Mrs = qw(Kalai Padmini Maha);

my $str = "I was invited the doctor Parasuram and Kalai and civil Engineer Raghavan and Padmini and finally Advocate Srivatsan and Maha";

#Mr. Parasuram Mr. Raghavan Mr. Srivatsan
if(grep ($_ eq $str), @Mister)
{ $str=~s/($_)/Mr. $1/g; }

#Mrs. Kalai Mrs. Padmini Mrs. Maha`
if(grep ($_ eq $str), @Mrs)
{ $str=~s/($_)/Mrs. $1/g; }

Output Should be:

I was invited the doctor Mr. Parasuram and Mrs. Kalai and civil Engineer Mr. Raghavan and Mrs. Padmini and finally Advocate Mr. Srivatsan and Mrs. Maha

Could someone simplify the way I am doing and whats wrong in this code.

Body:
@ssr1012 and other readers: Be careful! It's tempting to think there is a universal solution for this problem. But, unfortunately, even @zdim's approach will give undesirable results if the same name appears in both arrays, and it is still tricky if a name in one array is the same as a name in the other array except for a few additional characters at the start or end.
Here's your example using slightly different names:

my @Mister = qw(Parasuram Mahan Srivatsan);
my @Mrs = qw(Kalai Padmini Maha);
...

# I was invited the doctor Mr. Parasuram and Ms. Kalai and civil Engineer Mr. Ms. Mahan and Ms. Padmini and finally Advocate Mr. Srivatsan and Ms. Maha

See the "Mr. Ms. Mahan"? You don't have enough information for a universal solution. This is only reliable if your names are hard-coded and checked first to avoid collisions.

Even if you added first names, you might not have enough information - guessing gender from first names is unreliable in many language cultures.


来源: stackexchange

问:
python-driver pagination not working
I have below code to use cassandra python driver for pagination

I tried both overriding query and set session default_fetch_size. but none of them working, the results always all rows from the table. what am I missing?

```<code>from cassandra.cluster import Cluster
from cassandra.query import SimpleStatement

# setup
cluster = Cluster(["10.40.10.xxx","10.40.10.xxx","10.40.22.xxx","10.40.22.xxx"])
session = cluster.connect()
session.set_keyspace("ad_realtime")
# session.default_fetch_size = 10

query = "SELECT * from campaign_offset"
statement = SimpleStatement(query, fetch_size=10)
results = session.execute(statement)

for row in results:
   print row
</code>```

答:
You can get the rows of the current page by using current_rows, like:

```<code>for row in results.current_rows:
    print row
</code>```

ContentLicense: CC BY-SA 3.0

Title: python-driver pagination not working

Body:
I have below code to use cassandra python driver for pagination

I tried both overriding query and set session default_fetch_size. but none of them working, the results always all rows from the table. what am I missing?

from cassandra.cluster import Cluster
from cassandra.query import SimpleStatement

# setup
cluster = Cluster(["10.40.10.xxx","10.40.10.xxx","10.40.22.xxx","10.40.22.xxx"])
session = cluster.connect()
session.set_keyspace("ad_realtime")
# session.default_fetch_size = 10

query = "SELECT * from campaign_offset"
statement = SimpleStatement(query, fetch_size=10)
results = session.execute(statement)

for row in results:
   print row

Body:
You can get the rows of the current page by using current_rows, like:

for row in results.current_rows:
    print row


问:
Parsing a page that has to be logged into with jsoup - cant find authentication key?
Right now I'm trying to parse a page behind a login - specifically, my own transcript of grades that must be logged in to access through the university website.

I am following this tutorial - http://joelmin.blogspot.ca/2016/04/how-to-login-to-website-using-jsoup-java_4.html - but the author mentions finding an authentication key, as shown here:

What I wish I saw - note authentication field

However, when I follow the steps, the form data I see looks like this:

What I actually see - no authentication key field

I then tried to adapt the steps by searching for an "It" id and a "execution" id, as they seem to change with every login, but they dont exist.

This is the site I am attempting to automate login to: https://cas.id.ubc.ca/ubc-cas/login

Any help would be appreciated :) I apologize if I'm missing something obvious!

答:
Here is what you can try...

```<code>import org.jsoup.Connection;

Connection.Response res = null;
    try {
        res = Jsoup
                .connect("https://cas.id.ubc.ca/ubc-cas/login")
                .data("username", "your login id", "password", "your password")
                .method(Connection.Method.POST)
                .execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

Now save all your cookies and make request to the other page you want.

```<code>//Saving Cookies
cookies = res.cookies();
</code>```

Making request to another page.

```<code>try {
    Document doc = Jsoup.connect("your-second-page-link").cookies(cookies).get();
}
catch(Exception e){
    e.printStackTrace();
}
</code>```

Ask if further help needed.

Body:
Here is what you can try...

import org.jsoup.Connection;

Connection.Response res = null;
    try {
        res = Jsoup
                .connect("https://cas.id.ubc.ca/ubc-cas/login")
                .data("username", "your login id", "password", "your password")
                .method(Connection.Method.POST)
                .execute();
    } catch (IOException e) {
        e.printStackTrace();
    }

Now save all your cookies and make request to the other page you want.

//Saving Cookies
cookies = res.cookies();

Making request to another page.

try {
    Document doc = Jsoup.connect("your-second-page-link").cookies(cookies).get();
}
catch(Exception e){
    e.printStackTrace();
}

Ask if further help needed.


问:
Alter PHP Array
I'm need an array of all the folders in a directory, im using laravel to get an array of folders in the directory using the below code.

Storage::allDirectories('/public');

this returns an array like below.

```<code>$directories = [
    "Gallery",
    "Images",
    "Images/Proof",
    "Images/Proof/Another",
];
</code>```

I need a way to remove duplicate parent directories, so for example Images will be remove if Images/Proof/Another exists or something like that, i just need to build an array of a directory and its subfolders as one array, if that makes sense.

so for example:

```<code>$directories = [
    ["Gallery"],
    ["Images/Proof/Another"],
];
</code>```

Or something like this, I can't think of a way to get this to work.

I'm building a custom media manager component if anyone was wondering, some exist but i have no control over them so i built my own.

all help is appreciated.

Can you post the code you have tried so far

For 1 i can't get my head around the logic, thats why im asking what i've done "Which i dont see how it would help at all"

```<code>foreach (Storage::allDirectories('/public') as $folder)
{
    $all_folders[] = $exploded('/',$folder);
}
</code>```

Im trying to separate the array into smaller arrays and check each exploded bit against another. But this has me running in circles.

答:
Quick and dirty, but tested and works</p>

```<code>function removeRedundantParents($directories)
{
    foreach ($directories as $key => &$val)
    {
        foreach ($directories as $i => &$v)
        {

            if ($val !== $v && substr($v, 0, strlen($val)) == $val)
            {
                unset($directories[$key]);
                continue;
            }
        }
    }

    return $directories;
}
</code>```

Title: Alter PHP Array

Body:
I'm need an array of all the folders in a directory, im using laravel to get an array of folders in the directory using the below code.

Storage::allDirectories('/public');

this returns an array like below.

$directories = [
    "Gallery",
    "Images",
    "Images/Proof",
    "Images/Proof/Another",
];

I need a way to remove duplicate parent directories, so for example Images will be remove if Images/Proof/Another exists or something like that, i just need to build an array of a directory and its subfolders as one array, if that makes sense.

so for example:

$directories = [
    ["Gallery"],
    ["Images/Proof/Another"],
];

Or something like this, I can't think of a way to get this to work.

I'm building a custom media manager component if anyone was wondering, some exist but i have no control over them so i built my own.

all help is appreciated.

Can you post the code you have tried so far

For 1 i can't get my head around the logic, thats why im asking what i've done "Which i dont see how it would help at all"

foreach (Storage::allDirectories('/public') as $folder)
{
    $all_folders[] = $exploded('/',$folder);
}

Im trying to separate the array into smaller arrays and check each exploded bit against another. But this has me running in circles.

Body:
Quick and dirty, but tested and works

function removeRedundantParents($directories)
{
    foreach ($directories as $key => &$val)
    {
        foreach ($directories as $i => &$v)
        {

            if ($val !== $v && substr($v, 0, strlen($val)) == $val)
            {
                unset($directories[$key]);
                continue;
            }
        }
    }

    return $directories;
}


问:
How to migrate from version in Sonar from MySQL to PostgreSQL
I have a question about the migration of versions in Sonar, to see if you can solve it.

I have Sonar 5.2 with MySQL and I want to update to 6.1 and move to PostgreSQL. From what I've been reading, I think the best way is to perform the required update, create a Squema in the new Sonar and then import the database I had in the old Sonar ...

is this correct?

Greetings, Thank you very much

答:
It's possible but not that easy but it's doable.

You can find some details here : How to migrate SonarQube 6.7 from MySQL to postgresql


问:
Why is JSON replacing XML as a data format?
When I first saw XML, I thought it was basically a representation of trees.  Then I thought: the important thing isn't that it's a particularly good representation of trees, but that it is one that everyone agrees on.  Just like ASCII.  And once established, it's hard to displace due to network effects.  The new alternative would have to be much better (maybe 10 times better) to displace it. Of course, ASCII has been (mostly) replaced by Unicode, for internationalization.

According to google trends, XML has a x43 lead, but is declining - while JSON grows.

[edited] How and why will JSON replace XML as a data format?

for which tasks?

for which programmers/industries?

NOTES:
S-expressions (from lisp) are another representation of trees, but which has not gained mainstream adoption.  There are many, many other proposals, such as YAML and Protocol Buffers (for binary formats).

I can see JSON dominating the space of communicating with client-side AJAX (AJAJ?), and this possibly could back-spread into other systems transitively.

XML, being based on SGML, is better than JSON as a document format.  I'm interested in XML as a data format.

XML has an established ecosystem that JSON lacks, especially ways of defining formats (XML Schema) and transforming them (XSLT).  XML also has many other standards, esp for web services - but their weight and complexity can arguably count against XML, and make people want a fresh start (similar to "web services" beginning as a fresh start over CORBA).

[edited Mar2010] Like NoSQL, JSON is schemaless.

答:
My bold thesis is that such replacement is impossible after all, since these data-formats (JSON and XML) are different.

Short version: XML is not equivalent
to JSON (or similar) format since XML
nodes (tags) support attribute
notation and namespacing. It turns out
to be crucial.

So, the best way to answer this question is actually to show how these formats are different, i.e. to complete the comparison. Forgive me for stating the obvious but I only hope this will be interesting or even useful. It will help if we first agree with simple terminology that:

Data-format is actually a formal language, which governs how data can be recognized (in its representation, i.e. how to "read/write" it from memory according to the way it is stored there).

Data-structure is an abstract way of modeling (describing) how this data is organized or linked.

So, actually both concepts address different aspects of data maintenance (e.g. IO). For example, indexed array of a particular data-type is a (homogenues) structure and it can be accessed (read/written) as a serial sequence (contiguous format).

Wikipedia has a great article about JSON containing a lot of alternatives like (already named lisp's) S-Expressions, Python Nested Structures, PHP arrays, YAML, etc (note we are not considering dictionaries like .ini files since they lack multiple nesting). All these formats can be seen as representation of a certain data-structure - a tree. We can state that they are isomorphic in that sense. Each representation can be mapped to a tree in such manner that no extra processing should be done (e.g. grammar of a formal language is not changed). Also there exists a reverse mapping.

Well you may say that's "some" theory but what does it mean for practice? Implications are that if we compare XML and JSON by:

design purpose and motivation

application domain - set of task a format is used to solve

syntactical complexity (well, simplicity - to which extend format is more readable/writable/human friendly/etc)

maturity (like how many versions the format is around)

and so on

we will discover further practical differences. Major of them all is that XML is a MARKUP language (as been mentioned). Yes, to do folding it is able to mix namespaces and attributes which results in a higher-order of "parallel" nesting.

For the past two years I was busy transforming XML representation into python nested structures back and forth. To my only bitter conclusion they are very poorly compatible. To represent attributes and namespacing one should escape (e.g. with prefixes) this information in the tree representation. So once again XML is definitely not a tree ;-) it immediately (without the need to encode, encapsulate or escape) allows representation of much more sophisticated structures than trees due to "markup" capabilities, i.e. typed trees. Trees with specialized types of vertexes (again by namespaces and attributes).

There are other difficulties and dangers like parsing and mapping

```<code><body>The <strong>marked up</strong> text</body>
</code>```

into a tree without some pre-decided convention (How to break "The .. text"?) or preserving order followed in XML.

Obviously things which are not equivalent are naturally having trouble to substitute each other. In that sense XML is more complex than nested structures.

The part of the question regarding industries seems pretty well answered by a prognoses that XML will stay server-side and document-oriented technology. Mainly because of its superior data-typing abilities. Also there have been done a lot of research motivated by XML solely as a markup language.

Excuse me for being far off the topic further, discussing the popularity of JSON but it seems partially relevant ;)

I want to emphasize that JSON (being an object notation) completely fails to grasp any of the custom typing information (it enumerates the type without providing a "runtime"-reference or a context) by design (it is JavaScript), hence fails to pass highly-coupled objectified data. Type information will be always abstracted to JSON native types. This limits the abilities for type oriented development (type checking, constraining, casting, delegation, etc.). But IMHO this very crucial problem is shared with JSON by the most of modern programming languages (I know), which lack sophisticated nested custom data-typing as XML does (objects or functions are not documents). It seems that XML itself is doing this only by accident and not by design.

As the result while working with JSON one applies similar tactics as by processing "duck"- typed data in popular dynamical languages. So this is another characteristics for JSON - allows fast coding but risks to get bulky when is growing too big (nested and complex).

JSON is more of a swiss-knife than XML since it is simpler.

So, JSON does not help to interoperate with strongly-typed languages like Java but on the other hand it allows to lower the coupling by encouraging abstract decomposition. Since losing type information sometimes may be a good thing (reduction factor) it allows simpler architectures. ActionScript prefers to communicate de-facto in JSON (but they have also proposed own AMF). Finally, JSON works great with  KISS (e.g. RESTful) designs. JSON buys with speed and simplicity. But what one usually tends to ignore is when KISS is impossible and domain logic is too complicated - designing DTDs and XSDs, thinking formats through and so on - is the work that should be done by someone (often later on when cool KISS approach failed because of lack of designing competence and experience). The point is JSON is a great tool which lacks application scale.

ContentLicense: CC BY-SA 4.0

Body:
My bold thesis is that such replacement is impossible after all, since these data-formats (JSON and XML) are different.

Short version: XML is not equivalent
to JSON (or similar) format since XML
nodes (tags) support attribute
notation and namespacing. It turns out
to be crucial.

So, the best way to answer this question is actually to show how these formats are different, i.e. to complete the comparison. Forgive me for stating the obvious but I only hope this will be interesting or even useful. It will help if we first agree with simple terminology that:

Data-format is actually a formal language, which governs how data can be recognized (in its representation, i.e. how to "read/write" it from memory according to the way it is stored there).

Data-structure is an abstract way of modeling (describing) how this data is organized or linked.

So, actually both concepts address different aspects of data maintenance (e.g. IO). For example, indexed array of a particular data-type is a (homogenues) structure and it can be accessed (read/written) as a serial sequence (contiguous format).

Wikipedia has a great article about JSON containing a lot of alternatives like (already named lisp's) S-Expressions, Python Nested Structures, PHP arrays, YAML, etc (note we are not considering dictionaries like .ini files since they lack multiple nesting). All these formats can be seen as representation of a certain data-structure - a tree. We can state that they are isomorphic in that sense. Each representation can be mapped to a tree in such manner that no extra processing should be done (e.g. grammar of a formal language is not changed). Also there exists a reverse mapping.

Well you may say that's "some" theory but what does it mean for practice? Implications are that if we compare XML and JSON by:

design purpose and motivation

application domain - set of task a format is used to solve

syntactical complexity (well, simplicity - to which extend format is more readable/writable/human friendly/etc)

maturity (like how many versions the format is around)

and so on

we will discover further practical differences. Major of them all is that XML is a MARKUP language (as been mentioned). Yes, to do folding it is able to mix namespaces and attributes which results in a higher-order of "parallel" nesting.

For the past two years I was busy transforming XML representation into python nested structures back and forth. To my only bitter conclusion they are very poorly compatible. To represent attributes and namespacing one should escape (e.g. with prefixes) this information in the tree representation. So once again XML is definitely not a tree ;-) it immediately (without the need to encode, encapsulate or escape) allows representation of much more sophisticated structures than trees due to "markup" capabilities, i.e. typed trees. Trees with specialized types of vertexes (again by namespaces and attributes).

There are other difficulties and dangers like parsing and mapping

<body>The <strong>marked up</strong> text</body>

into a tree without some pre-decided convention (How to break "The .. text"?) or preserving order followed in XML.

Obviously things which are not equivalent are naturally having trouble to substitute each other. In that sense XML is more complex than nested structures.

The part of the question regarding industries seems pretty well answered by a prognoses that XML will stay server-side and document-oriented technology. Mainly because of its superior data-typing abilities. Also there have been done a lot of research motivated by XML solely as a markup language.

Excuse me for being far off the topic further, discussing the popularity of JSON but it seems partially relevant ;)

I want to emphasize that JSON (being an object notation) completely fails to grasp any of the custom typing information (it enumerates the type without providing a "runtime"-reference or a context) by design (it is JavaScript), hence fails to pass highly-coupled objectified data. Type information will be always abstracted to JSON native types. This limits the abilities for type oriented development (type checking, constraining, casting, delegation, etc.). But IMHO this very crucial problem is shared with JSON by the most of modern programming languages (I know), which lack sophisticated nested custom data-typing as XML does (objects or functions are not documents). It seems that XML itself is doing this only by accident and not by design.

As the result while working with JSON one applies similar tactics as by processing "duck"- typed data in popular dynamical languages. So this is another characteristics for JSON - allows fast coding but risks to get bulky when is growing too big (nested and complex).

JSON is more of a swiss-knife than XML since it is simpler.

So, JSON does not help to interoperate with strongly-typed languages like Java but on the other hand it allows to lower the coupling by encouraging abstract decomposition. Since losing type information sometimes may be a good thing (reduction factor) it allows simpler architectures. ActionScript prefers to communicate de-facto in JSON (but they have also proposed own AMF). Finally, JSON works great with  KISS (e.g. RESTful) designs. JSON buys with speed and simplicity. But what one usually tends to ignore is when KISS is impossible and domain logic is too complicated - designing DTDs and XSDs, thinking formats through and so on - is the work that should be done by someone (often later on when cool KISS approach failed because of lack of designing competence and experience). The point is JSON is a great tool which lacks application scale.


问:
Firebase firestore collection count with angularFire 2
I want to get the total number of the documents that exist in firestore.
I don't want to get the data only the total number of inside Products collection I have 200.000 items is that possible with Angular 4-5, not angular.js

Can someone expert tell me how I can achieve that ??

My code so far and is not work

```<code>  get_total_messages() {
    this.messages_collection = this.afs.collection<MessageEntity>('messages');
    return this.messages_collection.snapshotChanges();
  }
</code>```

End this is how I try to get the data but is not what I want;

```<code>this.firebase_Service.get_total_messages().subscribe( data => {
   console.log(data);
});
</code>```

答:
```<code>this.firebase_Service.get_total_messages().subscribe(data => this.totalnumber = data.length);
</code>```

Now you can get total number of messages

Body:
I want to get the total number of the documents that exist in firestore.
I don't want to get the data only the total number of inside Products collection I have 200.000 items is that possible with Angular 4-5, not angular.js

Can someone expert tell me how I can achieve that ??

My code so far and is not work

  get_total_messages() {
    this.messages_collection = this.afs.collection<MessageEntity>('messages');
    return this.messages_collection.snapshotChanges();
  }

End this is how I try to get the data but is not what I want;

this.firebase_Service.get_total_messages().subscribe( data => {
   console.log(data);
});

Body:
this.firebase_Service.get_total_messages().subscribe(data => this.totalnumber = data.length);

Now you can get total number of messages


问:
I want to get only count from the control file
I want to get only count from a control file. The control file's name is AA.dat (for example) and the data in the file will be as follows.

```<code>AA.dat  200
</code>```

From the above file I want to pick only the value 200. When I try to use the cut command I am not able to get the result.

答:
Simply with grep:

```<code>cnt=$(grep -o -m1 '[0-9]*$' AA.dat)
</code>```

[0-9]*$ - match any number of digits [0-9]* at the end of the line $

```<code>echo "$cnt"
200
</code>```

Body:
I want to get only count from a control file. The control file's name is AA.dat (for example) and the data in the file will be as follows.

AA.dat  200

From the above file I want to pick only the value 200. When I try to use the cut command I am not able to get the result.

Body:
Simply with grep:

cnt=$(grep -o -m1 '[0-9]*$' AA.dat)

[0-9]*$ - match any number of digits [0-9]* at the end of the line $

echo "$cnt"
200


问:
Clearing Javascript basics regarding variables

console.log(x);
x = 20;```

the value returned on the console is undefined.
I was expecting a value of 20 or a reference error.
Why is that so??

答: Because when your doing console.log(x);, it referring to global scope (window.x) and the value of x in global scope (window.x) is undefined. When you do x=20, you are setting the value of x after it is already displayed.

Body:
console.log(x);
x = 20;

the value returned on the console is undefined.
I was expecting a value of 20 or a reference error.
Why is that so??


问:
Build link (url) for calendar event
I want to build a url link from event, so I can use this url in my web app as a clickable link. After click on event I want to see opened event, where I can edit this event
I found this, but its not working correctly:

```<code>var calendarId = CalendarApp.getCalendarById(MYCAL).getId();

var splitEventId = event.getId().split('@');
var eventURL = "https://calendar.google.com/calendar/r/eventedit/" + Utilities.base64Encode(splitEventId[0] + " " + calendarId);
</code>```

Output (eventURL) is URL:

```<code>https://calendar.google.com/calendar/r/eventedit/MGtxajM4bjZnaDljdGZrczloNzdlZmFsM3IgbWFydGluLmJpZWxhazFAZ21haWwuY29t
</code>```

But original URL to event is :

```<code>https://calendar.google.com/calendar/r/eventedit/MGtxajM4bjZnaDljdGZrczloNzdlZmFsM3IgbWFydGluLmJpZWxhazFAbQ
</code>```

It is almost matching, but end of URL is different. I tried also without space between splitEventId and calendarId, but output was worst.
Does somebody know, why this is happening?
How can I build,get event URL?

Thanks.

答:
This link will help you: Google Calender v3

And the way to build this url is:

```<code>GET https://www.googleapis.com/calendar/v3/calendars/calendarId/events/eventId
</code>```

where calendarId & eventId are parametres.

Hope this is helpfull.

Title: Build link (url) for calendar event

Body:
I want to build a url link from event, so I can use this url in my web app as a clickable link. After click on event I want to see opened event, where I can edit this event
I found this, but its not working correctly:

var calendarId = CalendarApp.getCalendarById(MYCAL).getId();

var splitEventId = event.getId().split('@');
var eventURL = "https://calendar.google.com/calendar/r/eventedit/" + Utilities.base64Encode(splitEventId[0] + " " + calendarId);

Output (eventURL) is URL:

https://calendar.google.com/calendar/r/eventedit/MGtxajM4bjZnaDljdGZrczloNzdlZmFsM3IgbWFydGluLmJpZWxhazFAZ21haWwuY29t

But original URL to event is :

https://calendar.google.com/calendar/r/eventedit/MGtxajM4bjZnaDljdGZrczloNzdlZmFsM3IgbWFydGluLmJpZWxhazFAbQ

It is almost matching, but end of URL is different. I tried also without space between splitEventId and calendarId, but output was worst.
Does somebody know, why this is happening?
How can I build,get event URL?

Thanks.

Body:
This link will help you: Google Calender v3

And the way to build this url is:

GET https://www.googleapis.com/calendar/v3/calendars/calendarId/events/eventId

where calendarId & eventId are parametres.

Hope this is helpfull.


问:
visual tool for debugging recursive code
when debugging code which's called recursively many times, sometimes it gets difficult to realize  which execution of the code you are seeing. Is there any IDE graphic tool which helps to see that  with diagrams or something?</p>

答:
Now this is an very old and already answered topic but Visual Studio has the parallel debugging window which allows you to see the state of your variables. Callstack is typically very hard to track.

See more in Kaycee Anderson's MSDN blog

Here is a reference taken from the blog

ContentLicense: CC BY-SA 2.5


问:
Log in anonymously to firebase authentication and add onCompleteListener when user rotates his/her while the authentication is in progress?
I'm making random chat app where every 2 users are in 1 room. My app worked well if I don't rotate the device, but I just tried to rotate several times right after app is launched to make app robust. Then, the app crashed right away

how can I log in anonymously to firebase authentication and add onCompleteListener when user rotates his/her while the firebase authentication is in progress?

When I first launch the app, a dialog is showed up which is used to announce the user that the app is initializing something and during the dialog is showed in onCreateView of a fragment, app tries to log in to firebase authentication anonymously and set onCompleteListener because when authentication is completed,

I have to insert to firebase database '/user_state/{uid}/"home"' with uid and dismiss dialog to make user possible to push button which is used to find another user to chat where the uid is needed too.

Because the uid is needed in both jobs, I need to do these jobs right after the authentication is completed.

I just thought that I could implement inserting '/user_state/{uid}/"home"' by cloud functions for firebase, but I didn't know how I could know the time when I dismiss the initializing dialog that I showed before because I have to know when the authentication is completed and I need callback function. So I added onCompleteListener like this

```<code>FirebaseAuth.getInstance().signInAnonymously().addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInAnonymously:success");
                        mAuthInitDialog.dismiss();
                        mCurrentUser = mAuth.getCurrentUser();
                        UserState state = new UserState(STATE_HOME);
                        mFirebaseDatabase
                                .getReference("user_state/" + mCurrentUser.getUid())
                                .setValue(state);

                    } else {
                        Log.w(TAG, "signInAnonymously:failure", task.getException());
                        mAuthInitDialog.dismiss();
                        Toast.makeText(getActivity(), "Authentication Failed", Toast.LENGTH_SHORT).show();
                    }
                }
            });
</code>```

But when I rotate the device, the activity is destroyed and listener has gone for sure. So, I just thought that how about changing my code like below

```<code>Task mTask = FirebaseAuth.getInstance().signInAnonymously();
mTask.addOnCompleteListener( ...
</code>```

and I used onSaveInstanceState method and Gson to save my Task Object like below

```<code>bundle.putString(BUNDLE_TASK_AUTH, new Gson().toJson(mTaskAuth));
</code>```

and restored like below

```<code>if(savedInstanceState != null) {
    mTask =  new Gson().fromJson(savedInstanceState.getString(BUNDLE_TASK_AUTH), Task.class);
    mTask.setOnCompleteListener( ...
}
</code>```

But, I'm not sure if the listener could catch the authentication complete event even though the listener is retored after the fragment is recreated every time

Because I thought that authentication complete event can occur when after the activity is destroyed and before the activity is recreated.

I just want to make robust app even though there are several device rotations using firebase authentication. What should I do?

Code for MainFragment.java

```<code>public class MainFragment extends Fragment {
    private static final String TAG = "sgc109.MainFragment";
    private static final String DIALOG_PROGRESS = "DialogProgress";
    private static final String BUNDLE_IS_WAITING = "bundle_is_waiting";
    private static final String BUNDLE_TASK_AUTH = "bundle_task_auth";
    private static final String CMD_START_WAITING = "start_waiting";
    private static final String CMD_STOP_WAITING = "stop_waiting";
    private static final String CMD_EXIT = "exit";
    private static final String CMD_SEND = "send";
    private static final String STATE_HOME = "home";
    private static final String STATE_WAITING = "waiting";
    private static final String STATE_MATCHED = "matched";
    private static final String STATE_PENDING = "pending";

    private static final int REQUEST_CHAT_ROOM = 0;

    private boolean isWaiting;
    private boolean hasRequestedAuth;
    private Task mTaskAuth;
    private FirebaseAuth mAuth;
    private Button mEnterTheRoomButton;
    private ProgressDialog mProgressDialog;
    private ProgressDialog mAuthInitDialog;
    private FirebaseDatabase mFirebaseDatabase;
    private FirebaseUser mCurrentUser;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            Log.i(TAG, "retore savedInstanceState!");
            isWaiting = savedInstanceState.getBoolean(BUNDLE_IS_WAITING, false);
            mTaskAuth =  new Gson().fromJson(savedInstanceState.getString(BUNDLE_TASK_AUTH), Task.class);
        }

        if (isWaiting) {
            showProgressDialog();
        }

        View view = inflater.inflate(R.layout.fragment_main, container, false);

        mAuth = FirebaseAuth.getInstance();
        mCurrentUser = mAuth.getCurrentUser();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        if (mCurrentUser == null) {
            mAuthInitDialog = new ProgressDialog(getActivity());
            mAuthInitDialog.setTitle("첫 실행 초기화 중");
            mAuthInitDialog.setCanceledOnTouchOutside(false);
            mAuthInitDialog.setCancelable(false);
            mAuthInitDialog.show();

            if (mTaskAuth == null) {
                mTaskAuth = mAuth.signInAnonymously();
            }
            mTaskAuth.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInAnonymously:success");
                        mAuthInitDialog.dismiss();
                        mCurrentUser = mAuth.getCurrentUser();
                        UserState state = new UserState(STATE_HOME);
                        mFirebaseDatabase
                                .getReference("user_state/" + mCurrentUser.getUid())
                                .setValue(state);

                    } else {
                        Log.w(TAG, "signInAnonymously:failure", task.getException());
                        mAuthInitDialog.dismiss();
                        Toast.makeText(getActivity(), "Authentication Failed", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        else {
            mFirebaseDatabase
                    .getReference()
                    .child("user_state")
                    .child(mCurrentUser.getUid())
                    .addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            UserState state = dataSnapshot.getValue(UserState.class);
                            if (state.state.equals(STATE_MATCHED)) {
                                enterChatRoom();
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            Log.w(TAG, "onCancelled");
                        }
                    });
        }

        mEnterTheRoomButton = (Button) view.findViewById(R.id.activity_main_enter_the_room_button);
        mEnterTheRoomButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCurrentUser == null) {
                    return;
                }
                if (!isWaiting) {
                    startWaitingForOtherUser();
                    isWaiting = true;
                }
                showProgressDialog();
            }
        });

        return view;
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mProgressDialog != null) mProgressDialog.dismiss();
        if (mAuthInitDialog != null) mAuthInitDialog.dismiss();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.i(TAG, "onSavedInstaneState()");
        super.onSaveInstanceState(outState);
        outState.putBoolean(BUNDLE_IS_WAITING, isWaiting);
        outState.putString(BUNDLE_TASK_AUTH, new Gson().toJson(mTaskAuth));
    }

    public void showProgressDialog() {
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    isWaiting = false;
                    dialog.cancel();
                    stopWaitingForOtherUser();
                    return true;
                }
                return false;
            }
        });
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle(R.string.find_other_user_progress_dialog_text);
        mProgressDialog.show();
    }

    public void stopWaitingForOtherUser() {
        CommandSender.sendCommand(CMD_STOP_WAITING);
    }

    public void startWaitingForOtherUser() {
        CommandSender.sendCommand(CMD_START_WAITING);
    }

    public void enterChatRoom() {
        isWaiting = false;
        Intent intent = ChatRoomActivity.newIntent(getActivity());
        startActivityForResult(intent, REQUEST_CHAT_ROOM);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CHAT_ROOM:
                boolean reEnter = data.getBooleanExtra(ChatRoomActivity.EXTRA_RE_ENTER_ROOM, false);
                if (reEnter){
                    showProgressDialog();
                    startWaitingForOtherUser();
                }
            default:
                return;
        }
    }
}
</code>```

答:
I solved this by using ViewModel. I found from here that ViewModel holds our data even though Activity is destroyed because of configuration change such as device rotation.

My changed code is below.

MainFragment.java

```<code>public class MainFragment extends Fragment {
    private static final String TAG = "sgc109.MainFragment";
    private static final String DIALOG_PROGRESS = "DialogProgress";
    private static final String BUNDLE_IS_WAITING = "bundle_is_waiting";
    private static final String BUNDLE_IS_AUTH_COMPLETE = "bundle_is_auth_complete";
    private static final String CMD_START_WAITING = "start_waiting";
    private static final String CMD_STOP_WAITING = "stop_waiting";
    private static final String CMD_EXIT = "exit";
    private static final String CMD_SEND = "send";
    private static final String STATE_HOME = "home";
    private static final String STATE_WAITING = "waiting";
    private static final String STATE_MATCHED = "matched";
    private static final String STATE_PENDING = "pending";

    private static final int REQUEST_CHAT_ROOM = 0;

    private boolean mIsWaiting;
    private boolean mIsAuthComplete;
    private Button mEnterTheRoomButton;
    private ProgressDialog mProgressDialog;
    private ProgressDialog mAuthInitDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            Log.i(TAG, "retore savedInstanceState!");
            mIsWaiting = savedInstanceState.getBoolean(BUNDLE_IS_WAITING, false);
            mIsAuthComplete = savedInstanceState.getBoolean(BUNDLE_IS_AUTH_COMPLETE, false);
        }

        if (mIsWaiting) {
            showProgressDialog();
        }

        View view = inflater.inflate(R.layout.fragment_main, container, false);

        if (mIsAuthComplete) {
            showAuthInitDialog();
            MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
            model.getTask().addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    mAuthInitDialog.dismiss();
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInAnonymously:success");
                        mIsAuthComplete = true;
                        UserState state = new UserState(STATE_HOME);
                        FirebaseDatabase
                                .getInstance()
                                .getReference("user_state/" + FirebaseAuth.getInstance().getCurrentUser().getUid())
                                .setValue(state);

                    } else {
                        Log.w(TAG, "signInAnonymously:failure", task.getException());
                        getActivity().finish();
                    }
                }
            });
        } else {
            FirebaseDatabase
                    .getInstance()
                    .getReference()
                    .child("user_state")
                    .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                    .addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            UserState state = dataSnapshot.getValue(UserState.class);
                            if (state.state.equals(STATE_MATCHED)) {
                                enterChatRoom();
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            Log.w(TAG, "onCancelled");
                        }
                    });
        }

        mEnterTheRoomButton = (Button) view.findViewById(R.id.activity_main_enter_the_room_button);
        mEnterTheRoomButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (FirebaseAuth.getInstance().getCurrentUser() == null) {
                    Toast.makeText(getActivity(), "Shit Fuck!", Toast.LENGTH_SHORT).show();
                    return;
                }

                showProgressDialog();
                startWaitingForOtherUser();
                mIsWaiting = true;
            }
        });

        return view;
    }

    private void showAuthInitDialog() {
        mAuthInitDialog = new ProgressDialog(getActivity());
        mAuthInitDialog.setTitle("첫 실행 초기화 중");
        mAuthInitDialog.setCanceledOnTouchOutside(false);
        mAuthInitDialog.setCancelable(false);
        mAuthInitDialog.show();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mProgressDialog != null) mProgressDialog.dismiss();
        if (mAuthInitDialog != null) mAuthInitDialog.dismiss();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.i(TAG, "onSavedInstaneState()");
        super.onSaveInstanceState(outState);
        outState.putBoolean(BUNDLE_IS_WAITING, mIsWaiting);
        outState.putBoolean(BUNDLE_IS_AUTH_COMPLETE, mIsAuthComplete);
    }

    public void showProgressDialog() {
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    mIsWaiting = false;
                    dialog.cancel();
                    stopWaitingForOtherUser();
                    return true;
                }
                return false;
            }
        });
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle(R.string.find_other_user_progress_dialog_text);
        mProgressDialog.show();
    }

    public void stopWaitingForOtherUser() {
        CommandSender.sendCommand(CMD_STOP_WAITING);
    }

    public void startWaitingForOtherUser() {
        CommandSender.sendCommand(CMD_START_WAITING);
    }

    public void enterChatRoom() {
        mIsWaiting = false;
        Intent intent = ChatRoomActivity.newIntent(getActivity());
        startActivityForResult(intent, REQUEST_CHAT_ROOM);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CHAT_ROOM:
                boolean reEnter = data.getBooleanExtra(ChatRoomActivity.EXTRA_RE_ENTER_ROOM, false);
                if (reEnter) {
                    showProgressDialog();
                    startWaitingForOtherUser();
                }
            default:
                return;
        }
    }
}
</code>```

MyViewModel.java

```<code>public class MyViewModel extends ViewModel {
    private Task task;
    public Task getTask(){
        if (task == null){
            task = FirebaseAuth.getInstance().signInAnonymously();
        }
        return task;
    }
}
</code>```

Body:
I'm making random chat app where every 2 users are in 1 room. My app worked well if I don't rotate the device, but I just tried to rotate several times right after app is launched to make app robust. Then, the app crashed right away

how can I log in anonymously to firebase authentication and add onCompleteListener when user rotates his/her while the firebase authentication is in progress?

When I first launch the app, a dialog is showed up which is used to announce the user that the app is initializing something and during the dialog is showed in onCreateView of a fragment, app tries to log in to firebase authentication anonymously and set onCompleteListener because when authentication is completed,

I have to insert to firebase database '/user_state/{uid}/"home"' with uid and dismiss dialog to make user possible to push button which is used to find another user to chat where the uid is needed too.

Because the uid is needed in both jobs, I need to do these jobs right after the authentication is completed.

I just thought that I could implement inserting '/user_state/{uid}/"home"' by cloud functions for firebase, but I didn't know how I could know the time when I dismiss the initializing dialog that I showed before because I have to know when the authentication is completed and I need callback function. So I added onCompleteListener like this

FirebaseAuth.getInstance().signInAnonymously().addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInAnonymously:success");
                        mAuthInitDialog.dismiss();
                        mCurrentUser = mAuth.getCurrentUser();
                        UserState state = new UserState(STATE_HOME);
                        mFirebaseDatabase
                                .getReference("user_state/" + mCurrentUser.getUid())
                                .setValue(state);

                    } else {
                        Log.w(TAG, "signInAnonymously:failure", task.getException());
                        mAuthInitDialog.dismiss();
                        Toast.makeText(getActivity(), "Authentication Failed", Toast.LENGTH_SHORT).show();
                    }
                }
            });

But when I rotate the device, the activity is destroyed and listener has gone for sure. So, I just thought that how about changing my code like below

Task mTask = FirebaseAuth.getInstance().signInAnonymously();
mTask.addOnCompleteListener( ...

and I used onSaveInstanceState method and Gson to save my Task Object like below

bundle.putString(BUNDLE_TASK_AUTH, new Gson().toJson(mTaskAuth));

and restored like below

if(savedInstanceState != null) {
    mTask =  new Gson().fromJson(savedInstanceState.getString(BUNDLE_TASK_AUTH), Task.class);
    mTask.setOnCompleteListener( ...
}

But, I'm not sure if the listener could catch the authentication complete event even though the listener is retored after the fragment is recreated every time

Because I thought that authentication complete event can occur when after the activity is destroyed and before the activity is recreated.

I just want to make robust app even though there are several device rotations using firebase authentication. What should I do?

Code for MainFragment.java

public class MainFragment extends Fragment {
    private static final String TAG = "sgc109.MainFragment";
    private static final String DIALOG_PROGRESS = "DialogProgress";
    private static final String BUNDLE_IS_WAITING = "bundle_is_waiting";
    private static final String BUNDLE_TASK_AUTH = "bundle_task_auth";
    private static final String CMD_START_WAITING = "start_waiting";
    private static final String CMD_STOP_WAITING = "stop_waiting";
    private static final String CMD_EXIT = "exit";
    private static final String CMD_SEND = "send";
    private static final String STATE_HOME = "home";
    private static final String STATE_WAITING = "waiting";
    private static final String STATE_MATCHED = "matched";
    private static final String STATE_PENDING = "pending";

    private static final int REQUEST_CHAT_ROOM = 0;

    private boolean isWaiting;
    private boolean hasRequestedAuth;
    private Task mTaskAuth;
    private FirebaseAuth mAuth;
    private Button mEnterTheRoomButton;
    private ProgressDialog mProgressDialog;
    private ProgressDialog mAuthInitDialog;
    private FirebaseDatabase mFirebaseDatabase;
    private FirebaseUser mCurrentUser;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            Log.i(TAG, "retore savedInstanceState!");
            isWaiting = savedInstanceState.getBoolean(BUNDLE_IS_WAITING, false);
            mTaskAuth =  new Gson().fromJson(savedInstanceState.getString(BUNDLE_TASK_AUTH), Task.class);
        }

        if (isWaiting) {
            showProgressDialog();
        }

        View view = inflater.inflate(R.layout.fragment_main, container, false);

        mAuth = FirebaseAuth.getInstance();
        mCurrentUser = mAuth.getCurrentUser();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        if (mCurrentUser == null) {
            mAuthInitDialog = new ProgressDialog(getActivity());
            mAuthInitDialog.setTitle("첫 실행 초기화 중");
            mAuthInitDialog.setCanceledOnTouchOutside(false);
            mAuthInitDialog.setCancelable(false);
            mAuthInitDialog.show();

            if (mTaskAuth == null) {
                mTaskAuth = mAuth.signInAnonymously();
            }
            mTaskAuth.addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInAnonymously:success");
                        mAuthInitDialog.dismiss();
                        mCurrentUser = mAuth.getCurrentUser();
                        UserState state = new UserState(STATE_HOME);
                        mFirebaseDatabase
                                .getReference("user_state/" + mCurrentUser.getUid())
                                .setValue(state);

                    } else {
                        Log.w(TAG, "signInAnonymously:failure", task.getException());
                        mAuthInitDialog.dismiss();
                        Toast.makeText(getActivity(), "Authentication Failed", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        else {
            mFirebaseDatabase
                    .getReference()
                    .child("user_state")
                    .child(mCurrentUser.getUid())
                    .addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            UserState state = dataSnapshot.getValue(UserState.class);
                            if (state.state.equals(STATE_MATCHED)) {
                                enterChatRoom();
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            Log.w(TAG, "onCancelled");
                        }
                    });
        }

        mEnterTheRoomButton = (Button) view.findViewById(R.id.activity_main_enter_the_room_button);
        mEnterTheRoomButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCurrentUser == null) {
                    return;
                }
                if (!isWaiting) {
                    startWaitingForOtherUser();
                    isWaiting = true;
                }
                showProgressDialog();
            }
        });

        return view;
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mProgressDialog != null) mProgressDialog.dismiss();
        if (mAuthInitDialog != null) mAuthInitDialog.dismiss();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.i(TAG, "onSavedInstaneState()");
        super.onSaveInstanceState(outState);
        outState.putBoolean(BUNDLE_IS_WAITING, isWaiting);
        outState.putString(BUNDLE_TASK_AUTH, new Gson().toJson(mTaskAuth));
    }

    public void showProgressDialog() {
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    isWaiting = false;
                    dialog.cancel();
                    stopWaitingForOtherUser();
                    return true;
                }
                return false;
            }
        });
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle(R.string.find_other_user_progress_dialog_text);
        mProgressDialog.show();
    }

    public void stopWaitingForOtherUser() {
        CommandSender.sendCommand(CMD_STOP_WAITING);
    }

    public void startWaitingForOtherUser() {
        CommandSender.sendCommand(CMD_START_WAITING);
    }

    public void enterChatRoom() {
        isWaiting = false;
        Intent intent = ChatRoomActivity.newIntent(getActivity());
        startActivityForResult(intent, REQUEST_CHAT_ROOM);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CHAT_ROOM:
                boolean reEnter = data.getBooleanExtra(ChatRoomActivity.EXTRA_RE_ENTER_ROOM, false);
                if (reEnter){
                    showProgressDialog();
                    startWaitingForOtherUser();
                }
            default:
                return;
        }
    }
}

Body:
I solved this by using ViewModel. I found from here that ViewModel holds our data even though Activity is destroyed because of configuration change such as device rotation.

My changed code is below.

MainFragment.java

public class MainFragment extends Fragment {
    private static final String TAG = "sgc109.MainFragment";
    private static final String DIALOG_PROGRESS = "DialogProgress";
    private static final String BUNDLE_IS_WAITING = "bundle_is_waiting";
    private static final String BUNDLE_IS_AUTH_COMPLETE = "bundle_is_auth_complete";
    private static final String CMD_START_WAITING = "start_waiting";
    private static final String CMD_STOP_WAITING = "stop_waiting";
    private static final String CMD_EXIT = "exit";
    private static final String CMD_SEND = "send";
    private static final String STATE_HOME = "home";
    private static final String STATE_WAITING = "waiting";
    private static final String STATE_MATCHED = "matched";
    private static final String STATE_PENDING = "pending";

    private static final int REQUEST_CHAT_ROOM = 0;

    private boolean mIsWaiting;
    private boolean mIsAuthComplete;
    private Button mEnterTheRoomButton;
    private ProgressDialog mProgressDialog;
    private ProgressDialog mAuthInitDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            Log.i(TAG, "retore savedInstanceState!");
            mIsWaiting = savedInstanceState.getBoolean(BUNDLE_IS_WAITING, false);
            mIsAuthComplete = savedInstanceState.getBoolean(BUNDLE_IS_AUTH_COMPLETE, false);
        }

        if (mIsWaiting) {
            showProgressDialog();
        }

        View view = inflater.inflate(R.layout.fragment_main, container, false);

        if (mIsAuthComplete) {
            showAuthInitDialog();
            MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
            model.getTask().addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    mAuthInitDialog.dismiss();
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInAnonymously:success");
                        mIsAuthComplete = true;
                        UserState state = new UserState(STATE_HOME);
                        FirebaseDatabase
                                .getInstance()
                                .getReference("user_state/" + FirebaseAuth.getInstance().getCurrentUser().getUid())
                                .setValue(state);

                    } else {
                        Log.w(TAG, "signInAnonymously:failure", task.getException());
                        getActivity().finish();
                    }
                }
            });
        } else {
            FirebaseDatabase
                    .getInstance()
                    .getReference()
                    .child("user_state")
                    .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                    .addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            UserState state = dataSnapshot.getValue(UserState.class);
                            if (state.state.equals(STATE_MATCHED)) {
                                enterChatRoom();
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            Log.w(TAG, "onCancelled");
                        }
                    });
        }

        mEnterTheRoomButton = (Button) view.findViewById(R.id.activity_main_enter_the_room_button);
        mEnterTheRoomButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (FirebaseAuth.getInstance().getCurrentUser() == null) {
                    Toast.makeText(getActivity(), "Shit Fuck!", Toast.LENGTH_SHORT).show();
                    return;
                }

                showProgressDialog();
                startWaitingForOtherUser();
                mIsWaiting = true;
            }
        });

        return view;
    }

    private void showAuthInitDialog() {
        mAuthInitDialog = new ProgressDialog(getActivity());
        mAuthInitDialog.setTitle("첫 실행 초기화 중");
        mAuthInitDialog.setCanceledOnTouchOutside(false);
        mAuthInitDialog.setCancelable(false);
        mAuthInitDialog.show();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mProgressDialog != null) mProgressDialog.dismiss();
        if (mAuthInitDialog != null) mAuthInitDialog.dismiss();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.i(TAG, "onSavedInstaneState()");
        super.onSaveInstanceState(outState);
        outState.putBoolean(BUNDLE_IS_WAITING, mIsWaiting);
        outState.putBoolean(BUNDLE_IS_AUTH_COMPLETE, mIsAuthComplete);
    }

    public void showProgressDialog() {
        mProgressDialog = new ProgressDialog(getActivity());
        mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    mIsWaiting = false;
                    dialog.cancel();
                    stopWaitingForOtherUser();
                    return true;
                }
                return false;
            }
        });
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle(R.string.find_other_user_progress_dialog_text);
        mProgressDialog.show();
    }

    public void stopWaitingForOtherUser() {
        CommandSender.sendCommand(CMD_STOP_WAITING);
    }

    public void startWaitingForOtherUser() {
        CommandSender.sendCommand(CMD_START_WAITING);
    }

    public void enterChatRoom() {
        mIsWaiting = false;
        Intent intent = ChatRoomActivity.newIntent(getActivity());
        startActivityForResult(intent, REQUEST_CHAT_ROOM);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CHAT_ROOM:
                boolean reEnter = data.getBooleanExtra(ChatRoomActivity.EXTRA_RE_ENTER_ROOM, false);
                if (reEnter) {
                    showProgressDialog();
                    startWaitingForOtherUser();
                }
            default:
                return;
        }
    }
}

MyViewModel.java

public class MyViewModel extends ViewModel {
    private Task task;
    public Task getTask(){
        if (task == null){
            task = FirebaseAuth.getInstance().signInAnonymously();
        }
        return task;
    }
}


问:
Audiokit MIDI initialisation is confusing
CoreMIDI terminology is already super confusing and badly documented, and Audiokit isn't helping as much as I wished it might.

As far as I can tell, each application is supposed to have one instance of a midi client reference (MIDIClientRef). Audiokit has the AKMIDI class that creates a new client reference for each AKMIDI instance, and instances are being created left, right and center (including the initialization of each AKMIDIInstrument, AKCallbackInstrument and AKMIDISampler instance). All of these also create endpoints with hardcoded names in their built-in constructors so I don't see how I'm supposed to make ones that have proper names.

The top price goes to AKMIDISampler, whose source first says:

```<code>/// Initialize the MIDI Sampler
public override init() {
    super.init()
    enableMIDI()
}
</code>```

And then on the following few lines:

```<code>/// Enable MIDI input from a given MIDI client
/// This is not in the init function because it must be called AFTER you start AudioKit
///
/// [snipped parameter comments for brevity]
open func enableMIDI(_ midiClient: MIDIClientRef = AKMIDI().client, name: String = "MIDI Sampler")
</code>```

(Note that it IS in the init function)

I would be super happy to either hear some clarification about general usage guidelines (do I need to override everything?) or links to documentation/articles explaining this in more detail.

答:
We just fixed that issue with #1141 PR.
https://github.com/AudioKit/AudioKit/pull/1141/files

You can point to the develop branch on your podfile until the next release.

```<code>pod 'AudioKit', :git => 'https://github.com/AudioKit/AudioKit.git', :branch => 'develop'
</code>```

Body:
CoreMIDI terminology is already super confusing and badly documented, and Audiokit isn't helping as much as I wished it might.

As far as I can tell, each application is supposed to have one instance of a midi client reference (MIDIClientRef). Audiokit has the AKMIDI class that creates a new client reference for each AKMIDI instance, and instances are being created left, right and center (including the initialization of each AKMIDIInstrument, AKCallbackInstrument and AKMIDISampler instance). All of these also create endpoints with hardcoded names in their built-in constructors so I don't see how I'm supposed to make ones that have proper names.

The top price goes to AKMIDISampler, whose source first says:

/// Initialize the MIDI Sampler
public override init() {
    super.init()
    enableMIDI()
}

And then on the following few lines:

/// Enable MIDI input from a given MIDI client
/// This is not in the init function because it must be called AFTER you start AudioKit
///
/// [snipped parameter comments for brevity]
open func enableMIDI(_ midiClient: MIDIClientRef = AKMIDI().client, name: String = "MIDI Sampler")

(Note that it IS in the init function)

I would be super happy to either hear some clarification about general usage guidelines (do I need to override everything?) or links to documentation/articles explaining this in more detail.

Body:
We just fixed that issue with #1141 PR.
https://github.com/AudioKit/AudioKit/pull/1141/files

You can point to the develop branch on your podfile until the next release.

pod 'AudioKit', :git => 'https://github.com/AudioKit/AudioKit.git', :branch => 'develop'


问:
AdjustPan analog in IOS and get/lost focus for UITextField
I use VS with Xamarin (not Xamarin.Forms).
Right now it looks like

Is there anything like Android AdjustPan in IOs.

And second question - how to get/lost focus of UITextField programmatically?

答:
Is there anything like Android AdjustPan in IOs.

You can use third-party tool to manage your keyboard position.

For example : IQKeyboardManager , you could add it via NuGet here.

And second question - how to get/lost focus of UITextField programmatically?

Get focus:

```<code>textfield.BecomeFirstResponder();
</code>```

Lost focus:

```<code>textfield.ResignFirstResponder();
</code>```

Body:
Is there anything like Android AdjustPan in IOs.

You can use third-party tool to manage your keyboard position.

For example : IQKeyboardManager , you could add it via NuGet here.

And second question - how to get/lost focus of UITextField programmatically?

Get focus:

textfield.BecomeFirstResponder();

Lost focus:

textfield.ResignFirstResponder();


问:
Rails - Method that returns true or false
I'm working to create a method that returns true or false, but it's return neither, what am I doing wrong?

In the controller:

```<code>valid_email_domain(email.to_s)

protected
  def valid_email_domain(emailAddy)
    reg = Regexp.new /#{User::INVALID_EMAILS.map{|a| Regexp.quote(a)}.join("|")}/
    Rails.logger.info 'REGEX TIME'
    Rails.logger.info emailAddy.scan(reg).size
    if emailAddy.scan(reg).size == 0
      return true
    else
      return false
    end
  end
</code>```

valid_email_domain isn't return anything. What's the issue? Thanks

答:
Try this:

```<code>def valid_email_domain?(emailAddy)
   reg = Regexp.new /#{User::INVALID_EMAILS.map{|a| Regexp.quote(a)}.join("|")}/
   Rails.logger.info 'REGEX TIME'
   Rails.logger.info emailAddy.scan(reg).size
   emailAddy.scan(reg).size == 0
end
</code>```

As a side point, a common method naming convention in Ruby is to use a trailing ? for methods that return a boolean.

Body:
I'm working to create a method that returns true or false, but it's return neither, what am I doing wrong?

In the controller:

valid_email_domain(email.to_s)

protected
  def valid_email_domain(emailAddy)
    reg = Regexp.new /#{User::INVALID_EMAILS.map{|a| Regexp.quote(a)}.join("|")}/
    Rails.logger.info 'REGEX TIME'
    Rails.logger.info emailAddy.scan(reg).size
    if emailAddy.scan(reg).size == 0
      return true
    else
      return false
    end
  end

valid_email_domain isn't return anything. What's the issue? Thanks

Body:
Try this:

def valid_email_domain?(emailAddy)
   reg = Regexp.new /#{User::INVALID_EMAILS.map{|a| Regexp.quote(a)}.join("|")}/
   Rails.logger.info 'REGEX TIME'
   Rails.logger.info emailAddy.scan(reg).size
   emailAddy.scan(reg).size == 0
end

As a side point, a common method naming convention in Ruby is to use a trailing ? for methods that return a boolean.


问:
Undefined method for <variable>_cont in spree - Ruby on Rails
I am trying to do a search in the spree backend in reviews listing page.
But am getting undefined method error for the fields. Eg: undefined method title_cont' , undefined methodreview _cont'.

Hereby am posting my controller:

reviews_controller.rb

```<code>class Spree::Admin::ReviewsController < Spree::Admin::ResourceController
      helper Spree::ReviewsHelper

     def index
     @reviews = Spree::Review.ransack(params[:q]).result
     end

      def approve
      r = Spree::Review.find(params[:id])

      if r.update_attribute(:approved, true)
      flash[:notice] = Spree.t("info_approve_review")
      else
      flash[:error] = Spree.t("error_approve_review")
      end
      redirect_to admin_reviews_path
      end

      def edit
      if @review.product.nil?
      flash[:error] = Spree.t("error_no_product")
      redirect_to admin_reviews_path and return
      end
      end

      private

      def collection
      params[:q] ||= {}
      @search = Spree::Review.ransack(params[:q])
      @collection = @search.result.includes([:product, :user, :feedback_reviews]).page(params[:page]).per(params[:per_page])
      end
      end
</code>```

Model File : review.rb

```<code>class Spree::Review < ActiveRecord::Base

      belongs_to :product, touch: true
      belongs_to :user, :class_name => Spree.user_class.to_s
      has_many   :feedback_reviews

      after_save :recalculate_product_rating, :if => :approved?
      after_destroy :recalculate_product_rating

      validates :name, presence: true
      validates :review, presence: true

      validates :rating, numericality: { only_integer: true,
      greater_than_or_equal_to: 1,
      less_than_or_equal_to: 5,
      message: Spree.t('you_must_enter_value_for_rating') }

      default_scope { order("spree_reviews.created_at DESC") }

      scope :localized, ->(lc) { where('spree_reviews.locale = ?', lc) }
      scope :most_recent_first, -> { order('spree_reviews.created_at DESC') }
      scope :oldest_first, -> { reorder('spree_reviews.created_at ASC') }
      scope :preview, -> { limit(Spree::Reviews::Config[:preview_size]).oldest_first }
      scope :approved, -> { where(approved: true) }
      scope :not_approved, -> { where(approved: false) }
      scope :default_approval_filter, -> { Spree::Reviews::Config[:include_unapproved_reviews] ? all : approved }

      def feedback_stars
      return 0 if feedback_reviews.size <= 0
      ((feedback_reviews.sum(:rating) / feedback_reviews.size) + 0.5).floor
      end

      def set_search
      @search=Product.search(params[:q])
      end

      def recalculate_product_rating
      self.product.recalculate_rating if product.present?
      end
      end
</code>```

Index.html.erb

```<code><% content_for :table_filter do %>
<div data-hook="admin_reviews_index_search">
 <%= search_form_for [:admin, @search] do |f| %>
 <div class="alpha three columns">
    <div class="field">
    <%= label_tag nil, Spree.t(:user) %><br />
    <%= f.text_field :name_cont,:size => 25 %>
    </div>
</div>
<div class="four columns">
    <div class="field">
        <%= label_tag nil, Spree.t(:title) -%><br/>
        <%= f.text_field :title_cont, :size => 25%>
    </div>
</div>
<div class="four columns">
    <div class="field">
        <%= label_tag nil, Spree.t(:review) -%><br/>
        <%= f.text_field :review_cont, :size => 25 ,:value => ""%>
    </div>
</div>
<div class="two columns omega">

</div>

    <div class="clear"></div>

    <div class="form-buttons actions filter-actions" data-hook="admin_reviews_index_search_buttons">
        <%= button Spree.t(:search), 'icon-search' %>
    </div>
<%- end -%>
</code>```

Getting undefined when i use the above mentioned variables. Please help me to solve this.

答:
Issue has been solved!

Defined the ransackable_attributes method in associated model Review.rb for custom searchable attributes of that model.

```<code>def self.ransackable_attributes(auth_object = nil)
    ['title','review','user']
end
</code>```

Body:
I am trying to do a search in the spree backend in reviews listing page.
But am getting undefined method error for the fields. Eg: undefined method title_cont' , undefined methodreview _cont'.

Hereby am posting my controller:

reviews_controller.rb

class Spree::Admin::ReviewsController < Spree::Admin::ResourceController
      helper Spree::ReviewsHelper

     def index
     @reviews = Spree::Review.ransack(params[:q]).result
     end

      def approve
      r = Spree::Review.find(params[:id])

      if r.update_attribute(:approved, true)
      flash[:notice] = Spree.t("info_approve_review")
      else
      flash[:error] = Spree.t("error_approve_review")
      end
      redirect_to admin_reviews_path
      end

      def edit
      if @review.product.nil?
      flash[:error] = Spree.t("error_no_product")
      redirect_to admin_reviews_path and return
      end
      end

      private

      def collection
      params[:q] ||= {}
      @search = Spree::Review.ransack(params[:q])
      @collection = @search.result.includes([:product, :user, :feedback_reviews]).page(params[:page]).per(params[:per_page])
      end
      end

Model File : review.rb

class Spree::Review < ActiveRecord::Base

      belongs_to :product, touch: true
      belongs_to :user, :class_name => Spree.user_class.to_s
      has_many   :feedback_reviews

      after_save :recalculate_product_rating, :if => :approved?
      after_destroy :recalculate_product_rating

      validates :name, presence: true
      validates :review, presence: true

      validates :rating, numericality: { only_integer: true,
      greater_than_or_equal_to: 1,
      less_than_or_equal_to: 5,
      message: Spree.t('you_must_enter_value_for_rating') }

      default_scope { order("spree_reviews.created_at DESC") }

      scope :localized, ->(lc) { where('spree_reviews.locale = ?', lc) }
      scope :most_recent_first, -> { order('spree_reviews.created_at DESC') }
      scope :oldest_first, -> { reorder('spree_reviews.created_at ASC') }
      scope :preview, -> { limit(Spree::Reviews::Config[:preview_size]).oldest_first }
      scope :approved, -> { where(approved: true) }
      scope :not_approved, -> { where(approved: false) }
      scope :default_approval_filter, -> { Spree::Reviews::Config[:include_unapproved_reviews] ? all : approved }

      def feedback_stars
      return 0 if feedback_reviews.size <= 0
      ((feedback_reviews.sum(:rating) / feedback_reviews.size) + 0.5).floor
      end

      def set_search
      @search=Product.search(params[:q])
      end

      def recalculate_product_rating
      self.product.recalculate_rating if product.present?
      end
      end

Index.html.erb

<% content_for :table_filter do %>

 <%= search_form_for [:admin, @search] do |f| %>

    <%= label_tag nil, Spree.t(:user) %>

    <%= f.text_field :name_cont,:size => 25 %>

        <%= label_tag nil, Spree.t(:title) -%>

        <%= f.text_field :title_cont, :size => 25%>

        <%= label_tag nil, Spree.t(:review) -%>

        <%= f.text_field :review_cont, :size => 25 ,:value => ""%>

        <%= button Spree.t(:search), 'icon-search' %>

<%- end -%>

Getting undefined when i use the above mentioned variables. Please help me to solve this.

Body:
Issue has been solved!

Defined the ransackable_attributes method in associated model Review.rb for custom searchable attributes of that model.

def self.ransackable_attributes(auth_object = nil)
    ['title','review','user']
end


答:
Your code returns error - Uncaught ReferenceError: x is not defined not undefined.

So think of x = 20; as var x = 20; which prints undefined in console.

In JavaScript if you do not declare a variable before using it then the declaration happens first with default value undefined. Then happens the initialization for that variable.

Consider this code with var:

```<code>console.log(x);
var x = 20;
</code>```

Actually interpreted by JavaScript Engine as:

```<code>var x;
x = undefined;
console.log(x);
x = 20;
</code>```

Title: Clearing Javascript basics regarding variables

Body:
Your code returns error - Uncaught ReferenceError: x is not defined not undefined.

So think of x = 20; as var x = 20; which prints undefined in console.

In JavaScript if you do not declare a variable before using it then the declaration happens first with default value undefined. Then happens the initialization for that variable.

Consider this code with var:

console.log(x);
var x = 20;

Actually interpreted by JavaScript Engine as:

var x;
x = undefined;
console.log(x);
x = 20;


问:
How to get index and the range of a div element from a group of divs using jQuery
If I have a group of tokenized divs like the following.

```<code><script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<div> Barrack </div>
<div> Obama </div>
<div> was </div>
<div> the </div>
<div> president </div>
<div> of </div>
<div> the </div>
<div> United </div>
<div> States </div>
<div> from </div>
<div> the </div>
<div> year </div>
<div> 2012 </div>
<div> to </div>
<div> 2016 </div>
<div> . </div>

<button id="btnClick"> Click me </button>

<script>
$(function(){

$('#btnClick').click(function(){
var selection = window.getSelection();
alert(selection);
});

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

I have tried the above

1) I want to get the index of divs when I click on multiple divs on mouse click event.
Example is if I click on div which contains Barrack and 2012, I am not able to get the selected div's index.

2) If I select the div which contains both Barrack and Obama
I want the range of the div, something like:
startIndex -> 0 and length -> 2.
Where startIndex = "Barrack" is the 0th div and it ranges 2 divs Barrack and Obama.

答:
Here you go

```<code><div class="findIndex">
  <div> the </div>
  <div> United </div>
  <div> States </div>
  <div> from </div>
  <div> the </div>
  <div> year </div>
  <div> 2012 </div>
  <div> to </div>
  <div> 2016 </div>
  <div> . </div>
</div>
<button id="btnClick"> Click me </button>

var indexRange = [];
$(".findIndex div").on("click",function(){
  if(indexRange.length == 0){
      indexRange[0] = $(this).index();
  }else{
    indexRange[1] = $(this).index();
  }
})

$("#btnClick").on("click",function(){
    if(indexRange.length == 2){
        alert("Start Index:" + indexRange[0] + "\n" + "End Index:" + indexRange[1] + "\n" + "Length:" + ((indexRange[1] - indexRange[0]) + 1));
    }else{
        alert("Please select start and end first.");
    }
    indexRange = Array();
})
</code>```

Here is the fiddle :
https://jsfiddle.net/vsmdcc3L/

Body:
If I have a group of tokenized divs like the following.

 Barrack

 Obama

 was

 the

 president

 of

 the

 United

 States

 from

 the

 year

 2012

 to

 2016

 .

<button id="btnClick"> Click me </button>

I have tried the above

1) I want to get the index of divs when I click on multiple divs on mouse click event.
Example is if I click on div which contains Barrack and 2012, I am not able to get the selected div's index.

2) If I select the div which contains both Barrack and Obama
I want the range of the div, something like:
startIndex -> 0 and length -> 2.
Where startIndex = "Barrack" is the 0th div and it ranges 2 divs Barrack and Obama.

Body:
Here you go

<div class="findIndex">
  <div> the </div>
  <div> United </div>
  <div> States </div>
  <div> from </div>
  <div> the </div>
  <div> year </div>
  <div> 2012 </div>
  <div> to </div>
  <div> 2016 </div>
  <div> . </div>
</div>
<button id="btnClick"> Click me </button>

var indexRange = [];
$(".findIndex div").on("click",function(){
  if(indexRange.length == 0){
      indexRange[0] = $(this).index();
  }else{
    indexRange[1] = $(this).index();
  }
})

$("#btnClick").on("click",function(){
    if(indexRange.length == 2){
        alert("Start Index:" + indexRange[0] + "\n" + "End Index:" + indexRange[1] + "\n" + "Length:" + ((indexRange[1] - indexRange[0]) + 1));
    }else{
        alert("Please select start and end first.");
    }
    indexRange = Array();
})

Here is the fiddle :
https://jsfiddle.net/vsmdcc3L/


问:
How can I stop execution of an outer function within a callback
Lets imagine I have a scenario like this:

```<code>async function some_func() {
  await some_query.catch(async (e) => {
    await some_error_code()
  })

  console.log('The above function ran without an error')
}
</code>```

I only wish for the console.log() to be reached if the asynchronous function ran successfully.  At the moment, my solution is:

```<code>async function some_func() {
  let did_error = false
  await some_query.catch(async (e) => {
    await some_error_code()
    did_error = true
  })

  if (did_error) return

  console.log('The above function ran without an error')
}
</code>```

But that's not great.  Is there any way of handling this without the added bulk?  Similar to multiple for loops:

```<code>outer: for (let i = 0; i < 10; i++) {
  for (let j = 0; j < 10; j++) {
    continue outer;
  }
  console.log('Never called')
}
</code>```

答:
Turns out there is a better way, you can use the return value within the catch function:

```<code>async function some_func() {
  let response = await some_query.catch(async (e) => {
    await some_error_code()
    return { err: 'some_error_code' }
  })

  if (response.err) return

  console.log('The above function ran without an error')
}
</code>```

However this still isn't great, not sure if there's a better answer.

Body:
Lets imagine I have a scenario like this:

async function some_func() {
  await some_query.catch(async (e) => {
    await some_error_code()
  })

  console.log('The above function ran without an error')
}

I only wish for the console.log() to be reached if the asynchronous function ran successfully.  At the moment, my solution is:

async function some_func() {
  let did_error = false
  await some_query.catch(async (e) => {
    await some_error_code()
    did_error = true
  })

  if (did_error) return

  console.log('The above function ran without an error')
}

But that's not great.  Is there any way of handling this without the added bulk?  Similar to multiple for loops:

outer: for (let i = 0; i < 10; i++) {
  for (let j = 0; j < 10; j++) {
    continue outer;
  }
  console.log('Never called')
}

Body:
Turns out there is a better way, you can use the return value within the catch function:

async function some_func() {
  let response = await some_query.catch(async (e) => {
    await some_error_code()
    return { err: 'some_error_code' }
  })

  if (response.err) return

  console.log('The above function ran without an error')
}

However this still isn't great, not sure if there's a better answer.


问:
kernel mode version of OpenProcess
Is there a kernel mode version of OpenProcess function?

Basically I want to get a process HANDLE from process ID.
Specifically, I want to get the HANDLE of System Process ID.

Thanks!

答:
If you are in an arbitrary system thread you can use ZwCurrentProcess(), otherwise you will need to figure out the ID of a system thread somehow and use ZwOpenProcess.

You might also look to see if there is a way to convert the result of PsInitialSystemProcess to a  process handle (or maybe PsInitialSystemProcess is what you are really after).

Title: kernel mode version of OpenProcess


问:
Calculations based on Region and Cluster query SQL
I've table like this:

```<code>Cluster | Region | Value | Volume
---------------------------------
 West   |   AA   |  7500 |   2
 West   |   AB   |  9000 |   1
 West   |   AC   |  2200 |   2
 West   |   AC   |  7200 |   3
</code>```

Get sum of value and volume based on cluster, become value 25900 and volume 8. Get sum of value and volume based on region, become value (7500,9000,9400) and volume (2,1,5). Then value and volume based on region divided by value and volume based on cluster. Data should be like this:

```<code>Region | Growth Value | Growth Volume
-------------------------------------
  AA   |     29,0     |      25
  AB   |     34,7     |     12,5
  AC   |     36,3     |     62,5
</code>```

SQL Fiddle: http://sqlfiddle.com/#!15/5a908/27

答:
Basically if you need 1 direct query, see below. im not sure what is the data after comma 29,0 . You may modify from this to what you want after comma

```<code>    select cals."Region",
ROUND(100.0 * r."Value" / c."Value",1) as "Growth Value",
ROUND(100.0 * r."Volume" / c."Volume",1) as "Growth Volume"
    from cals
    inner join
    (select "Cluster",
    SUM("Value") as "Value",
    SUM("Volume") as "Volume"
    from cals
    group by "Cluster") as c
    on c."Cluster" = cals."Cluster"
    inner join
    (select "Region",
    SUM("Value") as "Value",
    SUM("Volume") as "Volume"
    from cals
    group by "Region") as r
    on r."Region" = cals."Region"
    group by cals."Region",r."Value",c."Value",c."Volume",r."Volume"
</code>```

result

Body:
I've table like this:

Cluster | Region | Value | Volume
---------------------------------
 West   |   AA   |  7500 |   2
 West   |   AB   |  9000 |   1
 West   |   AC   |  2200 |   2
 West   |   AC   |  7200 |   3

Get sum of value and volume based on cluster, become value 25900 and volume 8. Get sum of value and volume based on region, become value (7500,9000,9400) and volume (2,1,5). Then value and volume based on region divided by value and volume based on cluster. Data should be like this:

Region | Growth Value | Growth Volume
-------------------------------------
  AA   |     29,0     |      25
  AB   |     34,7     |     12,5
  AC   |     36,3     |     62,5

SQL Fiddle: http://sqlfiddle.com/#!15/5a908/27

Body:
Basically if you need 1 direct query, see below. im not sure what is the data after comma 29,0 . You may modify from this to what you want after comma

    select cals."Region",
ROUND(100.0 * r."Value" / c."Value",1) as "Growth Value",
ROUND(100.0 * r."Volume" / c."Volume",1) as "Growth Volume"
    from cals
    inner join
    (select "Cluster",
    SUM("Value") as "Value",
    SUM("Volume") as "Volume"
    from cals
    group by "Cluster") as c
    on c."Cluster" = cals."Cluster"
    inner join
    (select "Region",
    SUM("Value") as "Value",
    SUM("Volume") as "Volume"
    from cals
    group by "Region") as r
    on r."Region" = cals."Region"
    group by cals."Region",r."Value",c."Value",c."Volume",r."Volume"

result


答:
It works as

Is there and variable/functions used take it at the top and  variable assigned as undefined

so x= undefined; at the top, and you got result as undefined in second line and then you changed x=20 at last.

```<code>console.log(x);
x=20;
</code>```

Body:
console.log(x);
x = 20;

the value returned on the console is undefined.
I was expecting a value of 20 or a reference error.
Why is that so??

Body:
It works as

Is there and variable/functions used take it at the top and  variable assigned as undefined

so x= undefined; at the top, and you got result as undefined in second line and then you changed x=20 at last.

console.log(x);
x=20;


问:
How to get width of absolute positioned element in Angular
I'm trying to get the width off a component but it is 0. I've also tried putting the code in ngOnChanges().

```<code>constructor(private element: ElementRef) {
  this.htmlElement = this.element.nativeElement;
  let width = this.htmlElement.offsetWidth;
}
</code>```

Element style:

```<code>display: block;
position: absolute;
left: 100;
</code>```

I tried using clientWidth() but it is 0 too. How can I get the width of an element in angular 2?

Update:

I don't use position absolute and the width is correct, so I suppose the question is how do I get the width of an absolute positioned element?

答:
Try to move your code to AfterViewInit lifecycle hook method and use @ViewChild() decorator instead of injecting element directly in constructor.

Try this code:

```<code>import {Component, ElementRef, ViewChild, HTMLElement, AfterViewInit} from '@angular/core'

@Component({
  selector: 'my-app',
  template: `
    <div #child>
      <h2>Hello!</h2>
    </div>
  `,
})
export class App implements AfterViewInit {
  @ViewChild('child') element: any;
  htmlElement: HTMLElement;

  constructor() {}

  ngAfterViewInit() {
    this.htmlElement = this.element.nativeElement;
    let width = this.element.nativeElement.offsetWidth;
  }
}
</code>```

Or see the working example here. Also check comments for explanations.

Body:
I'm trying to get the width off a component but it is 0. I've also tried putting the code in ngOnChanges().

constructor(private element: ElementRef) {
  this.htmlElement = this.element.nativeElement;
  let width = this.htmlElement.offsetWidth;
}

Element style:

display: block;
position: absolute;
left: 100;

I tried using clientWidth() but it is 0 too. How can I get the width of an element in angular 2?

Update:

I don't use position absolute and the width is correct, so I suppose the question is how do I get the width of an absolute positioned element?

Body:
Try to move your code to AfterViewInit lifecycle hook method and use @ViewChild() decorator instead of injecting element directly in constructor.

Try this code:

import {Component, ElementRef, ViewChild, HTMLElement, AfterViewInit} from '@angular/core'

@Component({
  selector: 'my-app',
  template: `
    <div #child>
      <h2>Hello!</h2>
    </div>
  `,
})
export class App implements AfterViewInit {
  @ViewChild('child') element: any;
  htmlElement: HTMLElement;

  constructor() {}

  ngAfterViewInit() {
    this.htmlElement = this.element.nativeElement;
    let width = this.element.nativeElement.offsetWidth;
  }
}

Or see the working example here. Also check comments for explanations.


问:
How to concatenate columns on top of each other in an array
Say I have the following array:

```<code>a = np.array([[1,3,5,2,3],[3,2,5,6,7],[1,7,3,6,5]]);
</code>```

How can I stack the columns on top of each other to form a single column vector to produce the following?

```<code>b =np.array([[1], [3], [1], [3], [2], [7],[5],[5],[3],[2],[6],[6],[3],[7],[5]]);
</code>```

答:
You can use 'F' for Fortran order together with ravel or reshape:

```<code>a.ravel('F')[:, None]
# array([[1],
#        [3],
#        [1],
#        [3],
#        [2],
# ...
</code>```

Body:
Say I have the following array:

a = np.array([[1,3,5,2,3],[3,2,5,6,7],[1,7,3,6,5]]);

How can I stack the columns on top of each other to form a single column vector to produce the following?

b =np.array([[1], [3], [1], [3], [2], [7],[5],[5],[3],[2],[6],[6],[3],[7],[5]]);

Body:
You can use 'F' for Fortran order together with ravel or reshape:

a.ravel('F')[:, None]
# array([[1],
#        [3],
#        [1],
#        [3],
#        [2],
# ...


问:
What's the correct way to determine when a MapView's Lat/Lon window has changed?
I'm developing an Android application that uses a MapView.  I'd like to run a procedure whenever the visible portion of the map changes (due to zooming/panning/rotating the phone/etc), and I'd like to pass the new latitude and longitude values to the procedure.

I thought I could override onInterceptTouchEvent to do this, but then the procedure only seems to run when you first touch the screen (so, for example, panning by dragging your finger only calls the procedure at the beginning of the dragging motion).  Which means the procedure is never called with the new coordinates.

So -- what's the correct way to do it?

答:
You probably have to combine several techniques to achieve what you want.

To catch the panning, I'd try overriding your MapViews onTouchEvent(), or maybe dispatchTouchEvent(), and listen for the MotionEvent.ACTION_UP event. This is triggered when the user lifts his finger from the screen:

```<code>public boolean onTouchEvent(MotionEvent event) {
  if (event.getAction()==MotionEvent.ACTION_UP) {
    // Call your procedure here
  }

  return super.onTouchEvent(ev);
}
</code>```

If you wanted to call your procedure during the panning, I think you'd have to look for the panning motion overriding one of the two same methods. Something like this:

```<code>public boolean onTouchEvent(MotionEvent event) {
  if (event.getAction() == MotionEvent.ACTION_MOVE) {
    if (event.getHistorySize() < 1)
      return; // First call, no history

    // Get difference in position since previous move event
    float diffX = event.getX() - event.getHistoricalX(event.getHistorySize() - 1);
    float diffY = event.getY() - event.getHistoricalY(event.getHistorySize() - 1);

    if (Math.abs(diffX) > 0.5f || Math.abs(diffY) > 0.5f) {
      /* Position has changed substantially, so this is probably a drag action.
         Call your procedure here. */
    }
  }
}
</code>```

To detect a change in zoom level you can override dispatchDraw:

```<code>int oldZoomLevel=-1;

public void dispatchDraw(Canvas canvas) {
  super.dispatchDraw(canvas);

  if (getZoomLevel() != oldZoomLevel) {
    // Call your procedure here

    oldZoomLevel = getZoomLevel();
  }
}
</code>```

Body:
You probably have to combine several techniques to achieve what you want.

To catch the panning, I'd try overriding your MapViews onTouchEvent(), or maybe dispatchTouchEvent(), and listen for the MotionEvent.ACTION_UP event. This is triggered when the user lifts his finger from the screen:

public boolean onTouchEvent(MotionEvent event) {
  if (event.getAction()==MotionEvent.ACTION_UP) {
    // Call your procedure here
  }

  return super.onTouchEvent(ev);
}

If you wanted to call your procedure during the panning, I think you'd have to look for the panning motion overriding one of the two same methods. Something like this:

public boolean onTouchEvent(MotionEvent event) {
  if (event.getAction() == MotionEvent.ACTION_MOVE) {
    if (event.getHistorySize() < 1)
      return; // First call, no history

    // Get difference in position since previous move event
    float diffX = event.getX() - event.getHistoricalX(event.getHistorySize() - 1);
    float diffY = event.getY() - event.getHistoricalY(event.getHistorySize() - 1);

    if (Math.abs(diffX) > 0.5f || Math.abs(diffY) > 0.5f) {
      /* Position has changed substantially, so this is probably a drag action.
         Call your procedure here. */
    }
  }
}

To detect a change in zoom level you can override dispatchDraw:

int oldZoomLevel=-1;

public void dispatchDraw(Canvas canvas) {
  super.dispatchDraw(canvas);

  if (getZoomLevel() != oldZoomLevel) {
    // Call your procedure here

    oldZoomLevel = getZoomLevel();
  }
}