问:
R Conditional evaluation when using the pipe operator %>%
When using the pipe operator %>% with packages such as dplyr, ggvis, dycharts, etc, how do I do a step conditionally? For example;

```<code>step_1 %>%
step_2 %>%

if(condition)
step_3
</code>```

These approaches don't seem to work:

```<code>step_1 %>%
step_2
if(condition) %>% step_3

step_1 %>%
step_2 %>%
if(condition) step_3
</code>```

There is a long way:

```<code>if(condition)
{
step_1 %>%
step_2
}else{
step_1 %>%
step_2 %>%
step_3
}
</code>```

Is there a better way without all the redundancy?

答:
Edit: purrr::when() is deprecated as of {purrr} version 1.0.0

I think that's a case for purrr::when(). Let's sum up a few numbers if their sum is below 25, otherwise return 0.

library("magrittr")
1:3 %>%
  purrr::when(sum(.) < 25 ~ sum(.), ~0)
#> [1] 6
```

when returns the value resulting from the action of the first valid condition.  Put the condition to the left of ~, and the action to the right of it. Above, we only used one condition (and then an else case), but you can have many conditions.

You can easily integrate that into a longer pipe.

Body:
When using the pipe operator %>% with packages such as dplyr, ggvis, dycharts, etc, how do I do a step conditionally? For example;

step_1 %>%
step_2 %>%

if(condition)
step_3

These approaches don't seem to work:

step_1 %>%
step_2
if(condition) %>% step_3

step_1 %>%
step_2 %>%
if(condition) step_3

There is a long way:

if(condition)
{
step_1 %>%
step_2
}else{
step_1 %>%
step_2 %>%
step_3
}

Is there a better way without all the redundancy?

Body:
Edit: purrr::when() is deprecated as of {purrr} version 1.0.0

I think that's a case for purrr::when(). Let's sum up a few numbers if their sum is below 25, otherwise return 0.

library("magrittr")
1:3 %>%
  purrr::when(sum(.) < 25 ~ sum(.), ~0)
#> [1] 6

when returns the value resulting from the action of the first valid condition.  Put the condition to the left of ~, and the action to the right of it. Above, we only used one condition (and then an else case), but you can have many conditions.

You can easily integrate that into a longer pipe.


来源: stackexchange

问:
Angular2-moment, format minutes to
These are minutes : 1956

I want to format these minutes to : HH:mm

I'm using angular2-moment.

I've tried : 1956 | amDuration:'minutes' | amDateFormat: 'HH:mm'

But I get "Invalid date"

What do i have to do to make it work ?

答:
```<code>moment.duration(1956, "minutes").format("h [hrs], m [min]");
// "32 hrs, 36 min"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Angular2-moment, format minutes to

ContentLicense: CC BY-SA 4.0


问:
User defined command
I am having a situation for which I am looking for some suggestion.

Suppose I write a program which prints the directory names of the directories.
Is it possible to convert this program into a command (just on my system).
Not be alias but via C only.

答:
As long as the file is executable (has the exec x access for the user starting it) and can be seen from the command interpreter (usually bash or sh), you can consider it to be a command.

There will be no difference in running your own file from your path than the ls command for instance.

Also, the C (or C++ ...) language is not a requirement. There are plenty of commands in, for instance, /usr/bin that are a script, meaning they're sh or bash (or even perl)...

access Ensure the file has the x access right (e.g. chmod u+x file)

path Ensure the file is in your PATH, or add an entry in your path (for instance) with PATH=$PATH:mypath

test Test it well before to put it in a path from which other users may have access

ContentLicense: CC BY-SA 2.5

Title: User defined command


问:
Get started with Latex on Linux
Impressed by is-latex-worth-learning-today, and many how-to's on Windows,

How do you have someone started with LaTeX on Linux?

How do you generate a pdf out of it and give up the OOO Word processer?

Update:

Thanks to all the suggestions given in here. I was able to create an awesome ppt using the Beamer class: http://github.com/becomingGuru/gids-django-ppt. I found this approach too far better than using powerpoint and the like.

Those interested may checkout the TEX file, with many custom commands and the corresponding presentation.

答:
I would personally use a complete editing package such as:

TexWorks

TexStudio

Then I would install "MikTeX" as the compiling package, which allows you to generate a PDF from your document, using the pdfLaTeX compiler.

Title: Get started with Latex on Linux


问:
HttpAccessTokenRefreshError at ... unauthorized_client: Client is unauthorized to retrieve access tokens using this method
I have set up a service account for my google calendar api project. The idea is that my web site can connect to my google calendar and display events, etc. As it was put by google

```<code>Service account clients are created when domain-wide delegation is
enabled on a service account.
</code>```

Which indeed happened and so I have a connecting OAuth 2.0 client ID. So far so good. I generated a json file that I used to connect and try to authenticate using this code

```<code>from cal.models import Cal as Caldb
import httplib2

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client import tools

from calendar import monthrange
from calendar_gui import MyCalendar
from datetime import datetime
from datetime import date
from django.utils.safestring import mark_safe

from oauth2client.service_account import ServiceAccountCredentials
import os
from django.conf import settings

def authenticate():
    scope= ['https://www.googleapis.com/auth/calendar']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(os.path.join(settings.PROJECT_ROOT, '../', 'myjson.json'), scopes=scope)
    delegated_credentials = credentials.create_delegated('email@email.com')

    http = httplib2.Http()
    http = delegated_credentials.authorize(http)
    service = build(serviceName='calendar', version='v3', http=http, credentials=credentials)

    return service
</code>```

But alas

```<code>service = build(serviceName='calendar', version='v3', http=http, credentials=credentials)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 137, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 214, in build
cache)
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 261, in _retrieve_discovery_doc
resp, content = http.request(actual_url)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/transport.py", line 153, in new_request
credentials._refresh(orig_request_method)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 765, in _refresh
self._do_refresh_request(http_request)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 834, in _do_refresh_request
  raise HttpAccessTokenRefreshError(error_msg, status=resp.status)
HttpAccessTokenRefreshError: unauthorized_client: Client is unauthorized to retrieve access tokens using this method.
</code>```

I have enabled the google calendar api. In fact, I feel like I've followed all of the steps. In fact, I've done this once before with complete success, but I'm perplexed now. I read that maybe I need to wait 24-48 hours before this all takes effect. Could it be as simple as that?

For right now, I'm just testing this locally. Nothing pushed to the server yet.

答:
Check this link out:
Google API Python unauthorized_client: Unauthorized client or scope in request

You need to use the client ID from your "Developer Console" as the Client Name in the "Manage API Client Access" when setting your API scopes.

Body:
I have set up a service account for my google calendar api project. The idea is that my web site can connect to my google calendar and display events, etc. As it was put by google

Service account clients are created when domain-wide delegation is
enabled on a service account.

Which indeed happened and so I have a connecting OAuth 2.0 client ID. So far so good. I generated a json file that I used to connect and try to authenticate using this code

from cal.models import Cal as Caldb
import httplib2

from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client import tools

from calendar import monthrange
from calendar_gui import MyCalendar
from datetime import datetime
from datetime import date
from django.utils.safestring import mark_safe

from oauth2client.service_account import ServiceAccountCredentials
import os
from django.conf import settings

def authenticate():
    scope= ['https://www.googleapis.com/auth/calendar']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(os.path.join(settings.PROJECT_ROOT, '../', 'myjson.json'), scopes=scope)
    delegated_credentials = credentials.create_delegated('email@email.com')

    http = httplib2.Http()
    http = delegated_credentials.authorize(http)
    service = build(serviceName='calendar', version='v3', http=http, credentials=credentials)

    return service

But alas

service = build(serviceName='calendar', version='v3', http=http, credentials=credentials)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 137, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 214, in build
cache)
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/discovery.py", line 261, in _retrieve_discovery_doc
resp, content = http.request(actual_url)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/transport.py", line 153, in new_request
credentials._refresh(orig_request_method)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 765, in _refresh
self._do_refresh_request(http_request)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/client.py", line 834, in _do_refresh_request
  raise HttpAccessTokenRefreshError(error_msg, status=resp.status)
HttpAccessTokenRefreshError: unauthorized_client: Client is unauthorized to retrieve access tokens using this method.

I have enabled the google calendar api. In fact, I feel like I've followed all of the steps. In fact, I've done this once before with complete success, but I'm perplexed now. I read that maybe I need to wait 24-48 hours before this all takes effect. Could it be as simple as that?

For right now, I'm just testing this locally. Nothing pushed to the server yet.


问:
.htaccess to secure admin directory in mvc architecture
I am trying to make a site with mvc structure. I have this :

www/

blog/

app/

admin/

controller/

model/

view/

config/

front/

controller/

model/

view/

assets/

images/

libs/

portfolio /

I have a first .htaccess at the root (www/) for Gzip compression and stuff.
I have a second .htaccess for my blog (in www/blog/) with my very basic redirection system :

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
#QSA permet de garder les paramètres GET et les ajouter à la suite
RewriteRule (.*) index.php?p=$1 [QSA]
</code>```

The file index.php in www/blog/ parses the url and uses the right controllers like this :

```<code>//****************************************************

