问:
iCalendar YEARLY rrule without BYMONTH value
I am building something that takes an icalendar event and calculate all occurrences of a repeating event.

I have discovered a problem which returns me a few YEARLY events every month.
Those event has a yearly frequency but only have bymonthday without bymonth value.

Is this specified in the RFC-5545 or is this just a bug from my calendar tool. (PS: This is actually in my Google Calendar and this event displays correctly there)

```<code>BEGIN:VEVENT
DTSTART;VALUE=DATE:20110814
DTEND;VALUE=DATE:20110815
RRULE:FREQ=YEARLY;BYMONTHDAY=14
DTSTAMP:20170328T223152Z
UID:388B4AE8602346DAA7BD9C1906FC390200000000000000000000000000000000
CREATED:20110610T073603Z
DESCRIPTION:
LAST-MODIFIED:20160811T230008Z
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Some BDAY
TRANSP:OPAQUE
CATEGORIES:http://schemas.google.com/g/2005#event
BEGIN:VALARM
ACTION:AUDIO
TRIGGER:-P1DT15H
ACKNOWLEDGED:20160811T230006Z
ATTACH;VALUE=URI:Basso
UID:26C6C0F7-8B77-4E20-8EFD-E82A614B0751
X-WR-ALARMUID:26C6C0F7-8B77-4E20-8EFD-E82A614B0751
END:VALARM
BEGIN:VALARM
ACTION:NONE
TRIGGER;VALUE=DATE-TIME:19760401T005545Z
END:VALARM
END:VEVENT
</code>```

答:
In the RFC 5545 - page 44 to be exact - the BYMONTHDAY is specified to expand a yearly rule, i.e. to generate more results that only 1 per year.

Furthermore on the next page it gives an example of how a rrule must be evaluated:

```<code>DTSTART;TZID=America/New_York:19970105T083000
</code>```

```<code>  RRULE:FREQ=YEARLY;INTERVAL=2;BYMONTH=1;BYDAY=SU;BYHOUR=8,9;
  BYMINUTE=30
</code>```

First, the "INTERVAL=2" would be applied to "FREQ=YEARLY" to
arrive at "every other year".  Then, "BYMONTH=1" would be applied
to arrive at "every January, every other year".  Then, "BYDAY=SU"
would be applied to arrive at "every Sunday in January, every
other year".  Then, "BYHOUR=8,9" would be applied to arrive at
"every Sunday in January at 8 AM and 9 AM, every other year".
Then, "BYMINUTE=30" would be applied to arrive at "every Sunday in
January at 8:30 AM and 9:30 AM, every other year".

As you can see, even if FREQ is YEARLY, the rule will return "every Sunday in January at 8AM and 9AM, every other year", i.e. much more than 1 occurrence every two year. That is in a nutshell the concept of expanding the behavior of FREQ.

Now applying to this rule:

RRULE:FREQ=YEARLY;BYMONTHDAY=14

It means "every 14th of the month, every year". So you will get 12 occurrences per year.

Edit: That being said, after re-reading the RFC, the definition of BYMONTHDAY is:

The BYMONTHDAY rule part specifies a COMMA-separated list of days of the month.

This could be interpreted as "list of days of the month" as in "only the month specified by DTSTART property". However this interpretation does not make sense with other values of FREQ (MONTHLY, DAILY, etc.), so that would be a special case only for FREQ=YEARLY and BYMONTH is missing... Personally I do not believe it is correct, but I must admit the RFC is slightly ambiguous.

Unfortunately there isn't any example of BYMONTHDAY with FREQ=YEARLY without BYMONTH, so there is no clear definite answer

Conclusion: To avoid any problem you should add a BYMONTH if you want only "the 14th of a given month".

Answer to your comment

The rule "FREQ=MONTHLY;BYMONTHDAY=14" indeed produces the same result. The differences would appear with INTERVAL greater than 1, or other BYxxx.

Body:
I am building something that takes an icalendar event and calculate all occurrences of a repeating event.

I have discovered a problem which returns me a few YEARLY events every month.
Those event has a yearly frequency but only have bymonthday without bymonth value.

Is this specified in the RFC-5545 or is this just a bug from my calendar tool. (PS: This is actually in my Google Calendar and this event displays correctly there)

BEGIN:VEVENT
DTSTART;VALUE=DATE:20110814
DTEND;VALUE=DATE:20110815
RRULE:FREQ=YEARLY;BYMONTHDAY=14
DTSTAMP:20170328T223152Z
UID:388B4AE8602346DAA7BD9C1906FC390200000000000000000000000000000000
CREATED:20110610T073603Z
DESCRIPTION:
LAST-MODIFIED:20160811T230008Z
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Some BDAY
TRANSP:OPAQUE
CATEGORIES:http://schemas.google.com/g/2005#event
BEGIN:VALARM
ACTION:AUDIO
TRIGGER:-P1DT15H
ACKNOWLEDGED:20160811T230006Z
ATTACH;VALUE=URI:Basso
UID:26C6C0F7-8B77-4E20-8EFD-E82A614B0751
X-WR-ALARMUID:26C6C0F7-8B77-4E20-8EFD-E82A614B0751
END:VALARM
BEGIN:VALARM
ACTION:NONE
TRIGGER;VALUE=DATE-TIME:19760401T005545Z
END:VALARM
END:VEVENT

Body:
In the RFC 5545 - page 44 to be exact - the BYMONTHDAY is specified to expand a yearly rule, i.e. to generate more results that only 1 per year.

Furthermore on the next page it gives an example of how a rrule must be evaluated:

DTSTART;TZID=America/New_York:19970105T083000

  RRULE:FREQ=YEARLY;INTERVAL=2;BYMONTH=1;BYDAY=SU;BYHOUR=8,9;
  BYMINUTE=30

First, the "INTERVAL=2" would be applied to "FREQ=YEARLY" to
arrive at "every other year".  Then, "BYMONTH=1" would be applied
to arrive at "every January, every other year".  Then, "BYDAY=SU"
would be applied to arrive at "every Sunday in January, every
other year".  Then, "BYHOUR=8,9" would be applied to arrive at
"every Sunday in January at 8 AM and 9 AM, every other year".
Then, "BYMINUTE=30" would be applied to arrive at "every Sunday in
January at 8:30 AM and 9:30 AM, every other year".

As you can see, even if FREQ is YEARLY, the rule will return "every Sunday in January at 8AM and 9AM, every other year", i.e. much more than 1 occurrence every two year. That is in a nutshell the concept of expanding the behavior of FREQ.

Now applying to this rule:

RRULE:FREQ=YEARLY;BYMONTHDAY=14

It means "every 14th of the month, every year". So you will get 12 occurrences per year.

Edit: That being said, after re-reading the RFC, the definition of BYMONTHDAY is:

The BYMONTHDAY rule part specifies a COMMA-separated list of days of the month.

This could be interpreted as "list of days of the month" as in "only the month specified by DTSTART property". However this interpretation does not make sense with other values of FREQ (MONTHLY, DAILY, etc.), so that would be a special case only for FREQ=YEARLY and BYMONTH is missing... Personally I do not believe it is correct, but I must admit the RFC is slightly ambiguous.

Unfortunately there isn't any example of BYMONTHDAY with FREQ=YEARLY without BYMONTH, so there is no clear definite answer

Conclusion: To avoid any problem you should add a BYMONTH if you want only "the 14th of a given month".

Answer to your comment

The rule "FREQ=MONTHLY;BYMONTHDAY=14" indeed produces the same result. The differences would appear with INTERVAL greater than 1, or other BYxxx.


来源: stackexchange

问:
Expanding and calling backend Service in UI-Grid
I have a UI Grid configured for my site. I have used expandableRowTemplate to expand it to show some simple content when user clicks on the expand button. Right now it shows the content properly.

But my requirement is when user user clicks on the expand button apart from expanding and showing the content it should also call a backend service to send some data to server and receive something.

Is this scenario possible in UI Grid? I am using Angular 1.5 and Ui Grid 4.0.1.

答:
There's public API event which is fired when a row is toggled.
You can provide a function calling the REST service to this event.

```<code>   gridApi.expandable.on.rowExpandedStateChanged(scope,function(row){})
</code>```

And if you want to make a call only if the row is expanded, I see only 2 ways:

Either you have your own one redundant key to each row as row.isExpanded and toggle it inside this function and use for your purpose.

Or you can find if row inside this function is included in getExpandedRows()'s result. This is hilariously redundant.

Source: http://ui-grid.info/docs/#/api/ui.grid.expandable.api:PublicApi

ContentLicense: CC BY-SA 3.0

Body:
There's public API event which is fired when a row is toggled.
You can provide a function calling the REST service to this event.

   gridApi.expandable.on.rowExpandedStateChanged(scope,function(row){})

And if you want to make a call only if the row is expanded, I see only 2 ways:

Either you have your own one redundant key to each row as row.isExpanded and toggle it inside this function and use for your purpose.

Or you can find if row inside this function is included in getExpandedRows()'s result. This is hilariously redundant.

Source: http://ui-grid.info/docs/#/api/ui.grid.expandable.api:PublicApi


问:
Is it possible to test whether a C define is declared in a gnu Makefile?
I want to include different directories in my build based on whether a #define is declared in a .h file in my project.  Is this possible or am I going about this completely wrong?</p>

答: Yes you are. The build system is supposed to configure the code, not vice-versa. You should use a configure script for this kind of options (or probably switch to a higher build system: autotools, CMake, QMake...).</p>

ContentLicense: CC BY-SA 2.5


问:
Aligning table cells using height
I am trying to align some table cells to an image by setting the height of each row. Sadly it does not seem to work properly, as it does not use the whole percentage for the rows. The table should be 725px high with each cell evenly spread out, but it is not. How can I ensure that they are spread out evenly?

https://jsfiddle.net/hpL127zr/1/

I am setting the height like this.

```<code>tr {
  height: 2.8571428571429%;

}
</code>```

I know I could use height out, but this will allow the rows to become to high if the text is to long (multi line).

答:
There is only 35 column in the table from your fiddle and the percentage you're using correspond to 40 column.

So just add :

```<code><tr><td>lala</td></tr>
<tr><td>lala</td></tr>
<tr><td>lala</td></tr>
<tr><td>lala</td></tr>
<tr><td>lala</td></tr>
</code>```