include_once(APP_f.controller/controller.class.php');
$controlF = new ControleurF();

include_once(APP_b.'controleur/controleur.class.php');
$controlB = new ControleurB();

if (isset($_GET['p'])&&(substr($_GET['p'],0,4)== 'admin')) {
//on est dans l'admin
    $lapage=explode('/',$_GET['p']);
    if (!empty($lapage[1])) {$pp = $lapage[1];} else {$pp="index";}

    if (!isset($pp) OR $pp == 'index')
    {
        $ctrl = "home"; $p = $ctrl;
    } else {
        $params = explode('/',$pp);
        $ctrl = $params[0]; $p = $ctrl;
        if (isset($params[1])) {
            if ($params[1]<>"") {$p = $params[1];}
        }
    }

    $c=$controlB->load($ctrl);
    include_once($c);

}else{
//on est en front
    if (!isset($_GET['p']) OR $_GET['p'] == 'index')
    {
        $ctrl = "home"; $p = $ctrl;
    } else {
        $params = explode('/',$_GET['p']);
        $ctrl = $params[0]; $p = $ctrl;
        if (isset($params[1])) {
            if ($params[1]<>"") {$p = $params[1];}
        }
    }

    $c=$controlF->load($ctrl);
    include_once($c);
}

//****************************************************
</code>```

Everything works fine but i am having trouble understanding how i could secure my admin folder with .htaccess/.htpasswd
Is there a way to do something like that in www/blog/.htaccess :

```<code><Directory admin>
AuthUserFile "/home/foobar/www/blog/.htpasswd"
AuthGroupFile /dev/null
AuthName "Admin"
AuthType Basic
Require valid-user
</Directory>
</code>```

答:
The Directory directive can only be used in server configuration or virtual host files. It cannot be used in htaccess files. It is described in Apache Directory Directive.

To password protect a directory using htaccess, you have to enter the following in .htaccess file:

```<code>AuthType Basic
AuthName "Restricted Files"
# (Following line optional)
AuthBasicProvider file
AuthUserFile "/usr/local/apache/passwd/passwords"
Require user rbowen
</code>```

The above commands will password protect the folder containing the htaccess file. The command: htpasswd -c /usr/local/apache/passwd/passwords rbowen generates a password for the user rbowen. It is described in Apache Authentication and Authorization

Body:
I am trying to make a site with mvc structure. I have this :

www/

blog/

app/

admin/

controller/

model/

view/

config/

front/

controller/

model/

view/

assets/

images/

libs/

portfolio /

I have a first .htaccess at the root (www/) for Gzip compression and stuff.
I have a second .htaccess for my blog (in www/blog/) with my very basic redirection system :

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
#QSA permet de garder les paramètres GET et les ajouter à la suite
RewriteRule (.*) index.php?p=$1 [QSA]

The file index.php in www/blog/ parses the url and uses the right controllers like this :

//****************************************************

include_once(APP_f.controller/controller.class.php');
$controlF = new ControleurF();

include_once(APP_b.'controleur/controleur.class.php');
$controlB = new ControleurB();

if (isset($_GET['p'])&&(substr($_GET['p'],0,4)== 'admin')) {
//on est dans l'admin
    $lapage=explode('/',$_GET['p']);
    if (!empty($lapage[1])) {$pp = $lapage[1];} else {$pp="index";}

    if (!isset($pp) OR $pp == 'index')
    {
        $ctrl = "home"; $p = $ctrl;
    } else {
        $params = explode('/',$pp);
        $ctrl = $params[0]; $p = $ctrl;
        if (isset($params[1])) {
            if ($params[1]<>"") {$p = $params[1];}
        }
    }

    $c=$controlB->load($ctrl);
    include_once($c);

}else{
//on est en front
    if (!isset($_GET['p']) OR $_GET['p'] == 'index')
    {
        $ctrl = "home"; $p = $ctrl;
    } else {
        $params = explode('/',$_GET['p']);
        $ctrl = $params[0]; $p = $ctrl;
        if (isset($params[1])) {
            if ($params[1]<>"") {$p = $params[1];}
        }
    }

    $c=$controlF->load($ctrl);
    include_once($c);
}

//****************************************************

Everything works fine but i am having trouble understanding how i could secure my admin folder with .htaccess/.htpasswd
Is there a way to do something like that in www/blog/.htaccess :

<Directory admin>
AuthUserFile "/home/foobar/www/blog/.htpasswd"
AuthGroupFile /dev/null
AuthName "Admin"
AuthType Basic
Require valid-user
</Directory>

Body:
The Directory directive can only be used in server configuration or virtual host files. It cannot be used in htaccess files. It is described in Apache Directory Directive.

To password protect a directory using htaccess, you have to enter the following in .htaccess file:

AuthType Basic
AuthName "Restricted Files"
# (Following line optional)
AuthBasicProvider file
AuthUserFile "/usr/local/apache/passwd/passwords"
Require user rbowen

The above commands will password protect the folder containing the htaccess file. The command: htpasswd -c /usr/local/apache/passwd/passwords rbowen generates a password for the user rbowen. It is described in Apache Authentication and Authorization


问:
Navigation in center
I do not want the navigation menu to be left-aligned but centered with space over the entire width. How do I do that? I use "Blogger".
Thank you for your answers!
Best regards,
Tini

答:
Go to Theme > Customize > Advanced > Add CSS

Add this css code :

```<code>#PageList1 ul {
    text-align: center;
}
#PageList1 ul li {
    float: none;
    display: inline-block;
    margin-left: -4px;
}
.tabs-inner .widget li a {
    border: 0;
}
</code>```

Then Press Apply to Blog

Title: Navigation in center

Body:
Go to Theme > Customize > Advanced > Add CSS

Add this css code :

#PageList1 ul {
    text-align: center;
}
#PageList1 ul li {
    float: none;
    display: inline-block;
    margin-left: -4px;
}
.tabs-inner .widget li a {
    border: 0;
}

Then Press Apply to Blog


问:
How to make HTML input tag only accept numerical values?
I need to make sure that a certain <input> field only takes numbers as value.
The input is not part of a form. Hence it doesn't get submitted, so validating during submission is not an option. I want the user to be unable to type in any characters other than numbers.

Is there a neat way to achieve this?

答:
It's better to add "+" to REGEX condition in order to accept multiple digits (not only one digit):

<input type="text" name="your_field" pattern="[0-9]+">


问:
Historical / auditable database
This question is related to the schema that can be found in one of my other questions here.  Basically in my database I store users, locations, sensors amongst other things.  All of these things are editable in the system by users, and deletable.

However - when an item is edited or deleted I need to store the old data; I need to be able to see what the data was before the change.

There are also non-editable items in the database, such as "readings".  They are more of a log really.  Readings are logged against sensors, because its the reading for a particular sensor.

If I generate a report of readings, I need to be able to see what the attributes for a location or sensor was at the time of the reading.

Basically I should be able to reconstruct the data for any point in time.

Now, I've done this before and got it working well by adding the following columns to each editable table:

```<code>valid_from
valid_to
edited_by
</code>```

If valid_to = 9999-12-31 23:59:59 then that's the current record.  If valid_to equals valid_from, then the record is deleted.

However, I was never happy with the triggers I needed to use to enforce foreign key consistency.

I can possibly avoid triggers by using the extension to the "PostgreSQL" database.  This provides a column type called "period" which allows you to store a period of time between two dates, and then allows you to do CHECK constraints to prevent overlapping periods.  That might be an answer.

I am wondering though if there is another way.

I've seen people mention using special historical tables, but I don't really like the thought of maintainling 2 tables for almost every 1 table (though it still might be a possibility).

Maybe I could cut down my initial implementation to not bother checking the consistency of records that aren't "current" - i.e. only bother to check constraints on records where the valid_to is 9999-12-31 23:59:59.  Afterall, the people who use historical tables do not seem to have constraint checks on those tables (for the same reason, you'd need triggers).

Does anyone have any thoughts about this?

PS - the title also mentions auditable database.  In the previous system I mentioned, there is always the edited_by field.  This allowed all changes to be tracked so we could always see who changed a record.  Not sure how much difference that might make.

Thanks.

答:
Depending on your budget and/or environment you might want to consider using Oracle's flashback archive feature.

You can turn on automatic "archiving" of rows in a table, and then run a statement on the basetable using something like

```SELECT *
FROM important_data
AS OF TIMESTAMP (SYSTIMESTAMP - INTERVAL '5' DAY)
```

Oracle takes care of maintaining the history in a separate (shadow) table. You can do this for any table so that you can also do a query with a join.

Title: Historical / auditable database

Body:
This question is related to the schema that can be found in one of my other questions here.  Basically in my database I store users, locations, sensors amongst other things.  All of these things are editable in the system by users, and deletable.

However - when an item is edited or deleted I need to store the old data; I need to be able to see what the data was before the change.

There are also non-editable items in the database, such as "readings".  They are more of a log really.  Readings are logged against sensors, because its the reading for a particular sensor.

If I generate a report of readings, I need to be able to see what the attributes for a location or sensor was at the time of the reading.

Basically I should be able to reconstruct the data for any point in time.

Now, I've done this before and got it working well by adding the following columns to each editable table:

valid_from
valid_to
edited_by

If valid_to = 9999-12-31 23:59:59 then that's the current record.  If valid_to equals valid_from, then the record is deleted.

However, I was never happy with the triggers I needed to use to enforce foreign key consistency.

I can possibly avoid triggers by using the extension to the "PostgreSQL" database.  This provides a column type called "period" which allows you to store a period of time between two dates, and then allows you to do CHECK constraints to prevent overlapping periods.  That might be an answer.

I am wondering though if there is another way.

I've seen people mention using special historical tables, but I don't really like the thought of maintainling 2 tables for almost every 1 table (though it still might be a possibility).

Maybe I could cut down my initial implementation to not bother checking the consistency of records that aren't "current" - i.e. only bother to check constraints on records where the valid_to is 9999-12-31 23:59:59.  Afterall, the people who use historical tables do not seem to have constraint checks on those tables (for the same reason, you'd need triggers).

Does anyone have any thoughts about this?

PS - the title also mentions auditable database.  In the previous system I mentioned, there is always the edited_by field.  This allowed all changes to be tracked so we could always see who changed a record.  Not sure how much difference that might make.

Thanks.

Body:
Depending on your budget and/or environment you might want to consider using Oracle's flashback archive feature.

You can turn on automatic "archiving" of rows in a table, and then run a statement on the basetable using something like

SELECT *
FROM important_data
AS OF TIMESTAMP (SYSTIMESTAMP - INTERVAL '5' DAY)

Oracle takes care of maintaining the history in a separate (shadow) table. You can do this for any table so that you can also do a query with a join.


问:
Vue.js 2 page and element transitions with vue-router
I'm trying to achieve a simple page enter and leave transition (Vue-CLI). On the leave transition i'd like to animate some elements out before vue-router moves to the next component. But the <router-link> don't wait for the animation to be finished.

My attempt:

App.vue: <router-view> wrapped in <transition ... > handles page transition

Component.vue: mounted() set state to this.show: true and <transition ... > and v-if animate specific Elements in on render

When I navigate away from the component with the App.vue <router-link> the beforeRouteLeave gets called and sets this.show: false to animate out specific Elements and should then move on. BUT <router-link> renders the next component immediately without waiting...

In short I'd like to achieve smth similar to this http://animate.mhaagens.me/

Any hints?

答:
I'm not sure if it solves all your problems, especially since I don't know exactly what behaviour you are looking for, but the transition effects in Vue provide transition modes.

transition mode="out-in" is perhaps what you are looking for. It waits for the first transition to end before starting the new one and is useful when transitioning between components. Check out the docs, they're very thorough and really good.


问:
Change character spacing on UILabel within Interface Builder
Is there anyway to change the character spacing (track) on UILabel text using Interface Builder? If not, is there a way to do it programmatically on an existing UILabel that was already created with attributed text?</p>

答:
Swift 5 and higher

```<code>extension UILabel {
  func setTextSpacingBy(value: Double) {
    if let textString = self.text {
      let attributedString = NSMutableAttributedString(string: textString)
      attributedString.addAttribute(NSKernAttributeName, value: value, range: NSRange(location: 0, length: attributedString.length - 1))
      attributedText = attributedString
    }
  }
}
</code>```

Body:
Swift 5 and higher

extension UILabel {
  func setTextSpacingBy(value: Double) {
    if let textString = self.text {
      let attributedString = NSMutableAttributedString(string: textString)
      attributedString.addAttribute(NSKernAttributeName, value: value, range: NSRange(location: 0, length: attributedString.length - 1))
      attributedText = attributedString
    }
  }
}


问:
FCM support when app is terminated
I am using FCM notification for my app. When my app is in background or foreground I am receiving notification. But when my app is terminated that means closed from task then I am not receiving any notification. I searched about this and I am confused is it work when the app is terminated? I just need to know is it work or not when the app is terminated.

If it works when the app is terminated then I will go for next step for my app otherwise I will stop my implementation that's why I am not sharing any code. I followed this link

答: Beware with fcm on iOS, there are 2 ways of sending and receiving data; one is upstream/downstream messages the other is the push notifications. If you are using upstream/downstream messages the fcm connection is closed after the app is suspended, new messages will not wake your app. You may use push notifications instead but of course the downside is that they are push notifications you don't have much control over them. </p>

Title: FCM support when app is terminated


问:
Keras Tutorial Example cifar10_cnn.py gives acc: 0.34 val_acc: 0.40 in 200 epochs on windows 10?
I am running the tutorial example cifar10_cnn.py from here.

Here is the environment/configuration for the test:

Windows 10

Keras 1.2.0

Theano 0.8.2

Numpy 1.11.2

Enthought/Canopy/MKL(2017.0.1-1)

.theanorc [blas] ldflags -L... -lmk2_rt

The program took about one and half day to finish 200 epochs. The following figure shows the header and the last three epochs.

Using Theano backend

X_train shape: (50000L, 32L, 32L, 3L) ...

Epoch 198/200
50000/50000 [==============================] - 639s - loss: 1.7894 - acc: 0.3497 - val_loss: 1.5930 - val_acc: 0.3968

Epoch 199/200
50000/50000 [==============================] - 617s - loss: 1.8111 - acc: 0.3446 - val_loss: 1.6960 - val_acc: 0.3824

Epoch 200/200
50000/50000 [==============================] - 612s - loss: 1.8005 - acc: 0.3497 - val_loss: 1.6164 - val_acc: 0.4041

I have two questions here:

The accuracy (0.34/0.40) is too bad. Does anyone have similar problems?

The shape of X_train as (50000, 32, 32, 3) seems strange to me because
other keras/cifar examples give the shape of X_train as (50000, 3, 32, 32). If I add "set_image_dim_ordering('th')" to the code, the shape will become (50000, 3, 32, 32) but the program will give even lower accuracy as "Epoch 80/200 50000/50000 - 635s - loss: 14.5010 - acc: 0.1003 - val_loss: 14.5063 - val_acc: 0.1000" How to explain the effect of set dim here?

Thanks for any comments.

答:
That may not be the answer for the whole subject, but in order to get the correct image shape, you should just verify whether the image channel is the first or the last item of the shape. You can do it the following way, considering Keras 2:

```<code>from keras import backend as K

def image_input_shape(img_width, img_height):
    if K.image_data_format() == 'channels_first':
        input_shape = (3, img_width, img_height)
    else:
        input_shape = (img_width, img_height, 3)
    return input_shape
</code>```

Just pass the image width and height and it will give back the correct ordering of the shape.

From there you can discard or validate you hypothesis for the "strange" shape.

Body:
That may not be the answer for the whole subject, but in order to get the correct image shape, you should just verify whether the image channel is the first or the last item of the shape. You can do it the following way, considering Keras 2:

from keras import backend as K

def image_input_shape(img_width, img_height):
    if K.image_data_format() == 'channels_first':
        input_shape = (3, img_width, img_height)
    else:
        input_shape = (img_width, img_height, 3)
    return input_shape

Just pass the image width and height and it will give back the correct ordering of the shape.

From there you can discard or validate you hypothesis for the "strange" shape.


问:
passing GL_FLOAT and GL_UNSIGNED_INT into one stride
I am wondering, I have the following setup:

```<code>glEnableVertexAttribArray(VERTEX_COORD_ATTRIB);
glEnableVertexAttribArray(TEXTURE_COORD_ATTRIB);
glEnableVertexAttribArray(COLOR_ATTRIB);
glEnableVertexAttribArray(TEXNUM_ATTRIB);

glVertexAttribPointer(VERTEX_COORD_ATTRIB, 3, GL_FLOAT, GL_FALSE, StrideSize, (void*)0);
glVertexAttribPointer(TEXTURE_COORD_ATTRIB, 2, GL_FLOAT, GL_FALSE, StrideSize, (void*)(VertFloatSize));
glVertexAttribPointer(COLOR_ATTRIB, 4, GL_FLOAT, GL_FALSE, StrideSize, (void*)(VertFloatSize + TexFloatSize));
glVertexAttribPointer(TEXNUM_ATTRIB, 1, GL_FLOAT, GL_FALSE, StrideSize, (void*)(VertFloatSize + TexFloatSize + ColorFloatSize));
</code>```

while StrideSize is:

```<code>GLuint StrideSize = (sizeof(float) * FloatsPerVertex) + (sizeof(float) * TexCoords2D) + (sizeof(float) * ColorInfo) + (sizeof(float));
</code>```

having in the shader

```<code>layout (location = 0) in vec3 Coords;
layout (location = 2) in vec2 TexCoords;
layout (location = 8) in vec4 DrawColor;
layout (location = 10) in float TexNum;
</code>```

Everything appears to be fine as a result. However I dislike to cast TexNum, which is an unsigned int, back into uint in the shader.

But if I do:

```<code>glEnableVertexAttribArray(VERTEX_COORD_ATTRIB);
glEnableVertexAttribArray(TEXTURE_COORD_ATTRIB);
glEnableVertexAttribArray(COLOR_ATTRIB);
glEnableVertexAttribArray(TEXNUM_ATTRIB);

glVertexAttribPointer(VERTEX_COORD_ATTRIB, 3, GL_FLOAT, GL_FALSE, StrideSize, (void*)0);
glVertexAttribPointer(TEXTURE_COORD_ATTRIB, 2, GL_FLOAT, GL_FALSE, StrideSize, (void*)(VertFloatSize));
glVertexAttribPointer(COLOR_ATTRIB, 4, GL_FLOAT, GL_FALSE, StrideSize, (void*)(VertFloatSize + TexFloatSize));
glVertexAttribIPointer(TEXNUM_ATTRIB, 1, GL_UNSIGNED_INT, StrideSize, (void*)(VertFloatSize + TexFloatSize + ColorFloatSize));
</code>```

while StrideSize is:

```<code>GLuint StrideSize = (sizeof(float) * FloatsPerVertex) + (sizeof(float) * TexCoords2D) + (sizeof(float) * ColorInfo) + (sizeof(GLuint));
</code>```

having in the shader

```<code>layout (location = 0) in vec3 Coords;
layout (location = 2) in vec2 TexCoords;
layout (location = 8) in vec4 DrawColor;
layout (location = 10) in uint TexNum;
</code>```

the value doesn't seem to be passed correctly. I know that glVertexAttribPointer always converts into float and that glVertexAttribIPointer is to be used instead.
What did I miss? Is it not allowed to pass 2 different datatypes in one stride? Or do I have to buffer it separately?
I found a couple of almost similar questions, but none asking this specifically, but I also didn't find any indication somewhere why this shouldn't work.
Passing TexNum as uniform also works out correctly, but is not really handy if I want to batch my drawcalls.

Forgive me if I am just blind again :)

答:
You didn't mention that in case of GL_UNSIGNED_INT for TexNum, you actually have ints in memory instead of floats.

So, do you convert your TexNum to int?

(you can pass whatever datatypes you want in one stride, it must work)

Body:
I am wondering, I have the following setup:

glEnableVertexAttribArray(VERTEX_COORD_ATTRIB);
glEnableVertexAttribArray(TEXTURE_COORD_ATTRIB);
glEnableVertexAttribArray(COLOR_ATTRIB);
glEnableVertexAttribArray(TEXNUM_ATTRIB);

glVertexAttribPointer(VERTEX_COORD_ATTRIB, 3, GL_FLOAT, GL_FALSE, StrideSize, (void*)0);
glVertexAttribPointer(TEXTURE_COORD_ATTRIB, 2, GL_FLOAT, GL_FALSE, StrideSize, (void*)(VertFloatSize));
glVertexAttribPointer(COLOR_ATTRIB, 4, GL_FLOAT, GL_FALSE, StrideSize, (void*)(VertFloatSize + TexFloatSize));
glVertexAttribPointer(TEXNUM_ATTRIB, 1, GL_FLOAT, GL_FALSE, StrideSize, (void*)(VertFloatSize + TexFloatSize + ColorFloatSize));

while StrideSize is:

GLuint StrideSize = (sizeof(float) * FloatsPerVertex) + (sizeof(float) * TexCoords2D) + (sizeof(float) * ColorInfo) + (sizeof(float));

having in the shader

layout (location = 0) in vec3 Coords;
layout (location = 2) in vec2 TexCoords;
layout (location = 8) in vec4 DrawColor;
layout (location = 10) in float TexNum;

Everything appears to be fine as a result. However I dislike to cast TexNum, which is an unsigned int, back into uint in the shader.

But if I do:

glEnableVertexAttribArray(VERTEX_COORD_ATTRIB);
glEnableVertexAttribArray(TEXTURE_COORD_ATTRIB);
glEnableVertexAttribArray(COLOR_ATTRIB);
glEnableVertexAttribArray(TEXNUM_ATTRIB);

glVertexAttribPointer(VERTEX_COORD_ATTRIB, 3, GL_FLOAT, GL_FALSE, StrideSize, (void*)0);
glVertexAttribPointer(TEXTURE_COORD_ATTRIB, 2, GL_FLOAT, GL_FALSE, StrideSize, (void*)(VertFloatSize));
glVertexAttribPointer(COLOR_ATTRIB, 4, GL_FLOAT, GL_FALSE, StrideSize, (void*)(VertFloatSize + TexFloatSize));
glVertexAttribIPointer(TEXNUM_ATTRIB, 1, GL_UNSIGNED_INT, StrideSize, (void*)(VertFloatSize + TexFloatSize + ColorFloatSize));

while StrideSize is:

GLuint StrideSize = (sizeof(float) * FloatsPerVertex) + (sizeof(float) * TexCoords2D) + (sizeof(float) * ColorInfo) + (sizeof(GLuint));

having in the shader

layout (location = 0) in vec3 Coords;
layout (location = 2) in vec2 TexCoords;
layout (location = 8) in vec4 DrawColor;
layout (location = 10) in uint TexNum;

the value doesn't seem to be passed correctly. I know that glVertexAttribPointer always converts into float and that glVertexAttribIPointer is to be used instead.
What did I miss? Is it not allowed to pass 2 different datatypes in one stride? Or do I have to buffer it separately?
I found a couple of almost similar questions, but none asking this specifically, but I also didn't find any indication somewhere why this shouldn't work.
Passing TexNum as uniform also works out correctly, but is not really handy if I want to batch my drawcalls.

Forgive me if I am just blind again :)


问:
Building executable with Android NDK
I am trying to build an executable using the Android NDK.  To do this, I've created an "Android Library" project and included all my native code (cpp) files in it under the directory "src/main/cpp".

In the CMakeLists.txt file, I've added the following.

```<code>cmake_minimum_required(VERSION 3.4.1)