And with 40 column it seems to be working perfectly.

https://jsfiddle.net/hpL127zr/2/

Title: Aligning table cells using height

Body:
I am trying to align some table cells to an image by setting the height of each row. Sadly it does not seem to work properly, as it does not use the whole percentage for the rows. The table should be 725px high with each cell evenly spread out, but it is not. How can I ensure that they are spread out evenly?

https://jsfiddle.net/hpL127zr/1/

I am setting the height like this.

tr {
  height: 2.8571428571429%;

}

I know I could use height out, but this will allow the rows to become to high if the text is to long (multi line).

Body:
There is only 35 column in the table from your fiddle and the percentage you're using correspond to 40 column.

So just add :

<tr><td>lala</td></tr>
<tr><td>lala</td></tr>
<tr><td>lala</td></tr>
<tr><td>lala</td></tr>
<tr><td>lala</td></tr>

And with 40 column it seems to be working perfectly.

https://jsfiddle.net/hpL127zr/2/


问:
What is this thumbnail icon on mobile chrome and how to use it in my website
I don't know what this icon is called and how to use it for my website. Can someone help me out.

答:
It's called favicon. Somewhere you should have a code like this:

<link rel="icon" type="image/png" href="/favicon.png" />```

Follow the href to the location. You can find it in your header somewhere.

Body:
It's called favicon. Somewhere you should have a code like this:

<link rel="icon" type="image/png" href="/favicon.png" />

Follow the href to the location. You can find it in your header somewhere.


答: It is possible, but you are going about this the wrong way. The way to include different directories is with different make targets. If your code has to know about them, use -D in your compiler switches. Alternatively, if your build needs to be able to run on other people's systems, something like autoconf is the way to go.

Title: Is it possible to test whether a C define is declared in a gnu Makefile?

Body: I want to include different directories in my build based on whether a #define is declared in a .h file in my project.  Is this possible or am I going about this completely wrong?


问:
Getting a particular subset of methods from a Python class
I have read other posts in Stack Overflow that answer this question, but I am interested in a specific subset of methods.

Suppose you have a class Cn with n higher than 1, as well as classes C0, C1, ..., Cn-1 such that, for each i between 1 and n-1, class Ci+1 inherits from class Ci.

My question is: for any i higher than 1, how can I obtain the list of methods that belong to Ci but not to Ci-1?

答:
You can find all names defined on the class itself in the __dict__ attribute of a class; you can use the vars() function to list those more succinctly:

```<code>from types import FunctionType

for name, object in vars(Ci).items():
    if isinstance(object, FunctionType):
        print(name, 'is defined on Ci directly and not inherited')
</code>```

You may need to vary the test for functions; I'm assuming here you only want plain function objects (which are bound into methods when looked up on the instance), but you may need to test for class or static methods or other callables too, depending on your use-case.

This will include names that have been re-defined; so these exist on the parent too but Ci provides a new implementation that masks that of a parent.

If you must find all names that uniquely belong to Ci and no parent provides, you'll have to filter on names that exist on the bases:

```<code>parent_defined = set().union(*(dir(b) for b in Ci.__bases__))

for name, object in vars(Ci).items():
    if name not in parent_defined and isinstance(object, FunctionType):
        print(name, 'is defined on Ci directly and not inherited')
</code>```

Body:
You can find all names defined on the class itself in the __dict__ attribute of a class; you can use the vars() function to list those more succinctly:

from types import FunctionType

for name, object in vars(Ci).items():
    if isinstance(object, FunctionType):
        print(name, 'is defined on Ci directly and not inherited')

You may need to vary the test for functions; I'm assuming here you only want plain function objects (which are bound into methods when looked up on the instance), but you may need to test for class or static methods or other callables too, depending on your use-case.

This will include names that have been re-defined; so these exist on the parent too but Ci provides a new implementation that masks that of a parent.

If you must find all names that uniquely belong to Ci and no parent provides, you'll have to filter on names that exist on the bases:

parent_defined = set().union(*(dir(b) for b in Ci.__bases__))

for name, object in vars(Ci).items():
    if name not in parent_defined and isinstance(object, FunctionType):
        print(name, 'is defined on Ci directly and not inherited')


问:
Redirect from PHP page is it wasn't included or required
I have a set of PHP files that I am including and using as templates for information that I am storing in a MYSQL Database. These files can be accessed with the link to them. I do not want these files to be accessed if they are not being loaded by another file.

For example:
I have a file called errorBox.php which should only be visible when included in mainPage.php. However, currently, by going to http://myUrl.com/errorBox.php I can access the page.

I have tried using the following:

```<code>header("Location: http://myUrl.com");
</code>```

but unfortunately it doesn't seem to work.

Is there a way to redirect automatically from these pages if they have not been included? Or is there a different solution to my problem?

Thank you in advance.

答:
May you can check if was included/required using the get_included_files function.

And if was not included/required, you can redirect:

```<code>header('Location: http://myurl.com');
die;
</code>```

Use die after to stop execute things.

Body:
I have a set of PHP files that I am including and using as templates for information that I am storing in a MYSQL Database. These files can be accessed with the link to them. I do not want these files to be accessed if they are not being loaded by another file.

For example:
I have a file called errorBox.php which should only be visible when included in mainPage.php. However, currently, by going to http://myUrl.com/errorBox.php I can access the page.

I have tried using the following:

header("Location: http://myUrl.com");

but unfortunately it doesn't seem to work.

Is there a way to redirect automatically from these pages if they have not been included? Or is there a different solution to my problem?

Thank you in advance.

Body:
May you can check if was included/required using the get_included_files function.

And if was not included/required, you can redirect:

header('Location: http://myurl.com');
die;

Use die after to stop execute things.


问:
What is the XPATH of following web element?
I want to find the XPATH of the following element. I want to click on 'Next' hyperlink. Any help would be appreciated.</p>

```<code>  <span class="inputtextfields"> <Previous  <a accesskey="n" href="javascript:ButtonClickFunction('NEXT' , 1, 'bulkpayments.jsp')">Next</a>> </span>
</code>```

答:
Try the following XPath:</p>

```<code>driver.findElement(by.xpath("//span[@class='inputtextfields']").click();
</code>```

Body:
I want to find the XPATH of the following element. I want to click on 'Next' hyperlink. Any help would be appreciated.

   <Previous  Next>

Body:
Try the following XPath:

driver.findElement(by.xpath("//span[@class='inputtextfields']").click();


问:
layout-small not being recognized/not working
I made a layout-small xml file to fit smaller screen sizes for my activity. I was told that if you create a folder, named layout-small(with the XML inside it, of course) inside the res folder, android would recognize that the phones screen size is small and would automatically use the layout-small XML file.

I used the 3.2" HVGA Slider AVD to test the program, but it still used the normal layout. I hope this make sense, as I couldn't find another question similar to this.

If you need any additonal information or have any questions, let me know.
Thanks.

答:
According to this page your AVD device has a screen size of "normal", so you will not pick up the definition for "small".

Device Definitions

The platform includes the following device definitions for use in creating Android Virtual Devices in the AVD Manager:

...

• 3.2" HVGA slider ADP1 (320 x 480, Normal mdpi screen)

If you want to target your AVD with a different layout, take a look at ways to specify an alternative.


问:
Can't bind data to src attribute of img tag in a jhipster - angular 2 project
I've changed from raw-loader to html-loader as the issue: https://github.com/jhipster/generator-jhipster/issues/5333

then it works if I code as below:

```<code> <div class="img">
            <img src="../../content/images/lotto-euro1.png" alt="Logo here"/>
            <p>{{imgSrc}} here </p>
    </div>
</code>```

When I bind data to src as below, it doesn't work.

```<code>this.imgSrc = "../../content/images/lotto-euro1.png";

<div class="img">
    <img src={{imgSrc}} alt="Logo here"/>
    <p>{{imgSrc}} here </p>
</div>
</code>```

or

```<code><div class="img">
                <img [src]="imgSrc" alt="Logo here"/>
                <p>{{imgSrc}} here </p>
            </div>
</code>```

Many thanks for any help.

答: Try to change src={{imgSrc}} to src="{{imgSrc}}" in the first case or [src] to [attr.src] in the second case. If it doesn't work, give us an html code of the img.

Body:
I've changed from raw-loader to html-loader as the issue: https://github.com/jhipster/generator-jhipster/issues/5333

then it works if I code as below:

{{imgSrc}} here

When I bind data to src as below, it doesn't work.

this.imgSrc = "../../content/images/lotto-euro1.png";

{{imgSrc}} here

or

{{imgSrc}} here

Many thanks for any help.


问:
Need to open fancybox content on page scroll instead of click somewhere
I am using fancybox. Here it fancybox will display on clicking somewhere but i need to display after page scroll. Now i am looking for fancybox. Anyone can suggest me any plugin like fancybox with scrolling not clicking.

Now i have tried with fancybox so here is code of fancybox. But you can help me with any plugin.

$(document).ready(function() {
  $(".fancybox").fancybox();
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.css" rel="stylesheet"/>

 <img src="http://farm9.staticflickr.com/8140/30366640446_eb359921c5_m.jpg" alt="" />
</code>```

答:
One simple way to stay with your fancybox plugin would be to trigger a click on a image on scroll.</p>

```<code>$(window).one('scroll', function(){
     $('img').trigger("click")
})
</code>```

Body:
I am using fancybox. Here it fancybox will display on clicking somewhere but i need to display after page scroll. Now i am looking for fancybox. Anyone can suggest me any plugin like fancybox with scrolling not clicking.

Now i have tried with fancybox so here is code of fancybox. But you can help me with any plugin.

$(document).ready(function() {
  $(".fancybox").fancybox();
 });

<link href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.css" rel="stylesheet"/>

Body:
One simple way to stay with your fancybox plugin would be to trigger a click on a image on scroll.

$(window).one('scroll', function(){
     $('img').trigger("click")
})


问:
How to get data from database to view page in laravel?
I am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).

Here is the code of my project:

HTML:

```<code><div class="table-responsive">
  <table class="table table-striped table-hover table-condensed">
    <thead>
      <tr>
        <th><strong>No</strong></th>
        <th><strong>Nama Petani</strong></th>
        <th><strong>Alamat</strong></th>
        <th><strong>No. Handphone</strong></th>
        <th><strong>Lokasi</strong></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
      </tr>
    </tbody>
  </table>
</div>
</code>```

PHP:
In my listpetani.blade.php I have an empty table and I want to show data from  database tbl_user:

```<code>Route::get('listpetani', function () {

  $petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');

  return view('listpetani', ['petani' => $petani]);

});
</code>```

And the table in my page: view in browser

I want to show all the data from database into my view in laravel 5.4. Can anybody help me?

答:
```<code>@foreach($petani as $p)
 <tr>
     <td>{{ $p['id_user'] }}</td>
     <td>{{ $p['username'] }}</td>
     <td>{{ $p['alamat'] }}</td>
     <td>{{ $p['no_telp'] }}</td>
     <td>{{ $p['id_lokasi'] }}</td>
 </tr>
@endforeach
</code>```

Body:
I am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).

Here is the code of my project:

HTML:

        No
        Nama Petani
        Alamat
        No. Handphone
        Lokasi

PHP:
In my listpetani.blade.php I have an empty table and I want to show data from  database tbl_user:

Route::get('listpetani', function () {

  $petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');

  return view('listpetani', ['petani' => $petani]);

});

And the table in my page: view in browser

I want to show all the data from database into my view in laravel 5.4. Can anybody help me?


问:
Mod Rewrite does not work when URI folder not exist
http://site.loc/ works fine

http://site.loc/books not working

.htaccess URL Rewrite failing on localhost with a 404 error

The requested URL /books was not found on this server

I just reinstalled Sierra and setup PHP & Apache, and facing above error, here is my simple .htaccess:

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?!=$1 [QSA,L]
</code>```

Here is the CustomLog

```<code>localhost - - [26/Mar/2017:21:30:08 +0300] "GET /books/ HTTP/1.1" 404 204
</code>```

NOTE same .htaccess is working right now in production without issues, and it has worked on another local environment before.

Tried 1:

```<code>RewriteEngine On
RewriteBase /
</code>```

Tried 2:

```<code>RewriteEngine On
Options +FollowSymlinks
RewriteBase /
RewriteRule ^.htaccess$ - [F]
</code>```

Also changed this in httpd.conf

```<code>ServerName localhost:80
<Directory />
    AllowOverride All
    Require all granted
</Directory>
</code>```

and also rewrite_module is enabled

Please share your thoughts ;) what I am missing here? thanks in advance.

答:
The problem is fixed by adding following Directory directive in vhosts.conf

```<code><Directory "/path/to/site">
    Options All
    AllowOverride All
    Allow from all