set (TEST_SRC
    src/test/cpp/test.cpp
)

add_library (test-lib SHARED ${TEST_SRC})
add_executable(test-exec ${TEST_SRC})
</code>```

When I perform a build, I see that the library is created correctly in my build output directory (libtest-lib.so), however, the executable is not produced.

I decided to build my project with command-line (./gradlew clean build --info --debug) and found the following log message.

```<code>externalNativeBuildRelease: not building target test-exec because no
targets are specified and library build output file extension isn't
'so'.
</code>```

It seems that the android NDK is purposefully disabling my executable from being built :( Is there a way around this? Or did I specify something incorrectly?

答:
UPDATE: Since I posted this answer, I have found a much cleaner solution. There is no need to modify anything in Android.mk files. The following is the relevant portion of app/build.gradle (The original gradle script belongs to the syncopoli project. You can find the original up-to-date version of this build.gradle script here:

```<code>android {

    defaultConfig {
        // ...

        externalNativeBuild {
            ndkBuild {
                // I only want the following targets to be built
                targets 'rsync', 'ssh'
            }
        }

        ndk {
            // add whatever ABIs you want here
            abiFilters 'armeabi'
        }
    }

    externalNativeBuild {
        ndkBuild {
            // all my external sources are under src/main/jni
            path 'src/main/jni/Android.mk'
        }
    }
}

// this is the meat. It copies the binaries to appropriate location
// after externalNativeBuildRelease task is finished.
// you can change the paths to match where your binaries live and where
// you want them to go
gradle.taskGraph.afterTask { task ->
    if (task.name == "externalNativeBuildRelease") {
        def src = rootProject.file('app/build/intermediates/ndkBuild/release/obj/local/')
        def dst = rootProject.file('app/src/main/assets/')

        copy {
            from(src) {
                // the objs directory has all the .o files I don't care about
                exclude "**/objs"
            }

            into dst

            // this is purely for debugging purposes. it might come in handy
            eachFile {
                println "file = " + it.getPath()
            }
        }

    }
}
</code>```

my src/main/jni/Android.mk has the following content:

```<code>include $(call all-subdir-makefiles)
</code>```

PREVIOUS ANSWER

I have hit this issue and worked around it by creating extra tasks in gradle that call ndk-build manually and setting the project to depend on these tasks.

This is the relevant part of app/build.gradle:

```<code>import org.apache.tools.ant.taskdefs.condition.Os

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())

task ndkBuild(type: Exec) {
    def ndkDirProperty = properties.getProperty('ndk.dir')
    def ndkDirPrefix = ndkDirProperty != null ? ndkDirProperty + '/' : ''

    def ndkBuildExt = Os.isFamily(Os.FAMILY_WINDOWS) ? ".cmd" : ""

    commandLine "${ndkDirPrefix}ndk-build${ndkBuildExt}", '-C', file('src/main').absolutePath,
            '-j', Runtime.runtime.availableProcessors()
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn ndkBuild
}

// Cleanup task to remove previously generated binaries
task ndkClean(type: Exec) {
    def ndkDirProperty = properties.getProperty('ndk.dir')
    def ndkDirPrefix = ndkDirProperty != null ? ndkDirProperty + '/' : ''

    def ndkBuildExt = Os.isFamily(Os.FAMILY_WINDOWS) ? ".cmd" : ""

    commandLine "${ndkDirPrefix}ndk-build${ndkBuildExt}", '-C', file('src/main').absolutePath, 'clean'
}

tasks.withType(Delete) {
    cleanTask -> cleanTask.dependsOn ndkClean
}
</code>```

I have also further modified Android.mk files for the executables so the final executables end up in assets/<target_arch_abi>/<executable.

```<code>SAVED_NDK_APP_DST_DIR := $(NDK_APP_DST_DIR)
NDK_APP_DST_DIR := assets/$(TARGET_ARCH_ABI)
...LOCAL_MODULE/LOCAL_CFLAGS/LOCAL_etc...
include $(BUILD_EXECUTABLE)
NDK_APP_DST_DIR := $(SAVED_NDK_APP_DST_DIR)
</code>```

now, running gradlew build builds the executables alongside the rest.

Hope this helps.

Title: Building executable with Android NDK

Body:
I am trying to build an executable using the Android NDK.  To do this, I've created an "Android Library" project and included all my native code (cpp) files in it under the directory "src/main/cpp".

In the CMakeLists.txt file, I've added the following.

cmake_minimum_required(VERSION 3.4.1)

set (TEST_SRC
    src/test/cpp/test.cpp
)

add_library (test-lib SHARED ${TEST_SRC})
add_executable(test-exec ${TEST_SRC})

When I perform a build, I see that the library is created correctly in my build output directory (libtest-lib.so), however, the executable is not produced.

I decided to build my project with command-line (./gradlew clean build --info --debug) and found the following log message.

externalNativeBuildRelease: not building target test-exec because no
targets are specified and library build output file extension isn't
'so'.

It seems that the android NDK is purposefully disabling my executable from being built :( Is there a way around this? Or did I specify something incorrectly?

Body:
UPDATE: Since I posted this answer, I have found a much cleaner solution. There is no need to modify anything in Android.mk files. The following is the relevant portion of app/build.gradle (The original gradle script belongs to the syncopoli project. You can find the original up-to-date version of this build.gradle script here:

android {

    defaultConfig {
        // ...

        externalNativeBuild {
            ndkBuild {
                // I only want the following targets to be built
                targets 'rsync', 'ssh'
            }
        }

        ndk {
            // add whatever ABIs you want here
            abiFilters 'armeabi'
        }
    }

    externalNativeBuild {
        ndkBuild {
            // all my external sources are under src/main/jni
            path 'src/main/jni/Android.mk'
        }
    }
}

// this is the meat. It copies the binaries to appropriate location
// after externalNativeBuildRelease task is finished.
// you can change the paths to match where your binaries live and where
// you want them to go
gradle.taskGraph.afterTask { task ->
    if (task.name == "externalNativeBuildRelease") {
        def src = rootProject.file('app/build/intermediates/ndkBuild/release/obj/local/')
        def dst = rootProject.file('app/src/main/assets/')

        copy {
            from(src) {
                // the objs directory has all the .o files I don't care about
                exclude "**/objs"
            }

            into dst

            // this is purely for debugging purposes. it might come in handy
            eachFile {
                println "file = " + it.getPath()
            }
        }

    }
}

my src/main/jni/Android.mk has the following content:

include $(call all-subdir-makefiles)

PREVIOUS ANSWER

I have hit this issue and worked around it by creating extra tasks in gradle that call ndk-build manually and setting the project to depend on these tasks.

This is the relevant part of app/build.gradle:

import org.apache.tools.ant.taskdefs.condition.Os

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())

task ndkBuild(type: Exec) {
    def ndkDirProperty = properties.getProperty('ndk.dir')
    def ndkDirPrefix = ndkDirProperty != null ? ndkDirProperty + '/' : ''

    def ndkBuildExt = Os.isFamily(Os.FAMILY_WINDOWS) ? ".cmd" : ""

    commandLine "${ndkDirPrefix}ndk-build${ndkBuildExt}", '-C', file('src/main').absolutePath,
            '-j', Runtime.runtime.availableProcessors()
}

tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn ndkBuild
}

// Cleanup task to remove previously generated binaries
task ndkClean(type: Exec) {
    def ndkDirProperty = properties.getProperty('ndk.dir')
    def ndkDirPrefix = ndkDirProperty != null ? ndkDirProperty + '/' : ''

    def ndkBuildExt = Os.isFamily(Os.FAMILY_WINDOWS) ? ".cmd" : ""

    commandLine "${ndkDirPrefix}ndk-build${ndkBuildExt}", '-C', file('src/main').absolutePath, 'clean'
}

tasks.withType(Delete) {
    cleanTask -> cleanTask.dependsOn ndkClean
}

I have also further modified Android.mk files for the executables so the final executables end up in assets/<target_arch_abi>/<executable.

SAVED_NDK_APP_DST_DIR := $(NDK_APP_DST_DIR)
NDK_APP_DST_DIR := assets/$(TARGET_ARCH_ABI)
...LOCAL_MODULE/LOCAL_CFLAGS/LOCAL_etc...
include $(BUILD_EXECUTABLE)
NDK_APP_DST_DIR := $(SAVED_NDK_APP_DST_DIR)

now, running gradlew build builds the executables alongside the rest.

Hope this helps.


问:
How to download Udemy Videos?
Once you buy a course there is usually option to download individual lecture. However there are many courses on Udemy which do not have download option for the lecture. Is there a way to download them.</p>

答:
The udemy-dl method doesn't always work; but the youtube-dl method works every time! And I'm personally using it for downloading Udemy courses all at once (full course) or also individual videos.
You can do so easily with the help of the youtube-dl Python script.

You have to have Python and PIP installed.

Open command prompt or terminal

Type in there: pip install youtube-dl

Then after downloading youtube-dl , open your Udemy account where you have bought the course.

Open the course that you want to download.

Click on the course content option

Copy the link in url bar copy the link in url bar

Finally, execute the following command in your terminal:

C:\Users\ARSHDEEP SINGH>** youtube-dl -u user@gmail.com -p password COURSE_LINK**

Type your username or e-mail and password

If the username and password are correct, the following will appear in your terminal:

```<code>[udemy:course] Downloading login popup
[udemy:course] Logging in as 2arshahuja@gmail.com
[udemy:course] python-for-data-science-and-machine-learning-bootcamp: Downloading webpage
[udemy:course] 903744: Downloading course curriculum
[download] Downloading playlist: Python for Data Science and Machine Learning Bootcamp
[udemy:course] playlist Python for Data Science and Machine Learning Bootcamp: Collected 133 video ids (downloading 133 of them)
[download] Downloading video 1 of 133
[udemy] Downloading login popup
[udemy] 5440650: Downloading webpage
[udemy] 5440650: Downloading lecture JSON
[download] Resuming download at byte 114615
[download] Destination: Introduction to the Course-6808420.mp4
[download]   0.7% of 43.01MiB at 66.01KiB/s ETA 11:02
</code>```

here explained with screenshots!! also explained for mac users

Title: How to download Udemy Videos?

Body:
The udemy-dl method doesn't always work; but the youtube-dl method works every time! And I'm personally using it for downloading Udemy courses all at once (full course) or also individual videos.
You can do so easily with the help of the youtube-dl Python script.

You have to have Python and PIP installed.

Open command prompt or terminal

Type in there: pip install youtube-dl

Then after downloading youtube-dl , open your Udemy account where you have bought the course.

Open the course that you want to download.

Click on the course content option

Copy the link in url bar copy the link in url bar

Finally, execute the following command in your terminal:

C:\Users\ARSHDEEP SINGH>** youtube-dl -u user@gmail.com -p password COURSE_LINK**

Type your username or e-mail and password

If the username and password are correct, the following will appear in your terminal:

[udemy:course] Downloading login popup
[udemy:course] Logging in as 2arshahuja@gmail.com
[udemy:course] python-for-data-science-and-machine-learning-bootcamp: Downloading webpage
[udemy:course] 903744: Downloading course curriculum
[download] Downloading playlist: Python for Data Science and Machine Learning Bootcamp
[udemy:course] playlist Python for Data Science and Machine Learning Bootcamp: Collected 133 video ids (downloading 133 of them)
[download] Downloading video 1 of 133
[udemy] Downloading login popup
[udemy] 5440650: Downloading webpage
[udemy] 5440650: Downloading lecture JSON
[download] Resuming download at byte 114615
[download] Destination: Introduction to the Course-6808420.mp4
[download]   0.7% of 43.01MiB at 66.01KiB/s ETA 11:02

here explained with screenshots!! also explained for mac users


问:
JTestcase for data in xml files with JUnit?
I looked upon some years old code which uses JTestcase for separating data from Test case(JTestCase basically helps to manage data in xml files).
So JTestCase is integrated with JUnit test cases code.

Jar available for JTestcase is 2006 version so i guess there is no new release for same. This makes me think that probably JTestCase is old thing to use otherwise they would have provided new version.

Please tell me if there is some new technology in place of JTestCase and if not what are negatives of Jtestcase(like one can be performance considering fact that it allows use of xml files which is itself in trade off with better organization of complex data).

I couldn't find Maven artifact for JTestcase. Please let me know if it is available on any site.

Which site is good dependable source to find maven artifact. Currently i see https://repository.sonatype.org/index.html#welcome for same purpose.

答:
That seems like a lot of effort to go to just to write a unit test.

I think the negative of using JTestCase is doubling the amount of code you have to write.

I wouldn't use this framework unless you could see some significant benefit to putting your test data into XML. I think doing this for tests would make it harder to maintain in most cases!


问:
Change value in nana listbox
I am trying to create a GUI with a property grid ( grid of name:value pairs )

The listbox widget seems to be the way to start. ( please correct me if something better is available )

The code ( below ) I have written compiles and runs. The initial name/value pairs show fine, but the attempt to change the value of the first item achieves nothing.

I have looked at several listbox examples, but cannot find a simple way to change a value in a listbox once initialized

```<code>int main()
{
using namespace nana;

// form to hold everything
form fm;

// listbox to be the property grid
listbox lb(fm, nana::rectangle(10, 10, 280, 120));

// column headers
lb.append_header("Name", 200);
lb.append_header("Value", 200);

// add two items to the default category
lb.at(0).append({"A", "0"});
lb.at(0).append({"B", "0"});

// change value of A item to 32 ( fails to do anything )
lb.at(listbox::index_pair(0,1)).value("32");

fm.show();
exec();
}
</code>```

Also tried ( doesn't compile )

```<code>lb.at(listbox::index_pair(0,1)).value({"A","32"});
</code>```

and ( runs, has no effect )

```<code>lb.anyobj(0, 0, "32");
</code>```

答:
You are using very low level functions. There are more convenient higth level functions to set/change the values/text/items in the listbox (using STL containers or resolvers).

Assuming you want to use these low level function becouse you want to implement your own higth level API, here are some facts:

The value function of the item_proxy you are accesing with at(index_pair) will give you acces to some object you have previusly attached to that item. You have not attached any object. You may effectively first attach, an object or you may continue to work directly with the text. The simplest "hack" is to use the function text:  lb.at(listbox::index_pair(0,1)).text(1,"32"), which set the text for the column 1 of that item.

EDIT: A relatively simple to understand explanation: 3-methods-to-insert-data-into-listbox

Title: Change value in nana listbox

Body:
I am trying to create a GUI with a property grid ( grid of name:value pairs )

The listbox widget seems to be the way to start. ( please correct me if something better is available )

The code ( below ) I have written compiles and runs. The initial name/value pairs show fine, but the attempt to change the value of the first item achieves nothing.

I have looked at several listbox examples, but cannot find a simple way to change a value in a listbox once initialized

int main()
{
using namespace nana;

// form to hold everything
form fm;

// listbox to be the property grid
listbox lb(fm, nana::rectangle(10, 10, 280, 120));

// column headers
lb.append_header("Name", 200);
lb.append_header("Value", 200);

// add two items to the default category
lb.at(0).append({"A", "0"});
lb.at(0).append({"B", "0"});

// change value of A item to 32 ( fails to do anything )
lb.at(listbox::index_pair(0,1)).value("32");

fm.show();
exec();
}

Also tried ( doesn't compile )

lb.at(listbox::index_pair(0,1)).value({"A","32"});

and ( runs, has no effect )

lb.anyobj(0, 0, "32");


问:
error when change onclick function to onload function
I have a script where there is a button to start playing sound.
If the button is clicked (onclick), then the sound will be played in sequence.

here the script:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="../syle.css" />
<script type="text/javascript" src="../jquery-1.7.2.js"></script>
</head>
<body>
    <audio id="suarabel" src="../panggilan/bell.wav"></audio>
    <audio id="suarabelnomorurut" src="../panggilan/nomor.wav"  ></audio>
    <audio id="suarabelsuarabelloket" src="../panggilan/loket.wav"  ></audio>
    <audio id="huruf_loket" src="../panggilan/a.wav"  ></audio>
    <audio id="huruf_nomor" src="../panggilan/1.wav"  ></audio>
    <audio id="suarabelloket1" src="../panggilan/1.wav"  ></audio>

    <div class="kontainer2">
      <div align="center">
        <input id="play" name="play" onclick="mulai();" type="button" value="Panggil" />
      </div>
    </div>

<script type="text/javascript">
function mulai(){
    //Play Bell
    document.getElementById('suarabel').pause();
    document.getElementById('suarabel').currentTime=0;
    document.getElementById('suarabel').play();

    //delay before squence
    totalwaktu=document.getElementById('suarabel').duration*1000;

    //play number voice
    setTimeout(function() {
            document.getElementById('suarabelnomorurut').pause();
            document.getElementById('suarabelnomorurut').currentTime=0;
            document.getElementById('suarabelnomorurut').play();
    }, totalwaktu);
    totalwaktu=totalwaktu+1600;
                setTimeout(function() {
                        document.getElementById('huruf_nomor').pause();
                        document.getElementById('huruf_nomor').currentTime=0;
                        document.getElementById('huruf_nomor').play();
                    }, totalwaktu);
                totalwaktu=totalwaktu+1000;

        totalwaktu=totalwaktu+1000;
        setTimeout(function() {
                        document.getElementById('suarabelsuarabelloket').pause();
                        document.getElementById('suarabelsuarabelloket').currentTime=0;
                        document.getElementById('suarabelsuarabelloket').play();
                    }, totalwaktu);

        totalwaktu=totalwaktu+1000;
        setTimeout(function() {
                        document.getElementById('suarabelloket1').pause();
                        document.getElementById('suarabelloket1').currentTime=0;
                        document.getElementById('suarabelloket1').play();
                    }, totalwaktu);

        totalwaktu=totalwaktu+750;
        setTimeout(function() {
                        document.getElementById('huruf_loket').pause();
                        document.getElementById('huruf_loket').currentTime=0;
                        document.getElementById('huruf_loket').play();
                    }, totalwaktu);
}
</script>
</body>
</html>
</code>```

I tried to replace onclick with onload function, but if I use the onload function, the sound is played simultaneously and not sequentially.

In Javascript

```<code>window.onload=function(){
    mulai();
};
</code>```

or In JQuery

```<code>$(document).ready(function(){
   mulai();
});
</code>```

edited:
i change the line

```<code>totalwaktu=document.getElementById('suarabel').duration*1000;
</code>```

with this

```<code>totalwaktu=5000;
</code>```

and now my script with onload function work.

答:
As written in the comment of skobaljic
document.getElementById('suarabel').duration is not loaded yet and you get  NaN so any mathematical operation on it will give NaN. All calculation of totalwaktu will give NaN and when setTimeout get NaN as parameter it converts it to 0.
Put console.log(totalwaktu) after each totalwaktu to see if this indeed happened

Body:
I have a script where there is a button to start playing sound.
If the button is clicked (onclick), then the sound will be played in sequence.

here the script:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="../syle.css" />

    <audio id="suarabel" src="../panggilan/bell.wav"></audio>
    <audio id="suarabelnomorurut" src="../panggilan/nomor.wav"  ></audio>
    <audio id="suarabelsuarabelloket" src="../panggilan/loket.wav"  ></audio>
    <audio id="huruf_loket" src="../panggilan/a.wav"  ></audio>
    <audio id="huruf_nomor" src="../panggilan/1.wav"  ></audio>
    <audio id="suarabelloket1" src="../panggilan/1.wav"  ></audio>

        <input id="play" name="play" onclick="mulai();" type="button" value="Panggil" />

I tried to replace onclick with onload function, but if I use the onload function, the sound is played simultaneously and not sequentially.

In Javascript

window.onload=function(){
    mulai();
};

or In JQuery

$(document).ready(function(){
   mulai();
});

edited:
i change the line

totalwaktu=document.getElementById('suarabel').duration*1000;

with this

totalwaktu=5000;

and now my script with onload function work.


问:
EmptyThrowable error in Android Studio's Run
I'm trying to run my App through Android Studio, but I'm receiving next error:

```<code>13:02:50 EmptyThrowable
     Invalid stub element type in index:
     file: file://C:/Users/d_mas/AppData/Local/Android/sdk/sources/android-25/java/util/Calendar.java
     psiElement: PsiImportList
     requiredClass: interface com.intellij.psi.PsiClass
     actualClass: class com.intellij.psi.impl.source.PsiImportListImpl
     virtualFile: size:106178; stamp:0; modCount:1499594398217; fileType:JAVA; language:JAVA
     document: size:106178; stamp:0; committed:true; saved:true
     psiFile: size:106178; stamp:0; class:com.intellij.psi.impl.source.PsiJavaFileImpl; language:JAVA
     stubInfo: created in getStubTree(); with backReference
     indexing info: no data
</code>```