</Directory>
</code>```

To see how the full VirtualHost directive looks, follow the screenshot below ;)

Body:
http://site.loc/ works fine

http://site.loc/books not working

.htaccess URL Rewrite failing on localhost with a 404 error

The requested URL /books was not found on this server

I just reinstalled Sierra and setup PHP & Apache, and facing above error, here is my simple .htaccess:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?!=$1 [QSA,L]

Here is the CustomLog

localhost - - [26/Mar/2017:21:30:08 +0300] "GET /books/ HTTP/1.1" 404 204

NOTE same .htaccess is working right now in production without issues, and it has worked on another local environment before.

Tried 1:

RewriteEngine On
RewriteBase /

Tried 2:

RewriteEngine On
Options +FollowSymlinks
RewriteBase /
RewriteRule ^.htaccess$ - [F]

Also changed this in httpd.conf

ServerName localhost:80
<Directory />
    AllowOverride All
    Require all granted
</Directory>

and also rewrite_module is enabled

Please share your thoughts ;) what I am missing here? thanks in advance.

Body:
The problem is fixed by adding following Directory directive in vhosts.conf

<Directory "/path/to/site">
    Options All
    AllowOverride All
    Allow from all
</Directory>

To see how the full VirtualHost directive looks, follow the screenshot below ;)


问:
Access is Always Denied in Spring Security - DenyAllPermissionEvaluator
I have configured ACL in my Spring Boot application. The ACL configuration is as follows:

```<code>@Configuration
@ComponentScan(basePackages = "com.company")
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class ACLConfigration extends GlobalMethodSecurityConfiguration {

    @Autowired
    DataSource dataSource;

    @Bean
    public EhCacheBasedAclCache aclCache() {
        return new EhCacheBasedAclCache(aclEhCacheFactoryBean().getObject(), permissionGrantingStrategy(), aclAuthorizationStrategy());
    }

    @Bean
    public EhCacheFactoryBean aclEhCacheFactoryBean() {
        EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean();
        ehCacheFactoryBean.setCacheManager(aclCacheManager().getObject());
        ehCacheFactoryBean.setCacheName("aclCache");
        return ehCacheFactoryBean;
    }

    @Bean
    public EhCacheManagerFactoryBean aclCacheManager() {
        return new EhCacheManagerFactoryBean();
    }

    @Bean
    public DefaultPermissionGrantingStrategy permissionGrantingStrategy() {
        ConsoleAuditLogger consoleAuditLogger = new ConsoleAuditLogger();
        return new DefaultPermissionGrantingStrategy(consoleAuditLogger);
    }

    @Bean
    public AclAuthorizationStrategy aclAuthorizationStrategy() {
        return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ACL_ADMIN"));
    }

    @Bean
    public LookupStrategy lookupStrategy() {
        return new BasicLookupStrategy(dataSource, aclCache(), aclAuthorizationStrategy(), new ConsoleAuditLogger());
    }

    @Bean
    public JdbcMutableAclService aclService() {
        return new JdbcMutableAclService(dataSource, lookupStrategy(), aclCache());
    }

    @Bean
    public DefaultMethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler() {
        return new DefaultMethodSecurityExpressionHandler();
    }

    @Override
    public MethodSecurityExpressionHandler createExpressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler = defaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(new AclPermissionEvaluator(aclService()));
        expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService()));
        return expressionHandler;
    }
}
</code>```

References:

SO Q1

SO Q2

and the security configuration is as follows:

```<code>@Configuration
@EnableWebSecurity
public class CustomSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public AuthenticationEntryPoint entryPoint() {
        return new LoginUrlAuthenticationEntryPoint("/authenticate");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/authenticate/**").permitAll()
                .anyRequest().fullyAuthenticated()
                .and().requestCache().requestCache(new NullRequestCache())
                .and().addFilterBefore(authenticationFilter(), CustomUsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
    }

    @Bean
    public CustomUsernamePasswordAuthenticationFilter authenticationFilter()
            throws Exception {
        CustomUsernamePasswordAuthenticationFilter authenticationFilter = new CustomUsernamePasswordAuthenticationFilter();
        authenticationFilter.setUsernameParameter("username");
        authenticationFilter.setPasswordParameter("password");
        authenticationFilter.setFilterProcessesUrl("/authenticate");
        authenticationFilter.setAuthenticationSuccessHandler(new CustomAuthenticationSuccessHandler());
        authenticationFilter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler());
        authenticationFilter.setAuthenticationManager(authenticationManagerBean());
        return authenticationFilter;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
</code>```

My CustomAuthenticationProvider class:

```<code>@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UsersService usersService;

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        User user = usersService.findOne(username);

        if(user != null && usersService.comparePassword(user, password)){

            return new UsernamePasswordAuthenticationToken(
                    user.getUsername(),
                    user.getPassword(),
                    AuthorityUtils.commaSeparatedStringToAuthorityList(
                            user.getUserRoles().stream().collect(Collectors.joining(","))));
        } else {
            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
</code>```

Here's my CustomUsernamePasswordAuthenticationToken:

```<code>public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        if(!request.getMethod().equals("POST"))
            throw new AuthenticationServiceException(String.format("Authentication method not supported: %s", request.getMethod()));

        try {

            CustomUsernamePasswordAuthenticationForm form = new ObjectMapper().readValue(request.getReader(), CustomUsernamePasswordAuthenticationForm.class);

            String username = form.getUsername();
            String password = form.getPassword();

            if(username == null)
                username = "";

            if(password == null)
                password = "";

            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);

            setDetails(request, token);

            return getAuthenticationManager().authenticate(token);

        } catch (IOException exception) {
            throw new CustomAuthenticationException(exception);
        }
    }

    private class CustomAuthenticationException extends RuntimeException {
        private CustomAuthenticationException(Throwable throwable) {
            super(throwable);
        }
    }
}
</code>```

Apart from the above, I have CustomAuthenticationFailureHandler, CustomAuthenticationSuccessHandler, CustomNoRedirectStrategy and CustomUsernamePasswordAuthenticationForm which I skipped for the sake of this question's length.

And I am using MySQL schema that can be found here.

I am adding entries to my acl related tables as follows:

```<code>INSERT INTO acl_class VALUES (1, com.company.project.domain.users.User)
INSERT INTO acl_sid VALUES (1, 1, "demo")
</code>```

(I have a user with username demo)

```<code>INSERT INTO acl_object_identity VALUES (1, 1, 1, NULL, 1, 0)
INSERT INTO acl_entry VALUES (1, 1, 1, 1, 1, 1, 1, 1)
</code>```

But all I am getting is:

```<code>Denying user demo permission 'READ' on object com.company.project.domain.users.User@4a49e9b4
</code>```

in my

```<code>@PostFilter("hasPermission(filterObject, 'READ')")
</code>```

I am suspecting of several issues here:

The hasPermission expression: I have substituted it with 'READ' and '1', but to no extent.

My database entries are not right

I am not implementing a custom permission evaluator. Is this required, or is expressionHandler.setPermissionEvaluator(new AclPermissionEvaluator(aclService())); enough?

Update

Sample method where @PostFilter is used:

```<code>@RequestMapping(method = RequestMethod.GET)
    @PostFilter("hasPermission(filterObject, 'READ')")
    List<User> find(@Min(0) @RequestParam(value = "limit", required = false, defaultValue = "10") Integer limit,
                    @Min(0) @RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                    @RequestParam(value = "email", required = false) String email,
                    @RequestParam(value = "firstName", required = false) String firstName,
                    @RequestParam(value = "lastName", required = false) String lastName,
                    @RequestParam(value = "userRole", required = false) String userRole) {

        return usersService.find(
                limit,
                page,
                email,
                firstName,
                lastName,
                userRole);
    }
</code>```

Update #2:

The question now reflects everything set up in regards to authentication/authorization/ACL.

Update #3:

I am now very close to resolve the issue, the only thing left is to resolve this:

https://stackoverflow.com/questions/42996579/custom-permissionevaluator-not-called-although-set-as-permissionevaluator-deny

If anyone could help me with that question, I can finally have a write up of what I have went through to resolve this.

答:
Here's the long waited answer:

The documentation clearly describes:

To use hasPermission() expressions, you have to explicitly configure a
  PermissionEvaluator in your application context. This would look
  something like this:

so basically I was doing in my AclConfiguration which extends GlobalMethodSecurityConfiguration:

```<code>    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(new AclPermissionEvaluator(aclService()));
        expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService()));
        return expressionHandler;
    }
</code>```

Which was not getting processed by Spring!

I had to separate AclConfig and GlobalMethodSecurityConfiguration. When there are @Beans defined in the latter, the above method is not getting processed, which might be a bug (if not, any clarification on subject is welcome).

Body:
I have configured ACL in my Spring Boot application. The ACL configuration is as follows:

@Configuration
@ComponentScan(basePackages = "com.company")
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class ACLConfigration extends GlobalMethodSecurityConfiguration {

    @Autowired
    DataSource dataSource;

    @Bean
    public EhCacheBasedAclCache aclCache() {
        return new EhCacheBasedAclCache(aclEhCacheFactoryBean().getObject(), permissionGrantingStrategy(), aclAuthorizationStrategy());
    }

    @Bean
    public EhCacheFactoryBean aclEhCacheFactoryBean() {
        EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean();
        ehCacheFactoryBean.setCacheManager(aclCacheManager().getObject());
        ehCacheFactoryBean.setCacheName("aclCache");
        return ehCacheFactoryBean;
    }

    @Bean
    public EhCacheManagerFactoryBean aclCacheManager() {
        return new EhCacheManagerFactoryBean();
    }

    @Bean
    public DefaultPermissionGrantingStrategy permissionGrantingStrategy() {
        ConsoleAuditLogger consoleAuditLogger = new ConsoleAuditLogger();
        return new DefaultPermissionGrantingStrategy(consoleAuditLogger);
    }

    @Bean
    public AclAuthorizationStrategy aclAuthorizationStrategy() {
        return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ACL_ADMIN"));
    }

    @Bean
    public LookupStrategy lookupStrategy() {
        return new BasicLookupStrategy(dataSource, aclCache(), aclAuthorizationStrategy(), new ConsoleAuditLogger());
    }

    @Bean
    public JdbcMutableAclService aclService() {
        return new JdbcMutableAclService(dataSource, lookupStrategy(), aclCache());
    }

    @Bean
    public DefaultMethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler() {
        return new DefaultMethodSecurityExpressionHandler();
    }

    @Override
    public MethodSecurityExpressionHandler createExpressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler = defaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(new AclPermissionEvaluator(aclService()));
        expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService()));
        return expressionHandler;
    }
}

References:

SO Q1

SO Q2

and the security configuration is as follows:

@Configuration
@EnableWebSecurity
public class CustomSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public AuthenticationEntryPoint entryPoint() {
        return new LoginUrlAuthenticationEntryPoint("/authenticate");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/authenticate/**").permitAll()
                .anyRequest().fullyAuthenticated()
                .and().requestCache().requestCache(new NullRequestCache())
                .and().addFilterBefore(authenticationFilter(), CustomUsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
    }

    @Bean
    public CustomUsernamePasswordAuthenticationFilter authenticationFilter()
            throws Exception {
        CustomUsernamePasswordAuthenticationFilter authenticationFilter = new CustomUsernamePasswordAuthenticationFilter();
        authenticationFilter.setUsernameParameter("username");
        authenticationFilter.setPasswordParameter("password");
        authenticationFilter.setFilterProcessesUrl("/authenticate");
        authenticationFilter.setAuthenticationSuccessHandler(new CustomAuthenticationSuccessHandler());
        authenticationFilter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler());
        authenticationFilter.setAuthenticationManager(authenticationManagerBean());
        return authenticationFilter;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

My CustomAuthenticationProvider class:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UsersService usersService;

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        User user = usersService.findOne(username);

        if(user != null && usersService.comparePassword(user, password)){

            return new UsernamePasswordAuthenticationToken(
                    user.getUsername(),
                    user.getPassword(),
                    AuthorityUtils.commaSeparatedStringToAuthorityList(
                            user.getUserRoles().stream().collect(Collectors.joining(","))));
        } else {
            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

Here's my CustomUsernamePasswordAuthenticationToken:

public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        if(!request.getMethod().equals("POST"))
            throw new AuthenticationServiceException(String.format("Authentication method not supported: %s", request.getMethod()));

        try {

            CustomUsernamePasswordAuthenticationForm form = new ObjectMapper().readValue(request.getReader(), CustomUsernamePasswordAuthenticationForm.class);

            String username = form.getUsername();
            String password = form.getPassword();

            if(username == null)
                username = "";

            if(password == null)
                password = "";

            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);

            setDetails(request, token);

            return getAuthenticationManager().authenticate(token);

        } catch (IOException exception) {
            throw new CustomAuthenticationException(exception);
        }
    }

    private class CustomAuthenticationException extends RuntimeException {
        private CustomAuthenticationException(Throwable throwable) {
            super(throwable);
        }
    }
}

Apart from the above, I have CustomAuthenticationFailureHandler, CustomAuthenticationSuccessHandler, CustomNoRedirectStrategy and CustomUsernamePasswordAuthenticationForm which I skipped for the sake of this question's length.

And I am using MySQL schema that can be found here.

I am adding entries to my acl related tables as follows:

INSERT INTO acl_class VALUES (1, com.company.project.domain.users.User)
INSERT INTO acl_sid VALUES (1, 1, "demo")

(I have a user with username demo)

INSERT INTO acl_object_identity VALUES (1, 1, 1, NULL, 1, 0)
INSERT INTO acl_entry VALUES (1, 1, 1, 1, 1, 1, 1, 1)

But all I am getting is:

Denying user demo permission 'READ' on object com.company.project.domain.users.User@4a49e9b4

in my

@PostFilter("hasPermission(filterObject, 'READ')")

I am suspecting of several issues here:

The hasPermission expression: I have substituted it with 'READ' and '1', but to no extent.

My database entries are not right

I am not implementing a custom permission evaluator. Is this required, or is expressionHandler.setPermissionEvaluator(new AclPermissionEvaluator(aclService())); enough?

Update

Sample method where @PostFilter is used:

@RequestMapping(method = RequestMethod.GET)
    @PostFilter("hasPermission(filterObject, 'READ')")
    List<User> find(@Min(0) @RequestParam(value = "limit", required = false, defaultValue = "10") Integer limit,
                    @Min(0) @RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                    @RequestParam(value = "email", required = false) String email,
                    @RequestParam(value = "firstName", required = false) String firstName,
                    @RequestParam(value = "lastName", required = false) String lastName,
                    @RequestParam(value = "userRole", required = false) String userRole) {

        return usersService.find(
                limit,
                page,
                email,
                firstName,
                lastName,
                userRole);
    }

Update #2:

The question now reflects everything set up in regards to authentication/authorization/ACL.

Update #3:

I am now very close to resolve the issue, the only thing left is to resolve this:

https://stackoverflow.com/questions/42996579/custom-permissionevaluator-not-called-although-set-as-permissionevaluator-deny

If anyone could help me with that question, I can finally have a write up of what I have went through to resolve this.

Body:
Here's the long waited answer:

The documentation clearly describes:

To use hasPermission() expressions, you have to explicitly configure a
  PermissionEvaluator in your application context. This would look
  something like this:

so basically I was doing in my AclConfiguration which extends GlobalMethodSecurityConfiguration:

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(new AclPermissionEvaluator(aclService()));
        expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService()));
        return expressionHandler;
    }

Which was not getting processed by Spring!

I had to separate AclConfig and GlobalMethodSecurityConfiguration. When there are @Beans defined in the latter, the above method is not getting processed, which might be a bug (if not, any clarification on subject is welcome).


问:
How to make a regular expression 'greedy but optional'
I'm trying to write a parser for a string which represents a file path, optionally following by a colon (:) and a string representing access flags (e.g. r+ or w). The file name can itself contain colons, e.g., foo:bar.txt, so the colon separating the access flags should be the last colon in the string.

Here is my implementation so far:

```<code>import re

def parse(string):
    SCHEME = r"file://"                             # File prefix
    PATH_PATTERN = r"(?P<path>.+)"                  # One or more of any character
    FLAGS_PATTERN = r"(?P<flags>.+)"        # The letters r, w, a, b, a '+' symbol, or any digit

    # FILE_RESOURCE_PATTERN = SCHEME + PATH_PATTERN + r":" + FLAGS_PATTERN + r"$"               # This makes the first test pass, but the second one fail
    FILE_RESOURCE_PATTERN = SCHEME + PATH_PATTERN + optional(r":" + FLAGS_PATTERN) + r"$"   # This makes the second test pass, but the first one fail

    tokens = re.match(FILE_RESOURCE_PATTERN, string).groupdict()

    return tokens['path'], tokens['flags']

def optional(re):
    '''Encloses the given regular expression in a group which matches 0 or 1 repetitions.'''
    return '({})?'.format(re)
</code>```

I've tried the following tests:

```<code>import pytest

def test_parse_file_with_colon_in_file_name():
    assert parse("file://foo:bar.txt:r+") == ("foo:bar.txt", "r+")

def test_parse_file_without_acesss_flags():
    assert parse("file://foobar.txt") == ("foobar.txt", None)

if __name__ == "__main__":
    pytest.main([__file__])
</code>```

The problem is that by either using or not using optional, I can make one or the other test pass, but not both. If I make r":" + FLAGS_PATTERN optional, then preceding regular expression consumes the entire string.

How can I adapt the parse method to make both tests pass?

答:
Just for fun, I wrote this parse function, which I think is better than using RE?</p>

```<code>def parse(string):
    s = string.split('//')[-1]
    try:
        path, flags = s.rsplit(':', 1)
    except ValueError:
        path, flags = s.rsplit(':', 1)[0], None
    return path, flags
</code>```

Body:
I'm trying to write a parser for a string which represents a file path, optionally following by a colon (:) and a string representing access flags (e.g. r+ or w). The file name can itself contain colons, e.g., foo:bar.txt, so the colon separating the access flags should be the last colon in the string.

Here is my implementation so far:

import re

def parse(string):
    SCHEME = r"file://"                             # File prefix
    PATH_PATTERN = r"(?P<path>.+)"                  # One or more of any character
    FLAGS_PATTERN = r"(?P<flags>.+)"        # The letters r, w, a, b, a '+' symbol, or any digit

    # FILE_RESOURCE_PATTERN = SCHEME + PATH_PATTERN + r":" + FLAGS_PATTERN + r"$"               # This makes the first test pass, but the second one fail
    FILE_RESOURCE_PATTERN = SCHEME + PATH_PATTERN + optional(r":" + FLAGS_PATTERN) + r"$"   # This makes the second test pass, but the first one fail

    tokens = re.match(FILE_RESOURCE_PATTERN, string).groupdict()

    return tokens['path'], tokens['flags']

def optional(re):
    '''Encloses the given regular expression in a group which matches 0 or 1 repetitions.'''
    return '({})?'.format(re)

I've tried the following tests:

import pytest

def test_parse_file_with_colon_in_file_name():
    assert parse("file://foo:bar.txt:r+") == ("foo:bar.txt", "r+")

def test_parse_file_without_acesss_flags():
    assert parse("file://foobar.txt") == ("foobar.txt", None)

if __name__ == "__main__":
    pytest.main([__file__])

The problem is that by either using or not using optional, I can make one or the other test pass, but not both. If I make r":" + FLAGS_PATTERN optional, then preceding regular expression consumes the entire string.

How can I adapt the parse method to make both tests pass?

Body:
Just for fun, I wrote this parse function, which I think is better than using RE?

def parse(string):
    s = string.split('//')[-1]
    try:
        path, flags = s.rsplit(':', 1)
    except ValueError:
        path, flags = s.rsplit(':', 1)[0], None
    return path, flags


问:
How do I use CSS transitions when adding elements in Elm?
Simple scenario is I have a button that fetches some data from an API and adds the data to a list.

I would like to apply a CSS transition of the opacity property for the newly added item so it fades in as its added to the list.

Usually this is done by having a default CSS class with opacity: 0; and a transition rule. Then after the element is added you apply another CSS class to it with opacity: 1; and you get a fade in effect.

How do you do this with Elm?

This is how list items are added to the view right now,

ul [ class "list" ] (List.map (\item -> li [] [ text item ]) model.items)

答:
What Amir said is really the only thing you need to add. Elm will work with that just fine.

If you run into any issues, you might try to use Html.Keyed package, which should get rid of bugs with ordering / adding / deleting - you just use Html.Keyed.ul, which expects children to be not Html msg but (String, Html msg). So typically you'd have some kind of ID for the row element. (Edit: for example adding to front of the list would seem as adding to back with this code. See here for updated example.)

So, to expand on Amir's answer with some Elm code (Ellie link):

```<code>module Main exposing (..)

import Html as H exposing (Html)
import Html.Events as HE

type alias Model =
    { rows : List String }

type Msg
    = AddText

main : Program Never Model Msg
main =
    H.beginnerProgram
        { model = model
        , update = update
        , view = view
        }

model : Model
model =
    { rows = [] }

update : Msg -> Model -> Model
update msg model =
    case msg of
        AddText ->
            { model | rows = model.rows ++ [ "Another row" ] }

view : Model -> Html Msg
view model =
    H.div []
        [ H.button [ HE.onClick AddText ] [ H.text "add new row" ]
        , H.ul [] (List.map viewRow model.rows)
        ]

viewRow : String -> Html Msg
viewRow row =
    H.li [] [ H.text row ]
</code>```

And the accompanying HTML (see the CSS):

```<code><html>
<head>
  <style>
    html {
      background: #F7F7F7;
      color: red;
    }
    li {
      animation: fadein 2s;
    }

    @keyframes fadein {
        from { opacity: 0; }
        to   { opacity: 1; }
    }
  </style>
</head>
<body>
  <script>
    var app = Elm.Main.fullscreen()
  </script>
</body>
</html>
</code>```

Body:
What Amir said is really the only thing you need to add. Elm will work with that just fine.

If you run into any issues, you might try to use Html.Keyed package, which should get rid of bugs with ordering / adding / deleting - you just use Html.Keyed.ul, which expects children to be not Html msg but (String, Html msg). So typically you'd have some kind of ID for the row element. (Edit: for example adding to front of the list would seem as adding to back with this code. See here for updated example.)

So, to expand on Amir's answer with some Elm code (Ellie link):

module Main exposing (..)

import Html as H exposing (Html)
import Html.Events as HE

type alias Model =
    { rows : List String }

type Msg
    = AddText

main : Program Never Model Msg
main =
    H.beginnerProgram
        { model = model
        , update = update
        , view = view
        }

model : Model
model =
    { rows = [] }

update : Msg -> Model -> Model
update msg model =
    case msg of
        AddText ->
            { model | rows = model.rows ++ [ "Another row" ] }

view : Model -> Html Msg
view model =
    H.div []
        [ H.button [ HE.onClick AddText ] [ H.text "add new row" ]
        , H.ul [] (List.map viewRow model.rows)
        ]

viewRow : String -> Html Msg
viewRow row =
    H.li [] [ H.text row ]

And the accompanying HTML (see the CSS):

<html>
<head>
  <style>
    html {
      background: #F7F7F7;
      color: red;
    }
    li {
      animation: fadein 2s;
    }

    @keyframes fadein {
        from { opacity: 0; }
        to   { opacity: 1; }
    }
  </style>
</head>
<body>
  <script>
    var app = Elm.Main.fullscreen()
  </script>
</body>
</html>


问:
What does the .size on number mean in ruby?
Why is my ruby giving incorrect size of number?  It doesn't matter what's the number. The output is always 4 for the size. What does that mean? I always thought it should give the number of digits.

```<code>number = 14
print number
print "\n"
print number.size
</code>```

output:

```<code>14
4
</code>```

ruby version

```<code>ruby 2.1.8p440 (2015-12-16 revision 53160) [i386-mingw32]
</code>```

答:
I always suggest to check the method you're not sure about using the following scheme:

Check where the method comes from (using Object#method):

```<code>number.method(:size)
#=> #<Method: Fixnum#size>
</code>```

Open docs and learn what it does for Fixnum#size and how it works.

2.1 If you're using IRB, you can run help 'Fixnum#size' to get the docs right in your console
2.2 If you're using pry, you can go with show-doc Fixnum#size (install pry-doc gem first)

In Ruby 2.1.8 method was defined in Fixnum#size.

Starting from Ruby 2.4 it's defined in
Integer#size:

Returns the number of bytes in the machine representation of int.

Body:
Why is my ruby giving incorrect size of number?  It doesn't matter what's the number. The output is always 4 for the size. What does that mean? I always thought it should give the number of digits.

number = 14
print number
print "\n"
print number.size

output:

14
4

ruby version

ruby 2.1.8p440 (2015-12-16 revision 53160) [i386-mingw32]

Body:
I always suggest to check the method you're not sure about using the following scheme:

Check where the method comes from (using Object#method):

number.method(:size)
#=> #<Method: Fixnum#size>

Open docs and learn what it does for Fixnum#size and how it works.

2.1 If you're using IRB, you can run help 'Fixnum#size' to get the docs right in your console
2.2 If you're using pry, you can go with show-doc Fixnum#size (install pry-doc gem first)

In Ruby 2.1.8 method was defined in Fixnum#size.

Starting from Ruby 2.4 it's defined in
Integer#size:

Returns the number of bytes in the machine representation of int.


问:
What is the best method for integrating an existing database schema into a RoR migration?
So basically I have an existing dump SQL file and I need to integrate it into a new RoR project. So I want to generate the .rb schema file as well as all the classes from the model layer.

How can I do it in Rails 3?

Thank you!

答:
May be
alexrothenberg/legacy_data or  timriley/acts-as-importable github projects will help.

Sorry, I'm new user and can not post links.


问:
vTiger AD authentication
I was trying to authenticate vTiger CRM 6.5 with my existing Active Directory services, but it's not working. Looks like this is getting response from my AD server but not going anywhere. After using correct credential the page will just refresh, but once you enter wrong credential, it says - "wrong username or password". I am using "http://adldap.sourceforge.net/" for AD authentication. And my log says - </p>

```<code>03/28/17 15:24:50,105 [632] DEBUG user - Entering Users() method ...
03/28/17 15:24:50,105 [632] DEBUG VT - Entering getColumnFields(Users) method ...
03/28/17 15:24:50,105 [632] DEBUG VT - in getColumnFields Users
03/28/17 15:24:50,105 [632] DEBUG VT - Prepared sql query being executed : SELECT tabid, name, ownedby FROM vtiger_tab
03/28/17 15:24:50,110 [632] DEBUG VT - Prepared sql query being executed : SELECT tabid, fieldname, fieldid, fieldlabel, columnname, tablename, uitype, typeofdata, presence
        FROM vtiger_field WHERE tabid in (?)
03/28/17 15:24:50,110 [632] DEBUG VT - Prepared sql query parameters : [29]
03/28/17 15:24:50,122 [632] DEBUG VT - Exiting getColumnFields method ...
03/28/17 15:24:50,122 [632] DEBUG user - Exiting Users() method ...
03/28/17 15:24:50,123 [632] DEBUG user - Using Active Directory authentication
03/28/17 15:24:51,361 [632] DEBUG VT - Prepared sql query being executed : SELECT id from vtiger_users where user_name=? AND deleted=0
03/28/17 15:24:51,361 [632] DEBUG VT - Prepared sql query parameters : [pritamkumar]
03/28/17 15:24:51,436 [632] DEBUG VT - Prepared sql query being executed : SELECT * FROM vtiger_tab
03/28/17 15:24:51,448 [632] DEBUG VT - Prepared sql query being executed : SELECT fieldname,modulename,tablename,entityidfield,entityidcolumn from vtiger_entityname
03/28/17 15:24:51,453 [632] DEBUG VT - Prepared sql query being executed : INSERT INTO vtiger_loginhistory (user_name, user_ip, logout_time, login_time, status) VALUES (?,?,?,?,?)
03/28/17 15:24:51,453 [632] DEBUG VT - Prepared sql query parameters : [pritamkumar,::1,0000-00-00 00:00:00,2017-03-28 15:24:51,Signed in]
03/28/17 15:24:51,818 [632] INFO VT - PearDatabase ->ADODB disconnect
03/28/17 15:24:52,438 [632] DEBUG VT - Login is required:#0 E:\xampp\htdocs\vtiger\includes\main\WebUI.php(186): Vtiger_WebUI->checkLogin(Object(Vtiger_Request))
#1 E:\xampp\htdocs\vtiger\index.php(18): Vtiger_WebUI->process(Object(Vtiger_Request))
#2 {main}
03/28/17 15:24:52,653 [632] INFO VT - PearDatabase ->ADODB disconnect
03/28/17 15:24:54,160 [632] INFO VT - PearDatabase ->ADODB disconnect
03/28/17 15:24:55,028 [632] INFO VT - PearDatabase ->ADODB disconnect
</code>```

答:
To test adLDAP, write a small php script than doing it directly with vTiger CRM. Just create adldap_test.php file, in the same directory where adLDAP.php resides, with following content:

```<code><?php

require_once(dirname(FILE) . '/adLDAP.php');

try {
    $adldap = new adLDAP();
} catch (adLDAPException $e) {
    echo $e;
    exit();
}
$authUser = $adldap->authenticate('user-to-authenticate', 'users-password');
if ($authUser == true) {
     echo "User authenticated successfully";
} else {
   // getLastError is not needed, but may be helpful for finding out why:
    echo "\n";
    echo $adldap->getLastError();
    echo "\n";

    echo "User authentication unsuccessful";
}

echo "\n";
$result=$adldap->user()->infoCollection('ldap', array("*"));
echo "User:\n";
echo $result->displayName;
echo "Mail:\n";
echo $result->mail;

?>
</code>```

Replace user and password for the user you want to test authentication for and execute it. It should give success and output the username and mail address if available. Hope this helps you to solve your problem.

Title: vTiger AD authentication

Body:
I was trying to authenticate vTiger CRM 6.5 with my existing Active Directory services, but it's not working. Looks like this is getting response from my AD server but not going anywhere. After using correct credential the page will just refresh, but once you enter wrong credential, it says - "wrong username or password". I am using "http://adldap.sourceforge.net/" for AD authentication. And my log says -

03/28/17 15:24:50,105 [632] DEBUG user - Entering Users() method ...
03/28/17 15:24:50,105 [632] DEBUG VT - Entering getColumnFields(Users) method ...
03/28/17 15:24:50,105 [632] DEBUG VT - in getColumnFields Users
03/28/17 15:24:50,105 [632] DEBUG VT - Prepared sql query being executed : SELECT tabid, name, ownedby FROM vtiger_tab
03/28/17 15:24:50,110 [632] DEBUG VT - Prepared sql query being executed : SELECT tabid, fieldname, fieldid, fieldlabel, columnname, tablename, uitype, typeofdata, presence
        FROM vtiger_field WHERE tabid in (?)
03/28/17 15:24:50,110 [632] DEBUG VT - Prepared sql query parameters : [29]
03/28/17 15:24:50,122 [632] DEBUG VT - Exiting getColumnFields method ...
03/28/17 15:24:50,122 [632] DEBUG user - Exiting Users() method ...
03/28/17 15:24:50,123 [632] DEBUG user - Using Active Directory authentication
03/28/17 15:24:51,361 [632] DEBUG VT - Prepared sql query being executed : SELECT id from vtiger_users where user_name=? AND deleted=0
03/28/17 15:24:51,361 [632] DEBUG VT - Prepared sql query parameters : [pritamkumar]
03/28/17 15:24:51,436 [632] DEBUG VT - Prepared sql query being executed : SELECT * FROM vtiger_tab
03/28/17 15:24:51,448 [632] DEBUG VT - Prepared sql query being executed : SELECT fieldname,modulename,tablename,entityidfield,entityidcolumn from vtiger_entityname
03/28/17 15:24:51,453 [632] DEBUG VT - Prepared sql query being executed : INSERT INTO vtiger_loginhistory (user_name, user_ip, logout_time, login_time, status) VALUES (?,?,?,?,?)
03/28/17 15:24:51,453 [632] DEBUG VT - Prepared sql query parameters : [pritamkumar,::1,0000-00-00 00:00:00,2017-03-28 15:24:51,Signed in]
03/28/17 15:24:51,818 [632] INFO VT - PearDatabase ->ADODB disconnect
03/28/17 15:24:52,438 [632] DEBUG VT - Login is required:#0 E:\xampp\htdocs\vtiger\includes\main\WebUI.php(186): Vtiger_WebUI->checkLogin(Object(Vtiger_Request))
#1 E:\xampp\htdocs\vtiger\index.php(18): Vtiger_WebUI->process(Object(Vtiger_Request))
#2 {main}
03/28/17 15:24:52,653 [632] INFO VT - PearDatabase ->ADODB disconnect
03/28/17 15:24:54,160 [632] INFO VT - PearDatabase ->ADODB disconnect
03/28/17 15:24:55,028 [632] INFO VT - PearDatabase ->ADODB disconnect

Body:
To test adLDAP, write a small php script than doing it directly with vTiger CRM. Just create adldap_test.php file, in the same directory where adLDAP.php resides, with following content:

<?php

require_once(dirname(FILE) . '/adLDAP.php');

try {
    $adldap = new adLDAP();
} catch (adLDAPException $e) {
    echo $e;
    exit();
}
$authUser = $adldap->authenticate('user-to-authenticate', 'users-password');
if ($authUser == true) {
     echo "User authenticated successfully";
} else {
   // getLastError is not needed, but may be helpful for finding out why:
    echo "\n";
    echo $adldap->getLastError();
    echo "\n";

    echo "User authentication unsuccessful";
}

echo "\n";
$result=$adldap->user()->infoCollection('ldap', array("*"));
echo "User:\n";
echo $result->displayName;
echo "Mail:\n";
echo $result->mail;

?>

Replace user and password for the user you want to test authentication for and execute it. It should give success and output the username and mail address if available. Hope this helps you to solve your problem.


问:
Spring MVC @Pathvariable won't work
I have an interface and an implementation class:

Interface

```<code>@RequestMapping(value = CUSTOMER_PATH + "{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON + CHARSET_UTF_8_ENCODING})
    Response getCustomerDetails(@PathVariable(CONTACT_ID) String id);
</code>```

Impl

```<code>@Override
public Response getCustomerDetails(String id) {
    String methodname = "getCustomerDetails: ";
    LOG.info(methodname + "Get Customer Details");

    Response response;
    System.out.println("******************id: " + id);

    if (StringUtils.isEmpty(id)) {
        response = Response.status(Status.BAD_REQUEST).entity(MockData.customerDetailsInvalid).build();
        LOG.info(methodname + "Returning Customer's Details - Status: Invalid Request");
    } else {
        response = Response.status(Status.OK).entity(MockData.customerDetails).build();
        LOG.info(methodname + "Returning Customer's Details - Status: OK");

    }

    return response;
}
</code>```

The path ..../MockDataProvider-war/services/mock/customers/7 returns “invalid request”.
The value for id is printed out as null, even though it should be 7.

Anyone know why id is null?

答:
Reason is @PathVariable(CONTACT_ID)
it should be @PathVariable String id this will work.

Title: Spring MVC @Pathvariable won't work

Body:
I have an interface and an implementation class:

Interface

@RequestMapping(value = CUSTOMER_PATH + "{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON + CHARSET_UTF_8_ENCODING})
    Response getCustomerDetails(@PathVariable(CONTACT_ID) String id);

Impl

@Override
public Response getCustomerDetails(String id) {
    String methodname = "getCustomerDetails: ";
    LOG.info(methodname + "Get Customer Details");

    Response response;
    System.out.println("******************id: " + id);

    if (StringUtils.isEmpty(id)) {
        response = Response.status(Status.BAD_REQUEST).entity(MockData.customerDetailsInvalid).build();
        LOG.info(methodname + "Returning Customer's Details - Status: Invalid Request");
    } else {
        response = Response.status(Status.OK).entity(MockData.customerDetails).build();
        LOG.info(methodname + "Returning Customer's Details - Status: OK");

    }

    return response;
}

The path ..../MockDataProvider-war/services/mock/customers/7 returns “invalid request”.
The value for id is printed out as null, even though it should be 7.

Anyone know why id is null?


问:
How do you override bootstrap.min.css? Django
On my page I have a toolbar which is supposed to be centered in the middle. I have a seperate css sheet which centres it, however it keeps being overriden by the min.css file.

In my body content.css I have:

```<code>.btn-toolbar .btn, .btn-toolbar .btn-group, .btn-toolbar .input-group {
  float:none !important;
}
</code>```

But when I inspect the page via the console it it always shows this in the min.css:

```<code>.btn-toolbar .btn, .btn-toolbar .btn-group, .btn-toolbar .input-group {
  float:left;
}
</code>```

How do I override it?

答:
I don't advice you change bootstrap.min.css . create new class and use it.
for example

```<code>      .my-toolbar {
           float:none !important;
      }
</code>```

Body:
On my page I have a toolbar which is supposed to be centered in the middle. I have a seperate css sheet which centres it, however it keeps being overriden by the min.css file.

In my body content.css I have:

.btn-toolbar .btn, .btn-toolbar .btn-group, .btn-toolbar .input-group {
  float:none !important;
}

But when I inspect the page via the console it it always shows this in the min.css:

.btn-toolbar .btn, .btn-toolbar .btn-group, .btn-toolbar .input-group {
  float:left;
}

How do I override it?

Body:
I don't advice you change bootstrap.min.css . create new class and use it.
for example

      .my-toolbar {
           float:none !important;
      }


问:
How to remove css transitions without delay?
I want a transition a css property smoothly then I want immediate change in css property value and then I want to attach the transition back again. To better understand see the following example:

if ($(".marquee").height() < $(".marquee-content").outerHeight(true)) {
  $(".marquee-content").clone().appendTo($(".marquee-wrapper"));
}
$('.marquee-wrapper').css("transition", "transform 3s linear");
$('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");

setInterval(function() {

  $('.marquee-wrapper').css("transition", "none");
  $('.marquee-wrapper').css("transform", "translateY(100px)"); //This should Immediately change translateY to 100px without smooth transition. But this doesn't happen without adding a delay before the below written line

  // Its weird why javascript engine executes the below line before executing this line

  $('.marquee-wrapper').css("transition", "transform 3s linear");
  $('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");

}, 3000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.marquee {
  margin: auto;
  width: 600px;
  height: 200px;
  overflow: auto;
}

.marquee-wrapper {
  transform: translateY(0);
}

.marquee-content {
  margin: 0;
  padding: 30px 0;
}</code>```

      Updates: Update (8 Mar 2016): Now plugin have new option: startVisible The marquee will be visible in the start if set to true. Thanks to @nuke-ellington ðŸ‘ Update (24 Jan 2014): Note: people who been asking me how to use this plugin with content being
      loaded with Ajax, please read notes about this update. New methods added, so now after you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq
      = $('.marquee').marquee();, then you can pause, resume, togglepause, resume) and desestroy destroy toggle(pause, resume) and destroy toggle(pause, resume) and destroy methods e.g to remove the marquee plugin from your element simply use $mq.marquee('destroy');.
      Similarly you can use pause the marquee any time using $mq.marquee('pause');.

```
</div>
</div>
</p>

<p>As you can see in the setInterval I first set transition to none then translateY to 100px. Now in principle this should suddenly translate the div to 100px but this doesn't happen before moving div to 100px javascript engine executes the next line and reassign transition. In the below example I have given a 100ms delay before reassigning the transition and it works:  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>if ($(".marquee").height() < $(".marquee-content").outerHeight(true)) {
  $(".marquee-content").clone().appendTo($(".marquee-wrapper"));
}
$('.marquee-wrapper').css("transition", "transform 3s linear");
$('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");

setInterval(function() {

  $('.marquee-wrapper').css("transition", "none");
  $('.marquee-wrapper').css("transform", "translateY(100px)"); //This  Immedeately change translateY to 100px without smooth transition now

  setTimeout(function(){
      $('.marquee-wrapper').css("transition", "transform 3s linear");
      $('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");
  },100);
}, 3000);</code>```

.marquee {
  margin: auto;
  width: 600px;
  height: 200px;
  overflow: auto;
}

.marquee-wrapper {
  transform: translateY(0);
}

.marquee-content {
  margin: 0;
  padding: 30px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="marquee">
  <div class="marquee-wrapper">
    <div class="marquee-content">
      Updates: Update (8 Mar 2016): Now plugin have new option: startVisible The marquee will be visible in the start if set to true. Thanks to @nuke-ellington ðŸ‘ Update (24 Jan 2014): Note: people who been asking me how to use this plugin with content being
      loaded with Ajax, please read notes about this update. New methods added, so now after you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq
      = $('.marquee').marquee();, then you can pause, resume, togglepause, resume) and desestroy destroy toggle(pause, resume) and destroy toggle(pause, resume) and destroy methods e.g to remove the marquee plugin from your element simply use $mq.marquee('destroy');.
      Similarly you can use pause the marquee any time using $mq.marquee('pause');.
    </div>
  </div>
</section></code>```

My questions are:

How do I stop javscript engine to reassign transition property before making changing translate property, without any delay?

Why does javscript engine excutes a forthcoming line($('.marquee-wrapper').css("transition", "transform 3s linear");) in script before the current line($('.marquee-wrapper').css("transform", "translateY(100px)");)

答:
I shall explain you why this happens.

I've been dealing with javascript animations, and there are many js libraries (focused on maths) having into account operational delays (I/O availability policies) and timeouts.

In your first code snippet, you have these operations:

```<code>$('.marquee-wrapper').css("transform", "translateY(100px)");
$('.marquee-wrapper').css("transition", "transform 3s linear");
</code>```

Transform

Css Transform method uses matrix based operations which have a high computational cost. There are css-animation frameworks that do use the graphics processor unit (having matrix operators) which works several times faster to achieve smooth, real-time graphic operations.

Transition

Css Transition is another graphical operation, but does not modify the css entity with a pure [matrix op matrix] transformation, it uses a right 1-dimension operator, that means your css matrix is modified with an [matrix op array].

Then the linear mode you choose, applies linear interpolation (probably just a few integration operators) on the position of your element. It has low computational cost, which makes the whole transition operation still faster to compute.

This is a schema of the execution taking place in a sort of timeline:

```<code>transform         calculation-process
exec -----------------------------------------> applied
 |         |                            |        |
 |         |                            |        |
 |         |                            |        |
transition |     calculation-process    |        |
--------- exec ---------------------> applied ---------
</code>```

As jQuery on the top of javascript has non blocking code execution (for i/o depending functions, and unless you code it synch) which is a base of the asynchronous policy of javascript, allows the next operation to execute even before the precedent finishes.

Your fix with the timeout function, ensures that the transform operation is completed before running following code, but as limitation, it will work only for clients with similar computational speed than the current client's processor. (If you develop it in a pc, then it might fail in a smartphone)

Another solution I use in my code is to use the jquery callbacks. Have a look at the jquery animate() doc in which is shown:

.animate( properties [, duration ] [, easing ] [, complete ] )

In your example it would be something like:

```<code>$('.marquee-wrapper').animate({"transform": "translateY(100px)"}, function(){
    // this code runs after transform ends...
    $('.marquee-wrapper').css("transition", "transform 3s linear");
    $('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");
});
</code>```

I found many useful libs around to "seriously" play with animations. These are some of the libs I use:

d3.js

bounce.js

secuence.js

paper.js

I hope it helps.

Update

There is a good SO answer about animate and css transitions here.

Body:
I want a transition a css property smoothly then I want immediate change in css property value and then I want to attach the transition back again. To better understand see the following example:

if ($(".marquee").height() < $(".marquee-content").outerHeight(true)) {
  $(".marquee-content").clone().appendTo($(".marquee-wrapper"));
}
$('.marquee-wrapper').css("transition", "transform 3s linear");
$('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");

setInterval(function() {

  $('.marquee-wrapper').css("transition", "none");
  $('.marquee-wrapper').css("transform", "translateY(100px)"); //This should Immediately change translateY to 100px without smooth transition. But this doesn't happen without adding a delay before the below written line

  // Its weird why javascript engine executes the below line before executing this line

  $('.marquee-wrapper').css("transition", "transform 3s linear");
  $('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");

}, 3000);

.marquee {
  margin: auto;
  width: 600px;
  height: 200px;
  overflow: auto;
}

.marquee-wrapper {
  transform: translateY(0);
}

.marquee-content {
  margin: 0;
  padding: 30px 0;
}

      Updates: Update (8 Mar 2016): Now plugin have new option: startVisible The marquee will be visible in the start if set to true. Thanks to @nuke-ellington ðŸ‘ Update (24 Jan 2014): Note: people who been asking me how to use this plugin with content being
      loaded with Ajax, please read notes about this update. New methods added, so now after you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq
      = $('.marquee').marquee();, then you can pause, resume, togglepause, resume) and desestroy destroy toggle(pause, resume) and destroy toggle(pause, resume) and destroy methods e.g to remove the marquee plugin from your element simply use $mq.marquee('destroy');.
      Similarly you can use pause the marquee any time using $mq.marquee('pause');.

As you can see in the setInterval I first set transition to none then translateY to 100px. Now in principle this should suddenly translate the div to 100px but this doesn't happen before moving div to 100px javascript engine executes the next line and reassign transition. In the below example I have given a 100ms delay before reassigning the transition and it works:

if ($(".marquee").height() < $(".marquee-content").outerHeight(true)) {
  $(".marquee-content").clone().appendTo($(".marquee-wrapper"));
}
$('.marquee-wrapper').css("transition", "transform 3s linear");
$('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");

setInterval(function() {

  $('.marquee-wrapper').css("transition", "none");
  $('.marquee-wrapper').css("transform", "translateY(100px)"); //This  Immedeately change translateY to 100px without smooth transition now

  setTimeout(function(){
      $('.marquee-wrapper').css("transition", "transform 3s linear");
      $('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");
  },100);
}, 3000);

.marquee {
  margin: auto;
  width: 600px;
  height: 200px;
  overflow: auto;
}

.marquee-wrapper {
  transform: translateY(0);
}

.marquee-content {
  margin: 0;
  padding: 30px 0;
}

      Updates: Update (8 Mar 2016): Now plugin have new option: startVisible The marquee will be visible in the start if set to true. Thanks to @nuke-ellington ðŸ‘ Update (24 Jan 2014): Note: people who been asking me how to use this plugin with content being
      loaded with Ajax, please read notes about this update. New methods added, so now after you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq = $('.marquee').marquee();, you start the plugin using var $mq
      = $('.marquee').marquee();, then you can pause, resume, togglepause, resume) and desestroy destroy toggle(pause, resume) and destroy toggle(pause, resume) and destroy methods e.g to remove the marquee plugin from your element simply use $mq.marquee('destroy');.
      Similarly you can use pause the marquee any time using $mq.marquee('pause');.

My questions are:

How do I stop javscript engine to reassign transition property before making changing translate property, without any delay?

Why does javscript engine excutes a forthcoming line($('.marquee-wrapper').css("transition", "transform 3s linear");) in script before the current line($('.marquee-wrapper').css("transform", "translateY(100px)");)

Body:
I shall explain you why this happens.

I've been dealing with javascript animations, and there are many js libraries (focused on maths) having into account operational delays (I/O availability policies) and timeouts.

In your first code snippet, you have these operations:

$('.marquee-wrapper').css("transform", "translateY(100px)");
$('.marquee-wrapper').css("transition", "transform 3s linear");

Transform

Css Transform method uses matrix based operations which have a high computational cost. There are css-animation frameworks that do use the graphics processor unit (having matrix operators) which works several times faster to achieve smooth, real-time graphic operations.

Transition

Css Transition is another graphical operation, but does not modify the css entity with a pure [matrix op matrix] transformation, it uses a right 1-dimension operator, that means your css matrix is modified with an [matrix op array].

Then the linear mode you choose, applies linear interpolation (probably just a few integration operators) on the position of your element. It has low computational cost, which makes the whole transition operation still faster to compute.

This is a schema of the execution taking place in a sort of timeline:

transform         calculation-process
exec -----------------------------------------> applied
 |         |                            |        |
 |         |                            |        |
 |         |                            |        |
transition |     calculation-process    |        |
--------- exec ---------------------> applied ---------

As jQuery on the top of javascript has non blocking code execution (for i/o depending functions, and unless you code it synch) which is a base of the asynchronous policy of javascript, allows the next operation to execute even before the precedent finishes.

Your fix with the timeout function, ensures that the transform operation is completed before running following code, but as limitation, it will work only for clients with similar computational speed than the current client's processor. (If you develop it in a pc, then it might fail in a smartphone)

Another solution I use in my code is to use the jquery callbacks. Have a look at the jquery animate() doc in which is shown:

.animate( properties [, duration ] [, easing ] [, complete ] )

In your example it would be something like:

$('.marquee-wrapper').animate({"transform": "translateY(100px)"}, function(){
    // this code runs after transform ends...
    $('.marquee-wrapper').css("transition", "transform 3s linear");
    $('.marquee-wrapper').css("transform", "translateY(-" + $(".marquee-content").outerHeight(true) + "px)");
});

I found many useful libs around to "seriously" play with animations. These are some of the libs I use:

d3.js

bounce.js

secuence.js

paper.js

I hope it helps.

Update

There is a good SO answer about animate and css transitions here.


问:
Preserving stack trace when rethrowing exceptions in Silverlight
I need to rethrow an Exception that was caught and stored elsewhere without losing the stack trace information about when the Exception was first caught/stored.  My code looks something like this:

```<code>    public void Test()
    {
        int someParameter = 12;
        ExecuteSomeAsyncMethod(someParameter, CallbackMethod);
    }

    public void CallbackMethod(object result, Exception error)
    {
        //Check for exceptions that were previously caught and passed to us
        if(error != null)
            //Throwing like this will lose the stack trace already in Exception
            //We'd like to be able to rethrow it without overwriting the stack trace
            throw error;

        //Success case: Process 'result'...etc...
    }
</code>```

I've seen solutions to this problem that use reflection (for example here and here) or use Serialization (for example here) but none of those will work for me in Silverlight (private reflection is not allowed and the classes/methods used in the serialization approach don't exist in Silverlight).

Is there any way to preserve the stack trace that works in Silverlight?

答:
Throw a new exception with the exception as inner exception:

```<code>throw new ApplcationException("Error message", error);
</code>```

The inner exception will keep it's stack trace.

Body:
I need to rethrow an Exception that was caught and stored elsewhere without losing the stack trace information about when the Exception was first caught/stored.  My code looks something like this:

    public void Test()
    {
        int someParameter = 12;
        ExecuteSomeAsyncMethod(someParameter, CallbackMethod);
    }

    public void CallbackMethod(object result, Exception error)
    {
        //Check for exceptions that were previously caught and passed to us
        if(error != null)
            //Throwing like this will lose the stack trace already in Exception
            //We'd like to be able to rethrow it without overwriting the stack trace
            throw error;

        //Success case: Process 'result'...etc...
    }

I've seen solutions to this problem that use reflection (for example here and here) or use Serialization (for example here) but none of those will work for me in Silverlight (private reflection is not allowed and the classes/methods used in the serialization approach don't exist in Silverlight).

Is there any way to preserve the stack trace that works in Silverlight?

Body:
Throw a new exception with the exception as inner exception:

throw new ApplcationException("Error message", error);

The inner exception will keep it's stack trace.


问:
How safe is it to have references to union members in C++?
Imagine this situation:

```<code>union Reg16
{
    uint16_t word;

    struct
    {
        uint8_t bottom;
        uint8_t top;
    };
};
</code>```

Let's say I had something like this somewhere that uses this union:

```<code>Reg16 reg_AF;
uint8_t& reg_A = reg_AF.top;
uint8_t& reg_F = reg_AF.bottom;
</code>```

Is it safe to keep a reference to the respective halves of the union even though the union does not technically always refer to a u8? I am not sure if this is a violation of strict aliasing rules, but it is worth noting that there is no reference anywhere to the word, only to top and bottom. Especially in this particular situation, the references are supposed to point to the top and and bottom halves of the entire u16, so there isn't any UB because I won't be getting any value I don't expect to get by reading them versus if I had a union of a float and an int and made a reference to each of those.

Thanks in advance.

答:
Assuming your code is actually:

```<code>union Reg16
{
    uint16_t word;

    struct
    {
        uint8_t bottom;
        uint8_t top;
    } bytes;
};
</code>```

This is perfectly fine as a declaration:

```<code>Reg16 reg_AF;
uint8_t& reg_A = reg_AF.bytes.top;
uint8_t& reg_F = reg_AF.bytes.bottom;
</code>```

You can use the references exactly as you could use directly the struct members.

For example reg_AF.bytes.bottom = 'A'; std::cout << ref_F; is perfectly fine: the union currently contains the struct and you correctly use a reference to a struct member.

But this reg_AF.word = 0x4142; std::cout << reg_A; is UB(*) exactly as is reg_AF.word = 0x4142; std::cout << reg_AF.bytes.bottom;

(*) Per the strict aliasing rule you should not access a value from a different type that the one that was used to write it. As struct bytes is different from uint_8, the aliasing is incorrect. That being said, common compilers currently accept it as an extension for unions and even have options to ignore the strict aliasing rule. Simply the code is not standard conformant and another compiler could behave differently.

Body:
Imagine this situation:

union Reg16
{
    uint16_t word;

    struct
    {
        uint8_t bottom;
        uint8_t top;
    };
};

Let's say I had something like this somewhere that uses this union:

Reg16 reg_AF;
uint8_t& reg_A = reg_AF.top;
uint8_t& reg_F = reg_AF.bottom;

Is it safe to keep a reference to the respective halves of the union even though the union does not technically always refer to a u8? I am not sure if this is a violation of strict aliasing rules, but it is worth noting that there is no reference anywhere to the word, only to top and bottom. Especially in this particular situation, the references are supposed to point to the top and and bottom halves of the entire u16, so there isn't any UB because I won't be getting any value I don't expect to get by reading them versus if I had a union of a float and an int and made a reference to each of those.

Thanks in advance.

Body:
Assuming your code is actually:

union Reg16
{
    uint16_t word;

    struct
    {
        uint8_t bottom;
        uint8_t top;
    } bytes;
};

This is perfectly fine as a declaration:

Reg16 reg_AF;
uint8_t& reg_A = reg_AF.bytes.top;
uint8_t& reg_F = reg_AF.bytes.bottom;

You can use the references exactly as you could use directly the struct members.

For example reg_AF.bytes.bottom = 'A'; std::cout << ref_F; is perfectly fine: the union currently contains the struct and you correctly use a reference to a struct member.

But this reg_AF.word = 0x4142; std::cout << reg_A; is UB(*) exactly as is reg_AF.word = 0x4142; std::cout << reg_AF.bytes.bottom;

(*) Per the strict aliasing rule you should not access a value from a different type that the one that was used to write it. As struct bytes is different from uint_8, the aliasing is incorrect. That being said, common compilers currently accept it as an extension for unions and even have options to ignore the strict aliasing rule. Simply the code is not standard conformant and another compiler could behave differently.


问:
How to pass any class object as a parameter to method
I have 3 classes :-

```<code>public Class Example1
{
  public void Method1()
  {
  }
  public void Method2()
  {
  }
}

public Class Example2
{
  public void Method3()
  {
  }
  public void Method4()
  {
  }
}

public Class CompletelyDifferentClass
{
  public void DifferentMethod(Example1/Example2 obj)
  {
      obj.Method1(); //if object is passed for Example1
      obj.Method3(); //if object is passed for Example2
  }
}
</code>```

If we see CompletelyDifferentClass and  public DifferentMethod(Example1/Example2 obj)

I want DifferentMethod to get parameter as any time I can send Example1 object or Example2 object.
If Example2 object is sent , it should enable methods for Example2 like obj.Method3();

It is not fixed that which class's object I am going to send as a parameter to that method.

How can I write a code for DifferentMethod

答:
You can write a base class and then inherit your child classes from that base class.

Then you can pass any type of child class inheriting from the same class. Like

```<code>public class myBase{

}

public class A: myBase{

}

public class B: myBase{

}

public static void myFunction(myBase obj){

}
</code>```

And you can pass any child class to ur base class like

```<code>myFunction(A);
myFunction(B);
</code>```

Another way is to use method overloading. You can write same functions with same signature. This is a good read for function overloading

Also you can take in object as a parameter type. Even better, perhaps, would be to use generics:

```<code>void MyFunction<T>(T parm) {

}
</code>```

Hope it helps :)

Body:
I have 3 classes :-

public Class Example1
{
  public void Method1()
  {
  }
  public void Method2()
  {
  }
}

public Class Example2
{
  public void Method3()
  {
  }
  public void Method4()
  {
  }
}

public Class CompletelyDifferentClass
{
  public void DifferentMethod(Example1/Example2 obj)
  {
      obj.Method1(); //if object is passed for Example1
      obj.Method3(); //if object is passed for Example2
  }
}

If we see CompletelyDifferentClass and  public DifferentMethod(Example1/Example2 obj)

I want DifferentMethod to get parameter as any time I can send Example1 object or Example2 object.
If Example2 object is sent , it should enable methods for Example2 like obj.Method3();

It is not fixed that which class's object I am going to send as a parameter to that method.

How can I write a code for DifferentMethod

Body:
You can write a base class and then inherit your child classes from that base class.

Then you can pass any type of child class inheriting from the same class. Like

public class myBase{

}

public class A: myBase{

}

public class B: myBase{

}

public static void myFunction(myBase obj){

}

And you can pass any child class to ur base class like

myFunction(A);
myFunction(B);

Another way is to use method overloading. You can write same functions with same signature. This is a good read for function overloading

Also you can take in object as a parameter type. Even better, perhaps, would be to use generics:

void MyFunction<T>(T parm) {

}

Hope it helps :)