The Compile SDK Version is 25, Build Tools Version 25.0.3, MinSdk Version 15 and compile 'com.android.support:appcompat-v7:25.0.0'. I'm using the JDK 1.8.

答: Try "Invalidate caches/restart" option in the File menu.

Body:
I'm trying to run my App through Android Studio, but I'm receiving next error:

13:02:50 EmptyThrowable
     Invalid stub element type in index:
     file: file://C:/Users/d_mas/AppData/Local/Android/sdk/sources/android-25/java/util/Calendar.java
     psiElement: PsiImportList
     requiredClass: interface com.intellij.psi.PsiClass
     actualClass: class com.intellij.psi.impl.source.PsiImportListImpl
     virtualFile: size:106178; stamp:0; modCount:1499594398217; fileType:JAVA; language:JAVA
     document: size:106178; stamp:0; committed:true; saved:true
     psiFile: size:106178; stamp:0; class:com.intellij.psi.impl.source.PsiJavaFileImpl; language:JAVA
     stubInfo: created in getStubTree(); with backReference
     indexing info: no data

The Compile SDK Version is 25, Build Tools Version 25.0.3, MinSdk Version 15 and compile 'com.android.support:appcompat-v7:25.0.0'. I'm using the JDK 1.8.


问:
cancelAnimationFrame Not Working
i made this flappy bird clone. But cancelAnimationFrame() does not seem to work

And i don't know how to stop my game.

cancelAnimationFrame is inside of function stop() and stop is being called from
class Pipe's update methode().

what am i missing.

Please can anyone help me solve this problem

```<code><head>
  <meta charset="utf-8">
  <title></title>
  <style media="screen">

    #app{
      height:500px;
      width:300px;
      background-color: #000;
      position: relative;
    }

    #app div{
      position:absolute;
      overflow: hidden;
      background-color: #fff;
    }

    .bird{
      border-radius:50%;
      height: 20px;
      width:20px;
      left:20px;
    }

    .pipe{
      width: 30px;
    }
  </style>
</head>
<body>
  <div id="app">
  </div>
  <script type="text/javascript">
    var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
                            window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

    var cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame;
    class App{
      constructor(){
        this.app = document.getElementById('app');
        this.bird = new Bird();
        this.pipe = []
        this.pipe.push(new Pipe(-30,this.bird));
        this.pipe.push(new Pipe(-130,this.bird));
        this.pipe.push(new Pipe(-230,this.bird));
        document.addEventListener("keypress",()=>{
          this.bird.jump+=10;
        });
      }
      update(){
        this.bird.update();
        this.pipe.forEach(function(p){
          p.update();
        });
        // myArray.splice(0, 2)
        if(frame%330==0){
          this.pipe.push(new Pipe(-30,this.bird));
          this.pipe.push(new Pipe(-130,this.bird));
          this.pipe.push(new Pipe(-230,this.bird));
          if(frame>990)
            this.pipe.splice(0,3);
        }
      }
    }
    class Bird{
      constructor(){
        this.el=document.createElement("div");
        this.el.setAttribute("class","bird");
        this.el.style.top=(app.clientHeight/2-10)+"px";
        app.appendChild(this.el);
        this.jump=0;
      }
      update(){
        if(this.jump>0){
          this.jumpf();
          this.jump--;
        }else
          this.fall();
      }
      jumpf(){
      this.el.style.top=n2p(p2n(this.el.style.top)-10);
      }
      fall(){
        this.el.style.top=(p2n(this.el.style.top)<app.clientHeight)?(n2p(p2n(this.el.style.top)+5)) : this.el.style.top;
      }
    }

    class Pipe{
      constructor(right=-30,bird){
        this.el=[];
        this.bird=bird;
        this.el.push(document.createElement("div"));
        this.el.push(document.createElement("div"));
        this.pipeNum=1;
        this.height1=0;
        this.el.forEach(
          (pipe)=>{
            pipe.setAttribute("class","pipe");
            app.appendChild(pipe);
            pipe.style.right=right+"px";
            if(this.pipeNum==1){
              pipe.style.height=this.height1=n2p(Math.random()*400);
              pipe.style.bottom="0px";
              this.pipeNum++;
            }else{
              pipe.style.height=n2p((400-p2n(this.height1))*Math.random());
              pipe.style.top="0px";
              this.pipeNum--;
            }
          });
      }
      update(){
        this.el.forEach((pipe)=>{
          pipe.style.right=n2p(p2n(pipe.style.right)+1);
          if(this.pipeNum==1 && p2n(pipe.style.right)>230 && p2n(pipe.style.right)<=280 && (500-(p2n(pipe.style.bottom) + pipe.clientHeight)) < (p2n(this.bird.el.style.top)+this.bird.el.clientHeight)){
            pipe.style.background="red";
            stop();
          }else if(this.pipeNum==2 && p2n(pipe.style.right)>230 && p2n(pipe.style.right)<=280 && pipe.clientHeight > p2n(this.bird.el.style.top)){
            pipe.style.background="red";
            stop();
          }
          if(this.pipeNum==1)
            this.pipeNum++;
          else
            this.pipeNum--;
          if(app.count%330==0)
            app.removeChild(pipe);
        });
      }
    }
    var game = new App();
    var frame;
    function start(){
      game.update();
      frame=requestAnimationFrame(start);
    }
    start();
    function p2n(num){
      return parseInt(num.replace("px",""));
    }
    function n2p(num){
      return num+"px";
    }
    function stop(){
      if(frame)
      console.log("asdfas");
      cancelAnimationFrame(frame);
    }
  </script>
</body>
</code>```

答:
Probably because of this code:

```<code>function start(){
  game.update();
  // game.update calls stop if conditions met
  // stop calls cancelAnimationFrame
  // then function start called again on following line
  frame=requestAnimationFrame(start);
}
</code>```

i think you can do this:

```<code>   var stopGame;

   function start(){
      stopGame = false;
      game.update();
      if (stopGame === false) {
          frame=requestAnimationFrame(start);
      }
    }

function stop(){
  if(frame) {
     console.log("asdfas");
     cancelAnimationFrame(frame);
     stopGame = true;
  }
}
</code>```

Title: cancelAnimationFrame Not Working

Body:
i made this flappy bird clone. But cancelAnimationFrame() does not seem to work

And i don't know how to stop my game.

cancelAnimationFrame is inside of function stop() and stop is being called from
class Pipe's update methode().

what am i missing.

Please can anyone help me solve this problem

  <meta charset="utf-8">
  <title></title>

Body:
Probably because of this code:

function start(){
  game.update();
  // game.update calls stop if conditions met
  // stop calls cancelAnimationFrame
  // then function start called again on following line
  frame=requestAnimationFrame(start);
}

i think you can do this:

   var stopGame;

   function start(){
      stopGame = false;
      game.update();
      if (stopGame === false) {
          frame=requestAnimationFrame(start);
      }
    }

function stop(){
  if(frame) {
     console.log("asdfas");
     cancelAnimationFrame(frame);
     stopGame = true;
  }
}


问:
How to swipe to dismiss a DialogFragment in android
I set this View.OnTouchListener on my DialogFragment's layout:

```<code>public class SwipeDismissTouchListener implements View.OnTouchListener {
    // Cached ViewConfiguration and system-wide constant values
    private int mSlop;
    private int mMinFlingVelocity;
    private int mMaxFlingVelocity;
    private long mAnimationTime;

    // Fixed properties
    private View mView;
    private DismissCallbacks mCallbacks;
    private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero

    // Transient properties
    private float mDownX;
    private float mDownY;
    private boolean mSwiping;
    private int mSwipingSlop;
    private Object mToken;
    private VelocityTracker mVelocityTracker;
    private float mTranslationX;

    private boolean mWasMoved;

    /**
     * The callback interface used by {@link SwipeDismissTouchListener} to inform its client
     * about a successful dismissal of the view for which it was created.
     */
    public interface DismissCallbacks {
        /**
         * Called to determine whether the view can be dismissed.
         */
        boolean canDismiss(Object token);

        /**
         * Called when the user has indicated they she would like to dismiss the view.
         *
         * @param view  The originating {@link View} to be dismissed.
         * @param token The optional token passed to this object's constructor.
         */
        void onDismiss(View view, Object token);
    }

    /**
     * Constructs a new swipe-to-dismiss touch listener for the given view.
     *
     * @param view     The view to make dismissable.
     * @param token    An optional token/cookie object to be passed through to the callback.
     * @param callbacks The callback to trigger when the user has indicated that she would like to
     *                 dismiss this view.
     */
    public SwipeDismissTouchListener(View view, Object token, DismissCallbacks callbacks) {
        ViewConfiguration vc = ViewConfiguration.get(view.getContext());
        mSlop = vc.getScaledTouchSlop();
        mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
        mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
        mAnimationTime = view.getContext().getResources().getInteger(
                android.R.integer.config_shortAnimTime);
        mView = view;
        mToken = token;
        mCallbacks = callbacks;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        // offset because the view is translated during swipe
        motionEvent.offsetLocation(mTranslationX, 0);

        if (mViewWidth < 2) {
            mViewWidth = mView.getWidth();
        }

        switch (motionEvent.getActionMasked()) {
            case MotionEvent.ACTION_DOWN: {
                // TODO: ensure this is a finger, and set a flag
                mDownX = motionEvent.getRawX();
                mDownY = motionEvent.getRawY();
                if (mCallbacks.canDismiss(mToken)) {
                    mVelocityTracker = VelocityTracker.obtain();
                    mVelocityTracker.addMovement(motionEvent);
                }
                break;
            }

            case MotionEvent.ACTION_UP: {
                if (mVelocityTracker == null) {
                    break;
                }

                float deltaX = motionEvent.getRawX() - mDownX;
                mVelocityTracker.addMovement(motionEvent);
                mVelocityTracker.computeCurrentVelocity(1000);
                float velocityX = mVelocityTracker.getXVelocity();
                float absVelocityX = Math.abs(velocityX);
                float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
                boolean dismiss = false;
                boolean dismissRight = false;
                if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
                    dismiss = true;
                    dismissRight = deltaX > 0;
                } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
                        && absVelocityY < absVelocityX
                        && absVelocityY < absVelocityX && mSwiping) {
                    // dismiss only if flinging in the same direction as dragging
                    dismiss = (velocityX < 0) == (deltaX < 0);
                    dismissRight = mVelocityTracker.getXVelocity() > 0;
                }
                if (dismiss) {
                    // dismiss
                    mView.animate()
                            .translationX(dismissRight ? mViewWidth : -mViewWidth)
                            .alpha(0)
                            .setDuration(mAnimationTime)
                            .setListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    performDismiss();
                                }
                            });
                    return true;
                } else if (mSwiping) {
                    // cancel
                    mView.animate()
                            .translationX(0)
                            .alpha(1)
                            .setDuration(mAnimationTime)
                            .setListener(null);
                }
                mVelocityTracker.recycle();
                mVelocityTracker = null;
                mTranslationX = 0;
                mDownX = 0;
                mDownY = 0;
                mSwiping = false;
                break;
            }

            case MotionEvent.ACTION_CANCEL: {
                if (mVelocityTracker == null) {
                    break;
                }

                mView.animate()
                        .translationX(0)
                        .alpha(1)
                        .setDuration(mAnimationTime)
                        .setListener(null);
                mVelocityTracker.recycle();
                mVelocityTracker = null;
                mTranslationX = 0;
                mDownX = 0;
                mDownY = 0;
                mSwiping = false;
                break;
            }

            case MotionEvent.ACTION_MOVE: {
                if (mVelocityTracker == null) {
                    break;
                }

                mVelocityTracker.addMovement(motionEvent);
                float deltaX = motionEvent.getRawX() - mDownX;
                float deltaY = motionEvent.getRawY() - mDownY;
                if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
                    mSwiping = true;
                    mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
                    mView.getParent().requestDisallowInterceptTouchEvent(true);

                    // Cancel listview's touch
                    MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
                            (motionEvent.getActionIndex() <<
                                    MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    mView.onTouchEvent(cancelEvent);
                    cancelEvent.recycle();
                }

                if (mSwiping) {
                    mTranslationX = deltaX;
                    mView.setTranslationX(deltaX - mSwipingSlop);
                    // TODO: use an ease-out interpolator or such
                    mView.setAlpha(Math.max(0f, Math.min(1f,
                            1f - 2f * Math.abs(deltaX) / mViewWidth)));
                    return true;
                }
                break;
            }
        }
        return false;
    }

    private void performDismiss() {
        // Animate the dismissed view to zero-height and then fire the dismiss callback.
        // This triggers layout on each animation frame; in the future we may want to do something
        // smarter and more performant.

        final ViewGroup.LayoutParams lp = mView.getLayoutParams();
        final int originalHeight = mView.getHeight();

        ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mCallbacks.onDismiss(mView, mToken);
                // Reset view presentation
                mView.setAlpha(1f);
                mView.setTranslationX(0);
                lp.height = originalHeight;
                mView.setLayoutParams(lp);
            }
        });

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                lp.height = (Integer) valueAnimator.getAnimatedValue();
                mView.setLayoutParams(lp);
            }
        });

        animator.start();
    }
}
</code>```

And I've used it before on EditTexts and it's worked, but I'm not getting the expected behavior with DialogFragments. What's happening with the DialogFragments is that when I swipe it, the layout begins to animate as expected, but not the underlying window that my layout is placed in. Here is what it looks like:

As you can see, my layout is dismissing, but only in the context of the underlying layout that it is in. I thought that when a layout was created, my layout's root was the root of the view, but in this case it seems to be something different; something that I can't get access to to set an View.OnTouchListener on.
Any idea on what I need to do in order to get the expected behavior?

答:
this works for me!</p>

```<code>    WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
    layoutParams.copyFrom(mDialog.getWindow().getAttributes());
    layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
    layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
    layoutParams.gravity = Gravity.CENTER;
    mDialog.getWindow().setAttributes(layoutParams);
    root.setOnTouchListener(new SwipeDismissTouchListener(mDialog.getWindow().getDecorView(),
            null, new SwipeDismissTouchListener.DismissCallbacks() {
        @Override
        public boolean canDismiss(Object token) {
            return true;
        }

        @Override
        public void onDismiss(View view, Object token) {
            dismiss();
        }
    }));
</code>```

Body:
I set this View.OnTouchListener on my DialogFragment's layout:

public class SwipeDismissTouchListener implements View.OnTouchListener {
    // Cached ViewConfiguration and system-wide constant values
    private int mSlop;
    private int mMinFlingVelocity;
    private int mMaxFlingVelocity;
    private long mAnimationTime;

    // Fixed properties
    private View mView;
    private DismissCallbacks mCallbacks;
    private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero

    // Transient properties
    private float mDownX;
    private float mDownY;
    private boolean mSwiping;
    private int mSwipingSlop;
    private Object mToken;
    private VelocityTracker mVelocityTracker;
    private float mTranslationX;

    private boolean mWasMoved;

    /**
     * The callback interface used by {@link SwipeDismissTouchListener} to inform its client
     * about a successful dismissal of the view for which it was created.
     */
    public interface DismissCallbacks {
        /**
         * Called to determine whether the view can be dismissed.
         */
        boolean canDismiss(Object token);

        /**
         * Called when the user has indicated they she would like to dismiss the view.
         *
         * @param view  The originating {@link View} to be dismissed.
         * @param token The optional token passed to this object's constructor.
         */
        void onDismiss(View view, Object token);
    }

    /**
     * Constructs a new swipe-to-dismiss touch listener for the given view.
     *
     * @param view     The view to make dismissable.
     * @param token    An optional token/cookie object to be passed through to the callback.
     * @param callbacks The callback to trigger when the user has indicated that she would like to
     *                 dismiss this view.
     */
    public SwipeDismissTouchListener(View view, Object token, DismissCallbacks callbacks) {
        ViewConfiguration vc = ViewConfiguration.get(view.getContext());
        mSlop = vc.getScaledTouchSlop();
        mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
        mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
        mAnimationTime = view.getContext().getResources().getInteger(
                android.R.integer.config_shortAnimTime);
        mView = view;
        mToken = token;
        mCallbacks = callbacks;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        // offset because the view is translated during swipe
        motionEvent.offsetLocation(mTranslationX, 0);

        if (mViewWidth < 2) {
            mViewWidth = mView.getWidth();
        }

        switch (motionEvent.getActionMasked()) {
            case MotionEvent.ACTION_DOWN: {
                // TODO: ensure this is a finger, and set a flag
                mDownX = motionEvent.getRawX();
                mDownY = motionEvent.getRawY();
                if (mCallbacks.canDismiss(mToken)) {
                    mVelocityTracker = VelocityTracker.obtain();
                    mVelocityTracker.addMovement(motionEvent);
                }
                break;
            }

            case MotionEvent.ACTION_UP: {
                if (mVelocityTracker == null) {
                    break;
                }

                float deltaX = motionEvent.getRawX() - mDownX;
                mVelocityTracker.addMovement(motionEvent);
                mVelocityTracker.computeCurrentVelocity(1000);
                float velocityX = mVelocityTracker.getXVelocity();
                float absVelocityX = Math.abs(velocityX);
                float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
                boolean dismiss = false;
                boolean dismissRight = false;
                if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
                    dismiss = true;
                    dismissRight = deltaX > 0;
                } else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
                        && absVelocityY < absVelocityX
                        && absVelocityY < absVelocityX && mSwiping) {
                    // dismiss only if flinging in the same direction as dragging
                    dismiss = (velocityX < 0) == (deltaX < 0);
                    dismissRight = mVelocityTracker.getXVelocity() > 0;
                }
                if (dismiss) {
                    // dismiss
                    mView.animate()
                            .translationX(dismissRight ? mViewWidth : -mViewWidth)
                            .alpha(0)
                            .setDuration(mAnimationTime)
                            .setListener(new AnimatorListenerAdapter() {
                                @Override
                                public void onAnimationEnd(Animator animation) {
                                    performDismiss();
                                }
                            });
                    return true;
                } else if (mSwiping) {
                    // cancel
                    mView.animate()
                            .translationX(0)
                            .alpha(1)
                            .setDuration(mAnimationTime)
                            .setListener(null);
                }
                mVelocityTracker.recycle();
                mVelocityTracker = null;
                mTranslationX = 0;
                mDownX = 0;
                mDownY = 0;
                mSwiping = false;
                break;
            }

            case MotionEvent.ACTION_CANCEL: {
                if (mVelocityTracker == null) {
                    break;
                }

                mView.animate()
                        .translationX(0)
                        .alpha(1)
                        .setDuration(mAnimationTime)
                        .setListener(null);
                mVelocityTracker.recycle();
                mVelocityTracker = null;
                mTranslationX = 0;
                mDownX = 0;
                mDownY = 0;
                mSwiping = false;
                break;
            }

            case MotionEvent.ACTION_MOVE: {
                if (mVelocityTracker == null) {
                    break;
                }

                mVelocityTracker.addMovement(motionEvent);
                float deltaX = motionEvent.getRawX() - mDownX;
                float deltaY = motionEvent.getRawY() - mDownY;
                if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
                    mSwiping = true;
                    mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
                    mView.getParent().requestDisallowInterceptTouchEvent(true);

                    // Cancel listview's touch
                    MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
                            (motionEvent.getActionIndex() <<
                                    MotionEvent.ACTION_POINTER_INDEX_SHIFT));
                    mView.onTouchEvent(cancelEvent);
                    cancelEvent.recycle();
                }

                if (mSwiping) {
                    mTranslationX = deltaX;
                    mView.setTranslationX(deltaX - mSwipingSlop);
                    // TODO: use an ease-out interpolator or such
                    mView.setAlpha(Math.max(0f, Math.min(1f,
                            1f - 2f * Math.abs(deltaX) / mViewWidth)));
                    return true;
                }
                break;
            }
        }
        return false;
    }

    private void performDismiss() {
        // Animate the dismissed view to zero-height and then fire the dismiss callback.
        // This triggers layout on each animation frame; in the future we may want to do something
        // smarter and more performant.

        final ViewGroup.LayoutParams lp = mView.getLayoutParams();
        final int originalHeight = mView.getHeight();

        ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);

        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mCallbacks.onDismiss(mView, mToken);
                // Reset view presentation
                mView.setAlpha(1f);
                mView.setTranslationX(0);
                lp.height = originalHeight;
                mView.setLayoutParams(lp);
            }
        });

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                lp.height = (Integer) valueAnimator.getAnimatedValue();
                mView.setLayoutParams(lp);
            }
        });

        animator.start();
    }
}

And I've used it before on EditTexts and it's worked, but I'm not getting the expected behavior with DialogFragments. What's happening with the DialogFragments is that when I swipe it, the layout begins to animate as expected, but not the underlying window that my layout is placed in. Here is what it looks like:

As you can see, my layout is dismissing, but only in the context of the underlying layout that it is in. I thought that when a layout was created, my layout's root was the root of the view, but in this case it seems to be something different; something that I can't get access to to set an View.OnTouchListener on.
Any idea on what I need to do in order to get the expected behavior?

Body:
this works for me!

    WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
    layoutParams.copyFrom(mDialog.getWindow().getAttributes());
    layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
    layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
    layoutParams.gravity = Gravity.CENTER;
    mDialog.getWindow().setAttributes(layoutParams);
    root.setOnTouchListener(new SwipeDismissTouchListener(mDialog.getWindow().getDecorView(),
            null, new SwipeDismissTouchListener.DismissCallbacks() {
        @Override
        public boolean canDismiss(Object token) {
            return true;
        }

        @Override
        public void onDismiss(View view, Object token) {
            dismiss();
        }
    }));


问:
Is a function definition an object?
Say I have an object and a function definition:

```<code>var jane = {
    firstName: 'Jane',
    lastName: 'Smith',
    describe: function () {
        return 'Person named '+this.firstName+this.lastName
    },
};

function Car (desc) {
    this.desc = desc;
    this.color = "red";
    this.getInfo = function getInfo() {
        return 'A ' + this.color + ' ' + this.desc + '.';
    };
}
</code>```

I can enumerate over the object's key:value pairs thus:

```<code>obj=jane
for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}
</code>```

but this fails for the function definition (same for function expression)

```<code>obj=Car.....
</code>```

If a function definition is an object then why can't I enumerate over it's properties? Is there a way do to it?

Thanks

答:
You are correct that a function definition is an object, but what you are trying to achieve is iterate over something which is declared inside of that function, which is impossible (imagine trying to iterate over a function's local variables - seems silly, and you have a kind of similar concept). You can always try

```<code>obj = new Car("dummy");
</code>```

which would iterate over the object returned by the function. Without calling new there is no way of accessing these properties from the outside.

Notice that these properties are not properties defined on the function object. They are properties of an object returned by that function. So JavaScript would need some new syntax for this, because using a simple for .. in loop would be a breaking change.

Title: Is a function definition an object?

Body:
Say I have an object and a function definition:

var jane = {
    firstName: 'Jane',
    lastName: 'Smith',
    describe: function () {
        return 'Person named '+this.firstName+this.lastName
    },
};

function Car (desc) {
    this.desc = desc;
    this.color = "red";
    this.getInfo = function getInfo() {
        return 'A ' + this.color + ' ' + this.desc + '.';
    };
}

I can enumerate over the object's key:value pairs thus:

obj=jane
for (var prop in obj) {
  console.log(`obj.${prop} = ${obj[prop]}`);
}

but this fails for the function definition (same for function expression)

obj=Car.....

If a function definition is an object then why can't I enumerate over it's properties? Is there a way do to it?

Thanks

Body:
You are correct that a function definition is an object, but what you are trying to achieve is iterate over something which is declared inside of that function, which is impossible (imagine trying to iterate over a function's local variables - seems silly, and you have a kind of similar concept). You can always try

obj = new Car("dummy");

which would iterate over the object returned by the function. Without calling new there is no way of accessing these properties from the outside.

Notice that these properties are not properties defined on the function object. They are properties of an object returned by that function. So JavaScript would need some new syntax for this, because using a simple for .. in loop would be a breaking change.


问:
Dropdownlist SelectedItemChanged Event in MVC4 Razor?
Is there any event available for Dropdownlist like onChange, etc. in MVC4? Do we have to use Javascript/jQuery in order to make some manipulations like DropwowlistSelectedItemChanged, etc? Or there is a way only using the Razor or MVC4 features?

On the other hand, could you please give me some examples how can I retrieve data and change a label's text with this data according to a Dropdownlist Selected Value? For example when selecting a City from Dropdownlist, I want to get an address data from database by using the selected city id and then show retrieved address on a label. I would be appreciated if you clarify me about the issue above and give me an example to achieve this.

Controller:

```<code>private void PopulateMeetingsDropDownList(object selectedMeetings = null)
    {
        var meetingsQuery = repository.Meetings
            .Join(repository.Cities, m => m.MeetingCityId, c => c.CityID,
                (m, c) => new
                {
                    CityID = c.CityID,
                    CityName = c.CityName,
                    MeetingDate = m.MeetingStartDate
                }
            )
            .OrderBy(x => x.CityID)
            .AsEnumerable()
            .Select(
                i => new
                {
                    CityID = i.CityID,
                    DisplayValue = string.Format(
                        "{0} ({1:dd MMMM yyyy})",
                        i.CityName, i.MeetingDate)
                }
            ).ToList();
        ViewData["MeetingId"] = new SelectList(meetingsQuery, "CityID", "DisplayValue", selectedMeetings);
    }
</code>```

View:

```<code><label>Meeting</label>
@Html.DropDownListFor(m => m.MeetingId, ViewData["MeetingId"] as SelectList,"---- Select ----", new { name = "meetingId", id = "meetingId"})
</code>```

答:
You must use onchange property in a new {} side of declaring class property like this example

@Html.DropDownListFor(model => model.IpoId, new SelectList(Model.IpoList, "Value", "Text", Model.IpoId), "--انتخاب کنید--", new {@class = "chzn-select chzn-rtl", @onchange = "IpoFilterOnChange();" })]

Body:
Is there any event available for Dropdownlist like onChange, etc. in MVC4? Do we have to use Javascript/jQuery in order to make some manipulations like DropwowlistSelectedItemChanged, etc? Or there is a way only using the Razor or MVC4 features?

On the other hand, could you please give me some examples how can I retrieve data and change a label's text with this data according to a Dropdownlist Selected Value? For example when selecting a City from Dropdownlist, I want to get an address data from database by using the selected city id and then show retrieved address on a label. I would be appreciated if you clarify me about the issue above and give me an example to achieve this.

Controller:

private void PopulateMeetingsDropDownList(object selectedMeetings = null)
    {
        var meetingsQuery = repository.Meetings
            .Join(repository.Cities, m => m.MeetingCityId, c => c.CityID,
                (m, c) => new
                {
                    CityID = c.CityID,
                    CityName = c.CityName,
                    MeetingDate = m.MeetingStartDate
                }
            )
            .OrderBy(x => x.CityID)
            .AsEnumerable()
            .Select(
                i => new
                {
                    CityID = i.CityID,
                    DisplayValue = string.Format(
                        "{0} ({1:dd MMMM yyyy})",
                        i.CityName, i.MeetingDate)
                }
            ).ToList();
        ViewData["MeetingId"] = new SelectList(meetingsQuery, "CityID", "DisplayValue", selectedMeetings);
    }

View:

Meeting
@Html.DropDownListFor(m => m.MeetingId, ViewData["MeetingId"] as SelectList,"---- Select ----", new { name = "meetingId", id = "meetingId"})


问:
FLEX:How to catch 'a href' event
I'm loading data from TextFlow to spark:TextArea. In TextFlow i have 'a href' elements. Problem lies with the address of the 'link' elements. Some of them will go outside of the page (these i will leave without doing anything), other will go to other subpages in my site(these one i have to catch and process in code).

I planned on catching 'clicking on link' event to decide what to do, but i can't do this. I read that by writing

```<code><a href="event:page_adress">
</code>```

i could catch the event on link:event in old mx:TextArea, but i cant do this here. I tried to manualy add:

```<code>addEventListener(TextEvent.Link, functionName)
</code>```

but it doesnt work.
When i change to catching MOUSE_CLICK event i'm catching the event, but cant parse it to get the needed address.

Anybody have idea how to do it? I doesnt have to stick with TextArea, but component have to download content form TextFlow.

PS I noticed that when i added event:page_adress to the 'a href' the link stopped working (that means it probably started throwing events), but i cant catch it...

PS2 TextFlow is imported from external database with

```<code>TextFlowUtil.importFromXML
</code>```

i tried using in link element, click event but it doesnt work:

```<code><a click="myClickHandler(event)">
</code>```

myClickHandler doesnt run after clicking on link...

答:
just found out how to get the original string:

```<code>function onClick(event:FlowElementMouseEvent):void
{
    var link:LinkElement = event.flowElement as LinkElement;
    var text:String = link.href;
}
</code>```

this will return the content of the  tag, so you can parse to get your parameters

thanks for the post, it helped me a
  lot. at least i got one step further,
  i can actually listen to the events.

but i still have a problem, the HTML
  code i set on my RichEditableText
  looks like this:

```<code><a href='event:n," + id + "'>Name</a>
</code>```

on Flex3 i could use the
  TextEvent.LINK get the arguments by
  its 'text' property, then parse to get
  the ID data that i need. but now that
  we are developing in Flex4 i cannot
  figure out how to do this. after
  catching the FlowElementMouseEvent i
  can only get the link text ('Name'),
  but not the  arguments im sending on
  the HTML code.

do you have any suggestions on how to
  do this?

Title: FLEX:How to catch 'a href' event

Body:
I'm loading data from TextFlow to spark:TextArea. In TextFlow i have 'a href' elements. Problem lies with the address of the 'link' elements. Some of them will go outside of the page (these i will leave without doing anything), other will go to other subpages in my site(these one i have to catch and process in code).

I planned on catching 'clicking on link' event to decide what to do, but i can't do this. I read that by writing

i could catch the event on link:event in old mx:TextArea, but i cant do this here. I tried to manualy add:

addEventListener(TextEvent.Link, functionName)

but it doesnt work.
When i change to catching MOUSE_CLICK event i'm catching the event, but cant parse it to get the needed address.

Anybody have idea how to do it? I doesnt have to stick with TextArea, but component have to download content form TextFlow.

PS I noticed that when i added event:page_adress to the 'a href' the link stopped working (that means it probably started throwing events), but i cant catch it...

PS2 TextFlow is imported from external database with

TextFlowUtil.importFromXML

i tried using in link element, click event but it doesnt work:

myClickHandler doesnt run after clicking on link...

Body:
just found out how to get the original string:

function onClick(event:FlowElementMouseEvent):void
{
    var link:LinkElement = event.flowElement as LinkElement;
    var text:String = link.href;
}

this will return the content of the  tag, so you can parse to get your parameters

thanks for the post, it helped me a
  lot. at least i got one step further,
  i can actually listen to the events.

but i still have a problem, the HTML
  code i set on my RichEditableText
  looks like this:

<a href='event:n," + id + "'>Name</a>

on Flex3 i could use the
  TextEvent.LINK get the arguments by
  its 'text' property, then parse to get
  the ID data that i need. but now that
  we are developing in Flex4 i cannot
  figure out how to do this. after
  catching the FlowElementMouseEvent i
  can only get the link text ('Name'),
  but not the  arguments im sending on
  the HTML code.

do you have any suggestions on how to
  do this?