问:
Unit Test MapReduce - Junit Mockito
I am new to writing test cases for Map Reduce and as I googled, I understood that MRUnit is deprecated and have to use Mockito. Could someone provide inspiration on testing mapreduce with Junit mockito as I couldn't find one. I could only see MRUnit test cases for mapreduce.</p>

答:
I am providing a sample test class here for mapper. Test for reducer can also be written in same fashion.

```<code>@RunWith(MockitoJUnitRunner.class)
public class SampleMapperTest {

    @Mock
    private Mapper.Context mockContext; // declare your mocks

    @Mock
    Counter mockCounter; // mocked hadoop counter

    SampleMapper mapper;

    @Before
    public void setUp() throws Exception {
       /*
        * mock and define your components here
        */
        mapper = new SampleMapper();
        doNothing().when(mockCounter).increment(anyLong());
    }

    @Test
    public void testMap() throws IOException, InterruptedException {
       /*
        * whatever you want to test you can write here in the verify statement
        */
        String line1 = "key_value";
        mapper.map(null, new Text(line1), mockContext);
        verify(mockCounter, times(1)).increment(1);
    }

    @After
    public void tearDown() throws Exception {
       /*
        * this will do the clean up part
        */
        verifyNoMoreInteractions(mockContext);
    }
}
</code>```

I hope you get some insight from this and should be able to write your test now.

Title: Unit Test MapReduce - Junit Mockito

Body:
I am providing a sample test class here for mapper. Test for reducer can also be written in same fashion.

@RunWith(MockitoJUnitRunner.class)
public class SampleMapperTest {

    @Mock
    private Mapper.Context mockContext; // declare your mocks

    @Mock
    Counter mockCounter; // mocked hadoop counter

    SampleMapper mapper;

    @Before
    public void setUp() throws Exception {
       /*
        * mock and define your components here
        */
        mapper = new SampleMapper();
        doNothing().when(mockCounter).increment(anyLong());
    }

    @Test
    public void testMap() throws IOException, InterruptedException {
       /*
        * whatever you want to test you can write here in the verify statement
        */
        String line1 = "key_value";
        mapper.map(null, new Text(line1), mockContext);
        verify(mockCounter, times(1)).increment(1);
    }

    @After
    public void tearDown() throws Exception {
       /*
        * this will do the clean up part
        */
        verifyNoMoreInteractions(mockContext);
    }
}

I hope you get some insight from this and should be able to write your test now.


来源: stackexchange

问:
Play several MP3 sounds Simultaneously
Is it possible to play several MP3 sounds Simultaneously with AVAudioPlayer?</p>

答: Yes, but note that there is only one (known) hardware MP3 decoder on current devices, any other simultaneous sounds must be decoded in software by the AV player.  So you will eventually run out of CPU cycles to keep up with over some (device dependent) number of sounds.</p>

ContentLicense: CC BY-SA 2.5

Title: Play several MP3 sounds Simultaneously


问:
Get file name from absolute path in Nodejs?
How can I get the file name from an absolute path in Nodejs?

e.g. "foo.txt" from "/var/www/foo.txt"

I know it works with a string operation, like fullpath.replace(/.+\//, ''),
but I want to know is there an explicit way, like file.getName() in Java?

答:
If you already know that the path separator is / (i.e. you are writing for a specific platform/environment), as implied by the example in your question, you could keep it simple and split the string by separator:

```<code>'/foo/bar/baz/asdf/quux.html'.split('/').pop()
</code>```

That would be faster (and cleaner imo) than replacing by regular expression.

Again: Only do this if you're writing for a specific environment, otherwise use the path module, as paths are surprisingly complex. Windows, for instance, supports / in many cases but not for e.g. the \\?\? style prefixes used for shared network folders and the like. On Windows the above method is doomed to fail, sooner or later.

ContentLicense: CC BY-SA 4.0

Body:
If you already know that the path separator is / (i.e. you are writing for a specific platform/environment), as implied by the example in your question, you could keep it simple and split the string by separator:

'/foo/bar/baz/asdf/quux.html'.split('/').pop()

That would be faster (and cleaner imo) than replacing by regular expression.

Again: Only do this if you're writing for a specific environment, otherwise use the path module, as paths are surprisingly complex. Windows, for instance, supports / in many cases but not for e.g. the \\?\? style prefixes used for shared network folders and the like. On Windows the above method is doomed to fail, sooner or later.


问:
Stumped by d3 error I'm receiving - Error: <path> attribute d: Expected number, "M0,NaNL21.923076923…"
I'm trying to convert a d3 sparkline example on codepen (https://codepen.io/jakelear-1472051722/pen/bRbqBB) so that it pulls data in from a csv file. Here is my code:

```<code>d3.csv("sparkline.csv", function (error, data) {

    if (error) throw error;

    // format the data
    data.forEach(function (d) {
        currentValue = +d.currentValue;

    });

    var graph = d3.select('.sparkline').append("svg").attr("width", "100%").attr("height", "100%");

    var height = parseInt(graph.style("height"));
    var width = parseInt(graph.style("width"));

    var x = d3.scaleLinear()
        .domain([0, data.length])
        .range([0, width]);

    var y = d3.scaleLinear()
        .domain([0, d3.max(data)])
        .range([height, 0]);

    var line = d3.line()
        .x(function(d,i) {
            return x(i);
        })

        .y(function(d) {
            return y(currentValue);
        });

    graph.append("path")
        .data([data])
        .attr("class", "line")
        .attr("d", line);

});
</code>```

I'm receiving the following error: d3.v4.js:1382 Error:  attribute d: Expected number, "M0,NaNL21.923076923…" and have been struggling trying to figure this out.

The contents of my CSV file:

```<code>currentValue
2.0
2.3
1.9
1.7
1.7
2.2
2.3
2.2
2.0
2.1
1.9
2.0
1.6
</code>```

Any help is greatly appreciated. I'm sure it's something small I'm just not seeing.

Thanks

答:
data is not a simple, flat array, but an array of objects.

Therefore, it should be:

```<code>var y = d3.scaleLinear()
    .domain([0, d3.max(data, function(d){ return d.currentValue})])
    .range([height, 0]);
</code>```

Besides that, remember to correctly provide a reference to the object. In the forEach loop:

```<code>data.forEach(function (d) {
    d.currentValue = +d.currentValue;

});
</code>```

And in the line generator:

```<code>var line = d3.line()
    .x(function(d,i) {
        return x(i);
    })

    .y(function(d) {
        return y(d.currentValue);
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to convert a d3 sparkline example on codepen (https://codepen.io/jakelear-1472051722/pen/bRbqBB) so that it pulls data in from a csv file. Here is my code:

d3.csv("sparkline.csv", function (error, data) {

    if (error) throw error;

    // format the data
    data.forEach(function (d) {
        currentValue = +d.currentValue;

    });

    var graph = d3.select('.sparkline').append("svg").attr("width", "100%").attr("height", "100%");

    var height = parseInt(graph.style("height"));
    var width = parseInt(graph.style("width"));

    var x = d3.scaleLinear()
        .domain([0, data.length])
        .range([0, width]);

    var y = d3.scaleLinear()
        .domain([0, d3.max(data)])
        .range([height, 0]);

    var line = d3.line()
        .x(function(d,i) {
            return x(i);
        })

        .y(function(d) {
            return y(currentValue);
        });

    graph.append("path")
        .data([data])
        .attr("class", "line")
        .attr("d", line);

});

I'm receiving the following error: d3.v4.js:1382 Error:  attribute d: Expected number, "M0,NaNL21.923076923…" and have been struggling trying to figure this out.

The contents of my CSV file:

currentValue
2.0
2.3
1.9
1.7
1.7
2.2
2.3
2.2
2.0
2.1
1.9
2.0
1.6

Any help is greatly appreciated. I'm sure it's something small I'm just not seeing.

Thanks

Body:
data is not a simple, flat array, but an array of objects.

Therefore, it should be:

var y = d3.scaleLinear()
    .domain([0, d3.max(data, function(d){ return d.currentValue})])
    .range([height, 0]);

Besides that, remember to correctly provide a reference to the object. In the forEach loop:

data.forEach(function (d) {
    d.currentValue = +d.currentValue;

});

And in the line generator:

var line = d3.line()
    .x(function(d,i) {
        return x(i);
    })

    .y(function(d) {
        return y(d.currentValue);
    });


问:
Detect table cell change on user edit
I'm trying to detect html table cell change on user input. When I click on table cell I can type text in it, but my .change function is not triggered. However on page load when data are populated from database, for every table cell change change function is fired. I can not figure why. Can you help.
My code below:

```<code>    <div id="table" class="table-editable">
        <table id="myTable" style="width:100%" class="table">
            <tr>
                <th>Id</th>
                <th>Link</th>
                <th>Naslov</th>
                <th>Lokacija</th>
                <th>Cijena</th>
                <th>Telefon</th>
                <th>Posjet</th>
                <th>Opis</th>
                <th>Prednosti</th>
                <th>Nedostaci</th>
                <th>Slike</th>
                <th>Select</th>
            {% for entry in entries %}
            </tr>
            <tr>
                <td>{{ forloop.counter }}</td>
                <td><a id="linkHouse_{{ forloop.counter }}" href="{{ entry.link }}">Link na oglas</a></td>
                <td contenteditable="true">{{ entry.header }}</td>
                <td contenteditable="true">{{ entry.location  }}</td>
                <td id="priceHouse_{{ forloop.counter }}" contenteditable="true">{{ entry.price  }}</td>
                <td id="contactHouse_{{ forloop.counter }}" contenteditable="true">{{ entry.contacts }}</td>
                <td id="visitedHouse_{{ forloop.counter }}" contenteditable="true">{{ entry.visited  }}</td>
                <td id="descriptionHouse_{{ forloop.counter }}" contenteditable="true">{% for line in entry.description.splitlines %} {{line}}<br> {% endfor %}</td>
                <td id="prosHouse_{{ forloop.counter }}" contenteditable="true" >{% for line in entry.pros.splitlines %} {{line}}<br> {% endfor %}</td>
                <td id="consHouse_{{ forloop.counter }}"contenteditable="true">{% for line in entry.cons.splitlines %} {{line}}<br> {% endfor %}</td>
                <td >
                    <a class="fancybox" target="_blank" data-fancybox="images" href="{% static "Pic/img_fjords_wide.jpg" %}"><img src="{% static "Pic/img_fjords_wide.jpg" %}" alt="" style="width:150px"></a>
                    <a class="hide fancybox" target="_blank" data-fancybox="images" href="{% static "Pic/img_lights_wide.jpg" %}"><img src="{% static "Pic/img_lights_wide.jpg" %}" alt=""></a>
                    <a class="hide fancybox" target="_blank" data-fancybox="images" href="{% static "Pic/img_mountains_wide.jpg" %}"><img src="{% static "Pic/img_mountains_wide.jpg" %}" alt=""></a>
                </td>
                <td style="text-align: center; vertical-align: middle;">
                    <button id="delHouse_{{ forloop.counter }}" onclick="delHouse(this.id)">Delete</button>

                    <!--<input type="checkbox" name="delete{{ forloop.counter }}">-->
                </td>
            </tr>
            {% endfor %}
        </table>
    </div>

$(document).ready(function(){
$( "#myTable td" )
  .change(function () {
        console.log("petar");
        var data = this.innerHTML;
        console.log("value="+data);
  })
  .change();
</code>```

});

答:
Use Javascript's input method.

Or the blur method.

Change me (input)!

Change me (blur)!
```
</div>
</div>
</p>

<p>IE 6 & 8 and Opera Mini are not supported & IE 9 partial support, but either than that, it works!</p>

<p>If you want global support, check out this thread.</p>

<p>So your code would look like:</p>

```$(document).ready(function(){
  $( "#myTable td" )
    .input(function () {
          console.log("petar");
          var data = this.innerHTML;
          console.log("value="+data);
    })
  .input();
});
```

Title: Detect table cell change on user edit

Body:
I'm trying to detect html table cell change on user input. When I click on table cell I can type text in it, but my .change function is not triggered. However on page load when data are populated from database, for every table cell change change function is fired. I can not figure why. Can you help.
My code below:

                Id
                Link
                Naslov
                Lokacija
                Cijena
                Telefon
                Posjet
                Opis
                Prednosti
                Nedostaci
                Slike
                Select
            {% for entry in entries %}

                {{ forloop.counter }}
                Link na oglas
                {{ entry.header }}
                {{ entry.location  }}
                {{ entry.price  }}
                {{ entry.contacts }}
                {{ entry.visited  }}
                {% for line in entry.description.splitlines %} {{line}}
 {% endfor %}
                {% for line in entry.pros.splitlines %} {{line}}
 {% endfor %}
                {% for line in entry.cons.splitlines %} {{line}}
 {% endfor %}

                    <button id="delHouse_{{ forloop.counter }}" onclick="delHouse(this.id)">Delete</button>

            {% endfor %}

$(document).ready(function(){
$( "#myTable td" )
  .change(function () {
        console.log("petar");
        var data = this.innerHTML;
        console.log("value="+data);
  })
  .change();

});

Body:
Use Javascript's input method.

Or the blur method.

<div contenteditable oninput="console.log(this.innerHTML)">Change me (input)!</div>

<div contenteditable onblur="console.log(this.innerHTML)">Change me (blur)!</div>

IE 6 & 8 and Opera Mini are not supported & IE 9 partial support, but either than that, it works!

If you want global support, check out this thread.

So your code would look like:

$(document).ready(function(){
  $( "#myTable td" )
    .input(function () {
          console.log("petar");
          var data = this.innerHTML;
          console.log("value="+data);
    })
  .input();
});


问:
Forcing TService OnStop event to wait until some job completes
working with a Windows Service application in Delphi, I stumbled on the issue as in the subject.

I do start a default Delphi Windows Service project on the IDE, follow the wizard and in the end I have a project and a
TService unit. I add to this project another unit, a Data Module (named DM) in which the service code logic is contained.
The DM has a TTimer (design-time) that runs a relatively long job.

Case 1:
DM is created by default in design-time. I have the following code in my TService Start/Stop

```<code>procedure TOmegaCAOraNT.ServiceStart(Sender: TService;
  var Started: Boolean);
begin
  DM.Timer1.Enabled := True;
  Started := true;
end;

procedure TOmegaCAOraNT.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
  DM.Agent_Stop;
  Stopped := true;
end;
</code>```

When I try to Stop the Service via Windows SCM - in appearance it confirms the Stop, field Status becomes empty - but it does not.
I can see the service .exe still running for a while, and what's more it does terminate the Timer's long job in the middle,
doing part of it only!
This is an undesired behavior!

I fixed this in the second case

Case 2:
DM is created in run-time. The Timer is enabled on DM.OnCreate
I have the following code in my TService Start/Stop

```<code>procedure TOmegaCAOraNT.ServiceStart(Sender: TService; var Started: Boolean);
begin
  FDataModule := TDM.Create(nil);
  Started := true;
end;

procedure TOmegaCAOraNT.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
  FreeAndNil(FDataModule);
  Stopped := true;
end;
</code>```

When I try to Stop the Service via Windows SCM - it throws the following Warning:

"Windows could not stop the SERVICE> service on the Local Computer.
  The service did not return an error. his could be an internal Windows error or an internal service error.
  if the error persists, contact your system Administrator"

field Status remains Started. Timer' long job finishes until the end, and then the service really stops (refresh in SCM to see, Status empty)
This is desired behavior !

My problem is that I would like the DM to be created in design-time, and not in run-time

My question is:
can I have the right behavior of run-time DM (Case 2), with a design-time DM (Case 1) ?

thanks and best regards,
Altin

答:
TService runs in is own worker thread at run-time.

If you configure the DM to be auto-created, it (and its TTimer) will be created in the main thread at run-time, not in the service thread.  And thus, the TTimer will run in the main thread, and can be activated only by the main thread, not in the TService.OnStart event handler (an EOutOfResources exception will be raised if you try).

If you manually create the DM in the TService.OnStart event handler, it (and its TTimer) will be created in the service thread, not in the main thread.  The TTimer will run in the service thread, and can be (de)activated in the TService events.

Either way, make sure your TTimer.OnTimer event handler uses thread-safe code.

Also, the TService.OnStop event handler must call the TService.ReportStatus() method periodically (before the TService.WaitHint interval elapses) while waiting for other threads to stop whatever they are doing.  Which means you shouldn't use thread-blocking code in the TService.OnStop event handler.

You are not handling this correctly, which is why the SCM is having problems.

Body:
working with a Windows Service application in Delphi, I stumbled on the issue as in the subject.

I do start a default Delphi Windows Service project on the IDE, follow the wizard and in the end I have a project and a
TService unit. I add to this project another unit, a Data Module (named DM) in which the service code logic is contained.
The DM has a TTimer (design-time) that runs a relatively long job.

Case 1:
DM is created by default in design-time. I have the following code in my TService Start/Stop

procedure TOmegaCAOraNT.ServiceStart(Sender: TService;
  var Started: Boolean);
begin
  DM.Timer1.Enabled := True;
  Started := true;
end;

procedure TOmegaCAOraNT.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
  DM.Agent_Stop;
  Stopped := true;
end;

When I try to Stop the Service via Windows SCM - in appearance it confirms the Stop, field Status becomes empty - but it does not.
I can see the service .exe still running for a while, and what's more it does terminate the Timer's long job in the middle,
doing part of it only!
This is an undesired behavior!

I fixed this in the second case

Case 2:
DM is created in run-time. The Timer is enabled on DM.OnCreate
I have the following code in my TService Start/Stop

procedure TOmegaCAOraNT.ServiceStart(Sender: TService; var Started: Boolean);
begin
  FDataModule := TDM.Create(nil);
  Started := true;
end;

procedure TOmegaCAOraNT.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
  FreeAndNil(FDataModule);
  Stopped := true;
end;

When I try to Stop the Service via Windows SCM - it throws the following Warning:

"Windows could not stop the SERVICE> service on the Local Computer.
  The service did not return an error. his could be an internal Windows error or an internal service error.
  if the error persists, contact your system Administrator"

field Status remains Started. Timer' long job finishes until the end, and then the service really stops (refresh in SCM to see, Status empty)
This is desired behavior !

My problem is that I would like the DM to be created in design-time, and not in run-time

My question is:
can I have the right behavior of run-time DM (Case 2), with a design-time DM (Case 1) ?

thanks and best regards,
Altin


问:
load different js files for different pages or load together?
I have 3 pages of site.

Page 1: 19 kb of JS

  Page 2: 26 kb of JS

  Page 3: 10 kb of JS

  Total : 55 kb of JS

These javascript files are non repeating, means the JS needed on page 1 is not needed on page 2 and I have expiry headers set 1 month.

Still I would like to know what will be best way to load these files, should I load separate file for each page or I load these all together?

答:
The way you described it, you should load them separately.

If the user is guaranteed to navigate to all 3 pages then yes, combine them. If they usually navigate to one page, then loading all three is a waste.

That said, 55k is not THAT large, however consider the impact from a mobile browser or even dial-up.

Minimize and use compression to reduce the JS to the maximum, but don't load a file unless it is required.


问:
Objects not moving with transition on postion : fixed
i was kind of building a fixed navbar by the right side of my design with position fixed , and i used jquery to toggle class one with display : none, and the other with display: block.

when code scrolls past say 300px height the sidebar shows if not it hides.

but when it scroll past say 300px high the side bar shows automatically with no transition effect, i have already generated a transition style for my design but does not seem to work, please i need help on this.

here is my code

jQuery(document).ready(function($){
 // browser window scroll (in pixels) after which the "back to top" link is shown
 var offset = 300,
  //browser window scroll (in pixels) after which the "back to top" link opacity is reduced
  offset_opacity = 1200,
  //duration of the top scrolling animation (in ms)
  scroll_top_duration = 700,
  //grab the "back to top" link
  $back_to_top = $('.even-more-sq-rt');

 //hide or show the "back to top" link
 $(window).scroll(function(){
  ( $(this).scrollTop() > offset ) ? $back_to_top.addClass('even-more-post-visible') : $back_to_top.removeClass('even-more-post-visible');

 });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>
.even-more-sq-rt {
    width: 300px !important;
    max-height: 350px;
    position: fixed;
    z-index: 999;
    right: 0px;
    bottom: 20px;
    top: 10px;
    background: white;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    border-radius: 0px;
    margin-bottom: 60px;
    padding:  20px;
    border: 1px solid #ddd;
    border-right-width: 1px;
    border-right-style: solid;
    border-right-color: rgb(221, 221, 221);
    border-right: 0px;
}

.even-more-sq-rt-postmeta h3 {
    font-size: 17px;
    padding-top: 10px;
}

.even-more-sq-rt-thumb.img-responsive {
    height: 145px;
    overflow: hidden;
}

.even-more-sq-rt {
    text-align: center;
}

.close-btn {
    position: absolute;
    right: 0;
    top: 0;
    background: #333;
    border: 0px;
    padding: 3px 11px;
    color: #fff;
}

.even-more-sq-rt h3 {
    margin-top: 0px;
    font-size: 17px;
}

.even-more-sq-rt {
    display: none;
    transition: all 12s ease-in 5s;
}

.even-more-post-visible {
    display: block;
}</code>```

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

Trending Now

                    <button class="close-btn">X</button>

 when there is no more words to say : silence is golden

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

<p>here is the transition i would love to add :</p>

```-webkit-transition: right 500ms cubic-bezier(0.265, 0.365, 0.26, 0.865);
-moz-transition: right 500ms cubic-bezier(0.265, 0.365, 0.26, 0.865);
-o-transition: right 500ms cubic-bezier(0.265, 0.365, 0.26, 0.865);
transition: right 500ms cubic-bezier(0.265, 0.365, 0.26, 0.865);
    transition-timing-function: cubic-bezier(0.265, 0.365, 0.26, 0.865);
-webkit-transition-timing-function: cubic-bezier(0.265, 0.365, 0.26, 0.865);
-moz-transition-timing-function: cubic-bezier(0.265, 0.365, 0.26, 0.865);
-o-transition-timing-function: cubic-bezier(0.265, 0.365, 0.26, 0.865);
transition-timing-function: cubic-bezier(0.265, 0.365, 0.26, 0.865);
```

答:
Was it something like this you where looking for, the only thing I did was adding a css3 animation and adding it to the even-more-post-visible style.

jQuery(document).ready(function($){
 // browser window scroll (in pixels) after which the "back to top" link is shown
 var offset = 300,
  //browser window scroll (in pixels) after which the "back to top" link opacity is reduced
  offset_opacity = 1200,
  //duration of the top scrolling animation (in ms)
  scroll_top_duration = 700,
  //grab the "back to top" link
  $back_to_top = $('.even-more-sq-rt');

 //hide or show the "back to top" link
 $(window).scroll(function(){
  ( $(this).scrollTop() > offset ) ? $back_to_top.addClass('even-more-post-visible') : $back_to_top.removeClass('even-more-post-visible');

 });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.even-more-sq-rt {
    width: 300px !important;
    max-height: 350px;
    position: fixed;
    z-index: 999;
    right: 0px;
    bottom: 20px;
    top: 10px;
    background: white;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    border-radius: 0px;
    margin-bottom: 60px;
    padding:  20px;
    border: 1px solid #ddd;
    border-right-width: 1px;
    border-right-style: solid;
    border-right-color: rgb(221, 221, 221);
    border-right: 0px;
}

.even-more-sq-rt-postmeta h3 {
    font-size: 17px;
    padding-top: 10px;
}

.even-more-sq-rt-thumb.img-responsive {
    height: 145px;
    overflow: hidden;
}

.even-more-sq-rt {
    text-align: center;
}

.close-btn {
    position: absolute;
    right: 0;
    top: 0;
    background: #333;
    border: 0px;
    padding: 3px 11px;
    color: #fff;
}

.even-more-sq-rt h3 {
    margin-top: 0px;
    font-size: 17px;
}

.even-more-sq-rt {
    display: none;
    transition: all 12s ease-in 5s;
}

.even-more-post-visible {
    display: block;
    animation: fadein 2s;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}</code>```

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

Trending Now

                    <button class="close-btn">X</button>

 when there is no more words to say : silence is golden

```

Body:
i was kind of building a fixed navbar by the right side of my design with position fixed , and i used jquery to toggle class one with display : none, and the other with display: block.

when code scrolls past say 300px height the sidebar shows if not it hides.

but when it scroll past say 300px high the side bar shows automatically with no transition effect, i have already generated a transition style for my design but does not seem to work, please i need help on this.

here is my code

jQuery(document).ready(function($){
 // browser window scroll (in pixels) after which the "back to top" link is shown
 var offset = 300,
  //browser window scroll (in pixels) after which the "back to top" link opacity is reduced
  offset_opacity = 1200,
  //duration of the top scrolling animation (in ms)
  scroll_top_duration = 700,
  //grab the "back to top" link
  $back_to_top = $('.even-more-sq-rt');

 //hide or show the "back to top" link
 $(window).scroll(function(){
  ( $(this).scrollTop() > offset ) ? $back_to_top.addClass('even-more-post-visible') : $back_to_top.removeClass('even-more-post-visible');

 });

});

.even-more-sq-rt {
    width: 300px !important;
    max-height: 350px;
    position: fixed;
    z-index: 999;
    right: 0px;
    bottom: 20px;
    top: 10px;
    background: white;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    border-radius: 0px;
    margin-bottom: 60px;
    padding:  20px;
    border: 1px solid #ddd;
    border-right-width: 1px;
    border-right-style: solid;
    border-right-color: rgb(221, 221, 221);
    border-right: 0px;
}

.even-more-sq-rt-postmeta h3 {
    font-size: 17px;
    padding-top: 10px;
}

.even-more-sq-rt-thumb.img-responsive {
    height: 145px;
    overflow: hidden;
}

.even-more-sq-rt {
    text-align: center;
}

.close-btn {
    position: absolute;
    right: 0;
    top: 0;
    background: #333;
    border: 0px;
    padding: 3px 11px;
    color: #fff;
}

.even-more-sq-rt h3 {
    margin-top: 0px;
    font-size: 17px;
}

.even-more-sq-rt {
    display: none;
    transition: all 12s ease-in 5s;
}

.even-more-post-visible {
    display: block;
}

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

 some space

Trending Now

                    <button class="close-btn">X</button>

 when there is no more words to say : silence is golden

here is the transition i would love to add :

-webkit-transition: right 500ms cubic-bezier(0.265, 0.365, 0.26, 0.865);
-moz-transition: right 500ms cubic-bezier(0.265, 0.365, 0.26, 0.865);
-o-transition: right 500ms cubic-bezier(0.265, 0.365, 0.26, 0.865);
transition: right 500ms cubic-bezier(0.265, 0.365, 0.26, 0.865);
    transition-timing-function: cubic-bezier(0.265, 0.365, 0.26, 0.865);
-webkit-transition-timing-function: cubic-bezier(0.265, 0.365, 0.26, 0.865);
-moz-transition-timing-function: cubic-bezier(0.265, 0.365, 0.26, 0.865);
-o-transition-timing-function: cubic-bezier(0.265, 0.365, 0.26, 0.865);
transition-timing-function: cubic-bezier(0.265, 0.365, 0.26, 0.865);

Body:
Was it something like this you where looking for, the only thing I did was adding a css3 animation and adding it to the even-more-post-visible style.

jQuery(document).ready(function($){
 // browser window scroll (in pixels) after which the "back to top" link is shown
 var offset = 300,
  //browser window scroll (in pixels) after which the "back to top" link opacity is reduced
  offset_opacity = 1200,
  //duration of the top scrolling animation (in ms)
  scroll_top_duration = 700,
  //grab the "back to top" link
  $back_to_top = $('.even-more-sq-rt');

 //hide or show the "back to top" link
 $(window).scroll(function(){
  ( $(this).scrollTop() > offset ) ? $back_to_top.addClass('even-more-post-visible') : $back_to_top.removeClass('even-more-post-visible');

 });

});

.even-more-sq-rt {
    width: 300px !important;
    max-height: 350px;
    position: fixed;
    z-index: 999;
    right: 0px;
    bottom: 20px;
    top: 10px;
    background: white;
    -webkit-border-radius: 30px;
    -moz-border-radius: 30px;
    border-radius: 0px;
    margin-bottom: 60px;
    padding:  20px;
    border: 1px solid #ddd;
    border-right-width: 1px;
    border-right-style: solid;
    border-right-color: rgb(221, 221, 221);
    border-right: 0px;
}

.even-more-sq-rt-postmeta h3 {
    font-size: 17px;
    padding-top: 10px;
}

.even-more-sq-rt-thumb.img-responsive {
    height: 145px;
    overflow: hidden;
}

.even-more-sq-rt {
    text-align: center;
}

.close-btn {
    position: absolute;
    right: 0;
    top: 0;
    background: #333;
    border: 0px;
    padding: 3px 11px;
    color: #fff;
}

.even-more-sq-rt h3 {
    margin-top: 0px;
    font-size: 17px;
}

.even-more-sq-rt {
    display: none;
    transition: all 12s ease-in 5s;
}

.even-more-post-visible {
    display: block;
    animation: fadein 2s;
}

@keyframes fadein {
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>
<h3> some space </h3>

<div class="even-more-sq-rt">
           <h3>Trending Now</h3>
                    <button class="close-btn">X</button>
                <div class="even-more-sq-rt-inner clearfix">

                    <div class="even-more-sq-rt-thumb img-responsive">
                        <img src="http://placehold.it/259x145">
                    </div>
                    <div class="even-more-sq-rt-postmeta">
                        <h3><a href="#"> when there is no more words to say : silence is golden</a></h3>
                    </div>
                </div>
            </div>


问:
MongoDB - Preserve order when using sample
I want to have pagination and sampling.

I have a client that requests entities in a random order.
I want to implement a new feature - pagination.
The only way I can think of is to use match to ensure the entities to be served do not have ID's of the entities already served, but this sounds like an expensive operation.

Is there a way to randomise the order of entities in a collection, and save it in a way? So that I can use skip on it?

答:
How about using a combination of $sample and $out?</p>

```<code>db.collection.aggregate({
    $sample: { size: 300 } // get 300 random documents
}, {
    $out: "temp" // write results to a new "temp" collection
})
</code>```

Body:
How about using a combination of $sample and $out?

db.collection.aggregate({
    $sample: { size: 300 } // get 300 random documents
}, {
    $out: "temp" // write results to a new "temp" collection
})


问:
BottomNavigationView back button behavior should work like the Youtube App but crashes
Steps to reproduce:

Start a new Android project, choose "BottomNavigationView":

Replace MainActivity with this:

```<code>class MainActivity : AppCompatActivity() {

private var fragmentIds = ArrayList<Int>()

val fragmentA: FragmentA = FragmentA()
private val fragmentB = FragmentB()
private val fragmentC = FragmentC()

private fun getFragment(fragmentId: Int): Fragment {
    when (fragmentId) {
        R.id.navigation_home -> {
            return fragmentA
        }
        R.id.navigation_dashboard -> {
            return fragmentB
        }
        R.id.navigation_notifications -> {
            return fragmentC
        }
    }
    return fragmentA
}

private fun updateView(fragmentId: Int) {
    var exists = false
    fragmentIds
            .filter { it == fragmentId }
            .forEach { exists = true }

    if (exists) {
        fragmentIds.remove(fragmentId)
        showTabWithoutAddingToBackStack(getFragment(fragmentId))
    } else {
        fragmentIds.add(fragmentId)
        showTab(getFragment(fragmentId))
    }
}

private val onNavigationItemClicked = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.navigation_home -> {
            updateView(R.id.navigation_home)
            return@OnNavigationItemSelectedListener true
        }
        R.id.navigation_dashboard -> {
            updateView(R.id.navigation_dashboard)
            return@OnNavigationItemSelectedListener true
        }
        R.id.navigation_notifications -> {
            updateView(R.id.navigation_notifications)
            return@OnNavigationItemSelectedListener true
        }
    }
    false
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    showTabWithoutAddingToBackStack(fragmentA)

    navigation.setOnNavigationItemSelectedListener(onNavigationItemClicked)

}

private fun showTab(fragment: Fragment) {
    supportFragmentManager
            .beginTransaction()
            .replace(R.id.main_container, fragment, fragment::class.java.simpleName)
            .addToBackStack(fragment::class.java.simpleName)
            .commit()
}

fun showTabWithoutAddingToBackStack(fragment: Fragment) {
    supportFragmentManager
            .beginTransaction()
            .replace(R.id.main_container, fragment, fragment::class.java.simpleName)
            .commit()
}

fun setBottomTab(id: Int) {
    navigation.setOnNavigationItemSelectedListener(null)
    navigation.selectedItemId = id
    // currentTab = id
    navigation.setOnNavigationItemSelectedListener(onNavigationItemClicked)
}
}
</code>```

Create 3 new classes, FragmentA, FragmentB and FragmentC:

```<code>class FragmentA : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    setHasOptionsMenu(true)
    return inflater.inflate(R.layout.fragment_a, container, false)
}

override fun onResume() {
    super.onResume()
    val act = activity as MainActivity
    act.setBottomTab(R.id.navigation_home)
}
}
</code>```

with this xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment A" />
</LinearLayout>
</code>```

Start the app

Press "Dashboard"  - Fragment B is shown

Press "Notifications" - Fragment C is shown

Press "Dashboard" - Fragment B is shown

Press "Home"  - Fragment A is shown

Press Back button - Fragment B is shown

Press Back button - Fragment C should be shown - App Crashes

Press Back button - Fragment A should be shown - App is crashed

Press Back button - App shuts down. - App is crashed

Here is a video that demonstrates above steps

Stacktrace:

```<code>12-06 12:58:35.899 25903-25903/com.example.jimclermonts.bottomnavigationview E/InputEventSender: Exception dispatching finished signal.
12-06 12:58:35.900 25903-25903/com.example.jimclermonts.bottomnavigationview E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
12-06 12:58:35.912 25903-25903/com.example.jimclermonts.bottomnavigationview E/MessageQueue-JNI: java.lang.**IllegalStateException: Fragment already added**: FragmentB{3aac1d9 #1 id=0x7f080059 FragmentB}
                                                                                at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1882)
                                                                                at android.support.v4.app.BackStackRecord.executePopOps(BackStackRecord.java:825)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2577)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
                                                                                at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                                                                                at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:851)
                                                                                at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:794)
                                                                                at android.support.v4.app.FragmentActivity.onBackPressed(FragmentActivity.java:174)
</code>```

答:
This lets you have the "do not repeat (but reorder) my fragments on the backstack" behavior using a custom backstack (deque):</p>

```<code>class MainActivity extends AppCompatActivity {
    private BottomNavigationView navigation;
    // initialize with number of different fragments
    private Deque<Integer> fragmentIds = new ArrayDeque<>(3);

    private FragmentA fragmentA = new FragmentA();
    private FragmentB fragmentB = new FragmentB();
    private FragmentC fragmentC = new FragmentC();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentIds.push(R.id.navigation_home);
        showTabWithoutAddingToBackStack(fragmentA);
        navigation = findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(onNavigationItemClicked);
    }

    private BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemClicked = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            item.setChecked(true);
            int itemId = item.getItemId();
            if (fragmentIds.contains(itemId)) {
                fragmentIds.remove(itemId);
            }
            fragmentIds.push(itemId);
            showTabWithoutAddingToBackStack(getFragment(item.getItemId()));
            return true;
        }
    };

    private Fragment getFragment(int fragmentId) {
        switch (fragmentId) {
            case R.id.navigation_home:
                return fragmentA;
            case R.id.navigation_dashboard:
                return fragmentB;
            case R.id.navigation_notifications:
                return fragmentC;
        }
        return fragmentA;
    }

    void showTabWithoutAddingToBackStack(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, fragment.getClass().getSimpleName()).commit();
    }

    void setBottomTab(int id) {
        int itemIndex;
        switch (id) {
            case R.id.navigation_dashboard:
                itemIndex = 1;
                break;
            case R.id.navigation_notifications:
                itemIndex = 2;
                break;
            default:
            case R.id.navigation_home:
                itemIndex = 0;
        }
        navigation.getMenu().getItem(itemIndex).setChecked(true);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        fragmentIds.pop();
        if (!fragmentIds.isEmpty()) {
            showTabWithoutAddingToBackStack(getFragment(fragmentIds.peek()));
        } else {
            finish();
        }
    }
}
</code>```

Body:
Steps to reproduce:

Start a new Android project, choose "BottomNavigationView":

Replace MainActivity with this:

class MainActivity : AppCompatActivity() {

private var fragmentIds = ArrayList<Int>()

val fragmentA: FragmentA = FragmentA()
private val fragmentB = FragmentB()
private val fragmentC = FragmentC()

private fun getFragment(fragmentId: Int): Fragment {
    when (fragmentId) {
        R.id.navigation_home -> {
            return fragmentA
        }
        R.id.navigation_dashboard -> {
            return fragmentB
        }
        R.id.navigation_notifications -> {
            return fragmentC
        }
    }
    return fragmentA
}

private fun updateView(fragmentId: Int) {
    var exists = false
    fragmentIds
            .filter { it == fragmentId }
            .forEach { exists = true }

    if (exists) {
        fragmentIds.remove(fragmentId)
        showTabWithoutAddingToBackStack(getFragment(fragmentId))
    } else {
        fragmentIds.add(fragmentId)
        showTab(getFragment(fragmentId))
    }
}

private val onNavigationItemClicked = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.navigation_home -> {
            updateView(R.id.navigation_home)
            return@OnNavigationItemSelectedListener true
        }
        R.id.navigation_dashboard -> {
            updateView(R.id.navigation_dashboard)
            return@OnNavigationItemSelectedListener true
        }
        R.id.navigation_notifications -> {
            updateView(R.id.navigation_notifications)
            return@OnNavigationItemSelectedListener true
        }
    }
    false
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    showTabWithoutAddingToBackStack(fragmentA)

    navigation.setOnNavigationItemSelectedListener(onNavigationItemClicked)

}

private fun showTab(fragment: Fragment) {
    supportFragmentManager
            .beginTransaction()
            .replace(R.id.main_container, fragment, fragment::class.java.simpleName)
            .addToBackStack(fragment::class.java.simpleName)
            .commit()
}

fun showTabWithoutAddingToBackStack(fragment: Fragment) {
    supportFragmentManager
            .beginTransaction()
            .replace(R.id.main_container, fragment, fragment::class.java.simpleName)
            .commit()
}

fun setBottomTab(id: Int) {
    navigation.setOnNavigationItemSelectedListener(null)
    navigation.selectedItemId = id
    // currentTab = id
    navigation.setOnNavigationItemSelectedListener(onNavigationItemClicked)
}
}

Create 3 new classes, FragmentA, FragmentB and FragmentC:

class FragmentA : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    setHasOptionsMenu(true)
    return inflater.inflate(R.layout.fragment_a, container, false)
}

override fun onResume() {
    super.onResume()
    val act = activity as MainActivity
    act.setBottomTab(R.id.navigation_home)
}
}

with this xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment A" />
</LinearLayout>

Start the app

Press "Dashboard"  - Fragment B is shown

Press "Notifications" - Fragment C is shown

Press "Dashboard" - Fragment B is shown

Press "Home"  - Fragment A is shown

Press Back button - Fragment B is shown

Press Back button - Fragment C should be shown - App Crashes

Press Back button - Fragment A should be shown - App is crashed

Press Back button - App shuts down. - App is crashed

Here is a video that demonstrates above steps

Stacktrace:

12-06 12:58:35.899 25903-25903/com.example.jimclermonts.bottomnavigationview E/InputEventSender: Exception dispatching finished signal.
12-06 12:58:35.900 25903-25903/com.example.jimclermonts.bottomnavigationview E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
12-06 12:58:35.912 25903-25903/com.example.jimclermonts.bottomnavigationview E/MessageQueue-JNI: java.lang.**IllegalStateException: Fragment already added**: FragmentB{3aac1d9 #1 id=0x7f080059 FragmentB}
                                                                                at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1882)
                                                                                at android.support.v4.app.BackStackRecord.executePopOps(BackStackRecord.java:825)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2577)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
                                                                                at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                                                                                at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:851)
                                                                                at android.support.v4.app.FragmentManagerImpl.popBackStackImmediate(FragmentManager.java:794)
                                                                                at android.support.v4.app.FragmentActivity.onBackPressed(FragmentActivity.java:174)

Body:
This lets you have the "do not repeat (but reorder) my fragments on the backstack" behavior using a custom backstack (deque):

class MainActivity extends AppCompatActivity {
    private BottomNavigationView navigation;
    // initialize with number of different fragments
    private Deque<Integer> fragmentIds = new ArrayDeque<>(3);

    private FragmentA fragmentA = new FragmentA();
    private FragmentB fragmentB = new FragmentB();
    private FragmentC fragmentC = new FragmentC();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentIds.push(R.id.navigation_home);
        showTabWithoutAddingToBackStack(fragmentA);
        navigation = findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(onNavigationItemClicked);
    }

    private BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemClicked = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            item.setChecked(true);
            int itemId = item.getItemId();
            if (fragmentIds.contains(itemId)) {
                fragmentIds.remove(itemId);
            }
            fragmentIds.push(itemId);
            showTabWithoutAddingToBackStack(getFragment(item.getItemId()));
            return true;
        }
    };

    private Fragment getFragment(int fragmentId) {
        switch (fragmentId) {
            case R.id.navigation_home:
                return fragmentA;
            case R.id.navigation_dashboard:
                return fragmentB;
            case R.id.navigation_notifications:
                return fragmentC;
        }
        return fragmentA;
    }

    void showTabWithoutAddingToBackStack(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, fragment.getClass().getSimpleName()).commit();
    }

    void setBottomTab(int id) {
        int itemIndex;
        switch (id) {
            case R.id.navigation_dashboard:
                itemIndex = 1;
                break;
            case R.id.navigation_notifications:
                itemIndex = 2;
                break;
            default:
            case R.id.navigation_home:
                itemIndex = 0;
        }
        navigation.getMenu().getItem(itemIndex).setChecked(true);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        fragmentIds.pop();
        if (!fragmentIds.isEmpty()) {
            showTabWithoutAddingToBackStack(getFragment(fragmentIds.peek()));
        } else {
            finish();
        }
    }
}


问:
Crystal Reports 11 Hide field until formula is run
I have a report in Crystal Reports 11 that has 2 images at the top of the page in the header.  I have a formula that runs down in the footer.  I would like to hide/show these images based on the value of the formula but when the report loads, the images load before the formula runs so they don't display properly.  Is there a way to delay load of something in the header until something has been run at the end?  Basically, load an image at the end of the report running?

The scenario is a dual receipt/invoice statement.  The formula balance owed resides in Footer Group Footer 3H.  The text boxes are in Group Header 3a.  At the time the report is run, @BalanceOwed shows a balance but when the report is fully run, @BalanceOwed is 0.  So in this case, the text box Receipt should show vs. the text box Invoice and then it works in the opposite if @BalanceOwed is > 0.

I know how to suppress something based on values but not based on values that don't exist at the time the report builds the element to hide/display.

Thanks.

Jayson

答:
Use the EvaluateAfter() function in the image selection formula. Give EvaluateAfter() the name of the formula in the footer that needs to run first.

You'll put the EvaluateAfter() in the conditional suppression formula of the field/image, at the top of the formula before any other logic.

EvaluateAfter() tells the crystal not to run the formula until after the specified formula has finished running.


问:
Eliminate style loading using media queries
I try to speed up initial loading by eliminating unnecessary downloading.
I split styles in to portrait and landscape css.
And want to load only one style based on media queries.
But is seems they are loading together.

  <link rel="stylesheet" type="text/css" href="style-p.css" media="(orientation: portrait)" />
  <link rel="stylesheet" type="text/css" href="style-l.css" media="(orientation: landscape)" />
```

答:
The purpose of media attribute in a <link> tag is to decide when the resource applies, not if it loads. It always loads.

So, simply put, what you seem to want is not possible without JavaScript. There is nothing in the current CSS Editor's Draft to indicate it should or will ever be possible using clean HTML + CSS.

If you think about it, this makes a lot of sense. All it takes to flip your device from landscape to portrait is a pet on the back by an enthusiastic colleague. And it would be impossible to provide a decent user experience if you had to wait for a resource to load before the layout change was applied.

The closest the spec gets to the subject is in:

User agents must re-evaluate media queries in response to changes in the user environment that they’re aware of, for example if the device is tiled from landscape to portrait orientation, and change the behavior of any constructs dependent on those media queries accordingly.

But there's an important note on this: most modern browsers made the following (smart) choice: they load <link> resources with media attributes evaluating to false as non-blocking to reduce the time needed to initially render the page to the user.

One of the first articles to go viral on the subject was written by Keith Clark. You might also find  Taylor Hunt's follow up interesting.

If you are still interested in loading stylesheets based on @media query conditions, you will need to load them using JavaScript. For performant detection of @media queries in JavaScript, I recommend enquire.js.


问:
Object doesn't support property or method 'json' servicestack-client HTTP post

servicestack-client version 1.0.9

Microsoft Edge 38.14393.2068.0

Microsoft EdgeHTML 14.14393

I am getting the following Javascript error in Microsoft Edge 38.14393.2068.0:

"Object doesn't support property or method 'json'"

I suspecting that this Microsoft Edge Javascript error is coming from the ServiceStack Typescript JsonServiceClient, you can find this npm package's source code is here

Use the standalone app below to reproduce this issue in MS Edge:

clone this repository, just follow these commands:

git clone https://github.com/Sweetog/servicestack-angular.git

npm install

npm run serve

Watch console in Chrome and MS Edge http://localhost:8080/#/sandbox

You will see Chrome works fine but MS Edge fails with the "Object doesn't support property or method 'json'" error.

If there is a valid bearerToken, both MS EDGE and Chrome requests work.

答:
I can't reproduce this exact error but I've found an issue with MS Edge where it throws a DOMException when calling W3C fetch's .json() API on an empty JSON response which is resolved in this commit. This fix is available from v0.0.41 of servicestack-client that's now available on npm.

If this doesn't solve your issue, please create a small stand-alone example which we can run that repro's the issue.


问:
Deprecated function: require_once()
Recently, I started converting my Drupal 6 module on PHP 5.2.x to Drupal 7 on PHP 5.3.x, and now I get following warning

Deprecated function: Assigning the
  return value of new by reference is
  deprecated in require_once() (line
  27 of
  C:\Users\ajinkya\Desktop\xampp\php\PEAR\SOAP\WSDL.php).

Line 27 of WSDL.php is : require_once 'HTTP/Request.php';

I am not able to figure out what is the cause of this warning.  Has the behavior of require_once() changed in PHP 5.3.x?

file.inc in Drupal 7 has a line : require_once DRUPAL_ROOT . '/includes/stream_wrappers.inc; and it does not throw any warning. Why?

If I put error_reporting(E_ALL & ~E_DEPRECATED); in a setting.php of Drupal 7, the warning goes away. Is it good to suppress a warning like that?

答:
The error message says that the code is using $something = &new SomeObject(); instead of $something = new SomeObject();.

&new was necessary in ancient PHP versions to ensure objects were always passed by reference. But in recent versions there is no reason to do this at all so it's deprecated.

I have no idea why your PHP reports an incorrect filename/line number though...

Title: Deprecated function: require_once()


问:
Possible to force CMake/MSVC to use UTF-8 encoding for source files without a BOM? C4819
All our source code is valid UTF-8, however some users on Windows cannot build them because their system is configured for a different encoding.

Without adding a BOM to source files, is it possible to tell MSVC to treat all source as UTF-8, irrespective of the users system encoding?

See MSDN's link regarding this topic (requires adding BOM header).

答:
You can try:

```<code>add_compile_options("$<$<C_COMPILER_ID:MSVC>:/utf-8>")
add_compile_options("$<$<CXX_COMPILER_ID:MSVC>:/utf-8>")
</code>```

By default, Visual Studio detects a byte-order mark to determine if the source file is in an encoded Unicode format, for example, UTF-16 or UTF-8. If no byte-order mark is found, it assumes the source file is encoded using the current user code page, unless you have specified a code page by using /utf-8 or the /source-charset option.

References

Docs - Visual C++ - Documentation - IDE and Tools - Building - Build Reference: /utf-8 (Set Source and Executable character sets to UTF-8)

Body:
You can try:

add_compile_options("$<$<C_COMPILER_ID:MSVC>:/utf-8>")
add_compile_options("$<$<CXX_COMPILER_ID:MSVC>:/utf-8>")

By default, Visual Studio detects a byte-order mark to determine if the source file is in an encoded Unicode format, for example, UTF-16 or UTF-8. If no byte-order mark is found, it assumes the source file is encoded using the current user code page, unless you have specified a code page by using /utf-8 or the /source-charset option.

References

Docs - Visual C++ - Documentation - IDE and Tools - Building - Build Reference: /utf-8 (Set Source and Executable character sets to UTF-8)


问:
How to use multiple DB connections using .env in Lumen 5.5..?
I have installed Lumen 5.5 and configured .env :

```<code>APP_ENV=local
APP_DEBUG=true
APP_KEY=2gh4RD89kWa87clEs6Vhjso3XhsFo3dR
APP_TIMEZONE=UTC

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=XXXXXX
DB_USERNAME=XXXXXX
DB_PASSWORD=XXXXXX

CACHE_DRIVER=memcached
QUEUE_DRIVER=sync
</code>```

and created a model using Eloquent :

```<code>namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Test extends Model {

    public $timestamps = false;
    protected $connection = 'foo';
}
</code>```

Now there is no documention on the official site to configure multiple DB connection in .env file. My single connection is working perfectly fine but now I need to add another DB connection details.

What I have tried so far :

Created db config file as app/config/database.php with multiple db details but my setup doesn't get affected whatever i write in that file. It's only using .env to get connection details.

Tried to add multiple DB connection details in .env file like :

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=XXXXXX
DB_USERNAME=XXXXXX
DB_PASSWORD=XXXXXX

FOO_DB_CONNECTION=mysql
FOO_DB_HOST=127.0.0.1
FOO_DB_PORT=3306
FOO_DB_DATABASE=FOOXXXXXX
FOO_DB_USERNAME=FOOXXXXXX
FOO_DB_PASSWORD=FOOXXXXXX

DB_CONNECTION_FOO=mysql
DB_HOST_FOO=127.0.0.1
DB_PORT_FOO=3306
DB_DATABASE_FOO=FOOXXXXXX
DB_USERNAME_FOO=FOOXXXXXX
DB_PASSWORD_FOO=FOOXXXXXX

But it just keep giving me this error :

```<code>(1/1) InvalidArgumentException
Database [foo] not configured.
</code>```

I have tried everything I found on Google.

答:
The way I configured in my project (it is in Lumen 5.4) is as below:

in the config/database.php

```<code>'pgsql' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST', 'db'),
        'port'     => env('DB_PORT', 5432),
        'database' => env('DB_DATABASE', 'service_db'),
        'username' => env('DB_USERNAME', 'service_user'),
        'password' => env('DB_PASSWORD'),
        'charset'  => env('DB_CHARSET', 'utf8'),
        'prefix'   => env('DB_PREFIX', ''),
        'schema'   => env('DB_SCHEMA', 'public'),
    ],

    'pgsql2' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST2', 'db'),
        'port'     => env('DB_PORT', 5432),
        'database' => env('DB_DATABASE2', 'service_db'),
        'username' => env('DB_USERNAME2', 'service_user'),
        'password' => env('DB_PASSWORD2'),
        'charset'  => env('DB_CHARSET', 'utf8'),
        'prefix'   => env('DB_PREFIX', ''),
        'schema'   => env('DB_SCHEMA2', 'public'),
    ],
</code>```

I have created 2 connections with 2 different names and each connection points to a different env variable for db host/database/username/password/schema. If this doesn't help, post your database.php file.

Body:
I have installed Lumen 5.5 and configured .env :

APP_ENV=local
APP_DEBUG=true
APP_KEY=2gh4RD89kWa87clEs6Vhjso3XhsFo3dR
APP_TIMEZONE=UTC

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=XXXXXX
DB_USERNAME=XXXXXX
DB_PASSWORD=XXXXXX

CACHE_DRIVER=memcached
QUEUE_DRIVER=sync

and created a model using Eloquent :

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Test extends Model {

    public $timestamps = false;
    protected $connection = 'foo';
}

Now there is no documention on the official site to configure multiple DB connection in .env file. My single connection is working perfectly fine but now I need to add another DB connection details.

What I have tried so far :

Created db config file as app/config/database.php with multiple db details but my setup doesn't get affected whatever i write in that file. It's only using .env to get connection details.

Tried to add multiple DB connection details in .env file like :

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=XXXXXX
DB_USERNAME=XXXXXX
DB_PASSWORD=XXXXXX

FOO_DB_CONNECTION=mysql
FOO_DB_HOST=127.0.0.1
FOO_DB_PORT=3306
FOO_DB_DATABASE=FOOXXXXXX
FOO_DB_USERNAME=FOOXXXXXX
FOO_DB_PASSWORD=FOOXXXXXX

DB_CONNECTION_FOO=mysql
DB_HOST_FOO=127.0.0.1
DB_PORT_FOO=3306
DB_DATABASE_FOO=FOOXXXXXX
DB_USERNAME_FOO=FOOXXXXXX
DB_PASSWORD_FOO=FOOXXXXXX

But it just keep giving me this error :

(1/1) InvalidArgumentException
Database [foo] not configured.

I have tried everything I found on Google.

Body:
The way I configured in my project (it is in Lumen 5.4) is as below:

in the config/database.php

'pgsql' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST', 'db'),
        'port'     => env('DB_PORT', 5432),
        'database' => env('DB_DATABASE', 'service_db'),
        'username' => env('DB_USERNAME', 'service_user'),
        'password' => env('DB_PASSWORD'),
        'charset'  => env('DB_CHARSET', 'utf8'),
        'prefix'   => env('DB_PREFIX', ''),
        'schema'   => env('DB_SCHEMA', 'public'),
    ],

    'pgsql2' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_HOST2', 'db'),
        'port'     => env('DB_PORT', 5432),
        'database' => env('DB_DATABASE2', 'service_db'),
        'username' => env('DB_USERNAME2', 'service_user'),
        'password' => env('DB_PASSWORD2'),
        'charset'  => env('DB_CHARSET', 'utf8'),
        'prefix'   => env('DB_PREFIX', ''),
        'schema'   => env('DB_SCHEMA2', 'public'),
    ],

I have created 2 connections with 2 different names and each connection points to a different env variable for db host/database/username/password/schema. If this doesn't help, post your database.php file.


问:
Is there any performance comparison between Perl web frameworks?
I have seen mentions (which sounded like unsubstantiated opinions, and dated ones at that) that Embperl is the fastest Perl web framework.

I was wondering if there's a consensus on the relative speed of the major stable Perl web frameworks, or ideally, some sort of fact-based performance comparisons between implementations of the same sample webapps, or individual functionalities (e.g. session handling or form data processing), etc...?

UPDATE: This question is specifically about the speed comparison of different frameworks, executing identical/equivalent tasks. I appreciate the good intentions, but I already know that speed is not the only criteria I should be looking at. I wasn't asking for philosophical advice. And believe it or not, being frameworks, you CAN actually compare their speed on an apple-to-apple basis by running identically purposed tasks/code/apps on them (e.g. render a given form with a given set of templated inserts etc...), even if the full functionality of each framework is not 100% the same.

答:
I don't want to go into the interpretation discussion (for most real world scenarios these overheads have no impact at all) - but here are my tests:

1. Pure Plack

```<code>zby@zby:~/progs/bench$ cat app.psgi

sub {
   my ( $env ) = @_;
   return [
       200,
       [ 'Content-Type' => 'text/text' ],
       [ 'Hello World' ]
       ];
}
zby@zby:~/progs/bench$ plackup
HTTP::Server::PSGI: Accepting connections at http://0:5000/
</code>```

With simple ab -n 10000 I get

Requests per second:    2168.05 [#/sec] (mean)

2. Dancer

```<code>zby@zby:~/progs/bench$ cat dancer.pl
 #!/usr/bin/perl
           use Dancer;

           get '/' => sub {
               return "Why, hello there";
           };

           dance;
zby@zby:~/progs/bench$ perl dancer.pl
>> Dancer server 1950 listening on http://0.0.0.0:3000
== Entering the development dance floor ...
</code>```

With similar ab test I get
Requests per second:    1570.49 [#/sec] (mean)

3. Mojolicious::Lite

```<code>zby@zby:~/progs/bench$ cat mojo.pl
 # Using Mojolicious::Lite will enable "strict" and "warnings"
    use Mojolicious::Lite;

    # Route with placeholder
    get '/' => sub {
        my $self = shift;
        $self->render(text => "Hello!");
    };

    # Start the Mojolicious command system
    app->start;
zby@zby:~/progs/bench$ perl mojo.pl daemon
Sat Jan 22 20:37:01 2011 info Mojo::Server::Daemon:320 [2315]: Server listening (http://*:3000)
Server available at http://*:3000.
</code>```

Result:
Requests per second:    763.72 [#/sec] (mean)

4. Catalyst.

Unfortunately the code is much too long to be presented here in its entirety, but the Root controller contains:

```<code>sub index :Path :Args(0) {
    my ( $self, $c ) = @_;

    # Hello World
    $c->response->body( 'Hello World' );
}
</code>```

The result is:

Requests per second:    727.93 [#/sec] (mean)

5. WebNano

zby@zby:~/progs/bench$ cat webnano.psgi

```<code>{
    package MyApp;
    use base 'WebNano';
    1;
}

{
    package MyApp::Controller;
    use base 'WebNano::Controller';

    sub index_action {
        my $self = shift;
        return 'This is my home';
    }
    1;
}
MyApp->new()->psgi_callback;
zby@zby:~/progs/bench$ plackup webnano.psgi
HTTP::Server::PSGI: Accepting connections at http://0:5000/
</code>```

And the result:

Requests per second:    1884.54 [#/sec] (mean)

This will change after some more features are added.

Body:
I don't want to go into the interpretation discussion (for most real world scenarios these overheads have no impact at all) - but here are my tests:

1. Pure Plack

zby@zby:~/progs/bench$ cat app.psgi

sub {
   my ( $env ) = @_;
   return [
       200,
       [ 'Content-Type' => 'text/text' ],
       [ 'Hello World' ]
       ];
}
zby@zby:~/progs/bench$ plackup
HTTP::Server::PSGI: Accepting connections at http://0:5000/

With simple ab -n 10000 I get

Requests per second:    2168.05 [#/sec] (mean)

2. Dancer

zby@zby:~/progs/bench$ cat dancer.pl
 #!/usr/bin/perl
           use Dancer;

           get '/' => sub {
               return "Why, hello there";
           };

           dance;
zby@zby:~/progs/bench$ perl dancer.pl
>> Dancer server 1950 listening on http://0.0.0.0:3000
== Entering the development dance floor ...

With similar ab test I get
Requests per second:    1570.49 [#/sec] (mean)

3. Mojolicious::Lite

zby@zby:~/progs/bench$ cat mojo.pl
 # Using Mojolicious::Lite will enable "strict" and "warnings"
    use Mojolicious::Lite;

    # Route with placeholder
    get '/' => sub {
        my $self = shift;
        $self->render(text => "Hello!");
    };

    # Start the Mojolicious command system
    app->start;
zby@zby:~/progs/bench$ perl mojo.pl daemon
Sat Jan 22 20:37:01 2011 info Mojo::Server::Daemon:320 [2315]: Server listening (http://*:3000)
Server available at http://*:3000.

Result:
Requests per second:    763.72 [#/sec] (mean)

4. Catalyst.

Unfortunately the code is much too long to be presented here in its entirety, but the Root controller contains:

sub index :Path :Args(0) {
    my ( $self, $c ) = @_;

    # Hello World
    $c->response->body( 'Hello World' );
}

The result is:

Requests per second:    727.93 [#/sec] (mean)

5. WebNano

zby@zby:~/progs/bench$ cat webnano.psgi

{
    package MyApp;
    use base 'WebNano';
    1;
}

{
    package MyApp::Controller;
    use base 'WebNano::Controller';

    sub index_action {
        my $self = shift;
        return 'This is my home';
    }
    1;
}
MyApp->new()->psgi_callback;
zby@zby:~/progs/bench$ plackup webnano.psgi
HTTP::Server::PSGI: Accepting connections at http://0:5000/

And the result:

Requests per second:    1884.54 [#/sec] (mean)

This will change after some more features are added.


问:
Making shader takes vertexArray as canvas instead of the window
Currently developing an open source GUI SFML based library, but struggling a bit with shaders. So far I've managed to render shader with no problem, but instead of applying the shader on the current object, it's apply it for the whole window, but only visible in the object range.

Here's my simple code:

```<code>#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>

#include <iostream>

const char *glsl = R"(
    #version 330 core
    uniform vec2 u_resolution;

    void main() {
        vec2 pos = gl_FragCoord.xy / u_resolution;
        float radius = 0.4;
        float d = distance(pos, vec2(0.5));

        gl_FragColor = d <= radius ? vec4(pos.y,pos.y/2.,pos.y, 1.0) : vec4(d*0.8, d*0.8, d*0.8, 1.0);

        //gl_FragColor = vec4(0.0, 0.5, 1.0, 1.0);
    }
)";

const char *pos = R"(
    // some default shader I've found
    // adding #version 330 core will complain for outdated gl_Position variable..

    void main() {
        gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

        gl_FrontColor = gl_Color;
    }
)";

int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "GLSL", sf::Style::Default);

    // create a quad
    sf::VertexArray quad(sf::Quads, 4);
    // define it as a rectangle, located at (10, 10) and with size 100x100
    quad[0].position = sf::Vector2f(100, 100);
    quad[1].position = sf::Vector2f(410, 100);
    quad[2].position = sf::Vector2f(410, 410);
    quad[3].position = sf::Vector2f(100, 410);

    sf::Shader shader;
    // the following line is the same as shader.loadFromMemory(pos, glsl);
    shader.loadFromMemory(glsl, sf::Shader::Fragment);
    shader.setUniform("u_resolution", sf::Vector2f(800, 600));

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear(sf::Color(244,244,244));

        window.draw(quad, &shader);

        window.display();
    }

    return 0;
}
</code>```

Not sure what do to for now, but I guess that pos shader should affect how the rendering is done. Thanks!

答:
Just some minor changes needed. I'm not exactly sure what's the best way to get it done in any more modern shader version, but if you omit any version markers (i.e. using legacy code), it's quick to change:

First of all, your individual vertices (or more specific the rendered fragments) don't know where they are relative to the quad being drawn. Luckily you can abuse texture coordinates for this. For example, define the top left as (0, 0) and the bottom right as (1, 1). This way their values will range from 0 to 1 based on where the fragment is. This is basically what your existing shader code calculates as pos.

So let's start by adding the texture coordinates:

```<code>quad[0].position = sf::Vector2f(100, 100);
quad[0].texCoords = sf::Vector2f(0, 0);
quad[1].position = sf::Vector2f(410, 100);
quad[1].texCoords = sf::Vector2f(1, 0);
quad[2].position = sf::Vector2f(410, 410);
quad[2].texCoords = sf::Vector2f(1, 1);
quad[3].position = sf::Vector2f(100, 410);
quad[3].texCoords = sf::Vector2f(0, 1);
</code>```

Now all we have to do is assign the texture coordinates to pos (or better remove pos completely). For simplification I'll just go with the assignment:

```<code>vec2 pos = gl_TexCoord[0].xy;
</code>```

However, this will cause the shader compiler to complain, since gl_TexCoord got removed. So for testing I just removed the precompiler line and the result looks like what you've had in mind I guess:

Body:
Currently developing an open source GUI SFML based library, but struggling a bit with shaders. So far I've managed to render shader with no problem, but instead of applying the shader on the current object, it's apply it for the whole window, but only visible in the object range.

Here's my simple code:

#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>

#include <iostream>

const char *glsl = R"(
    #version 330 core
    uniform vec2 u_resolution;

    void main() {
        vec2 pos = gl_FragCoord.xy / u_resolution;
        float radius = 0.4;
        float d = distance(pos, vec2(0.5));

        gl_FragColor = d <= radius ? vec4(pos.y,pos.y/2.,pos.y, 1.0) : vec4(d*0.8, d*0.8, d*0.8, 1.0);

        //gl_FragColor = vec4(0.0, 0.5, 1.0, 1.0);
    }
)";

const char *pos = R"(
    // some default shader I've found
    // adding #version 330 core will complain for outdated gl_Position variable..

    void main() {
        gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;

        gl_FrontColor = gl_Color;
    }
)";

int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "GLSL", sf::Style::Default);

    // create a quad
    sf::VertexArray quad(sf::Quads, 4);
    // define it as a rectangle, located at (10, 10) and with size 100x100
    quad[0].position = sf::Vector2f(100, 100);
    quad[1].position = sf::Vector2f(410, 100);
    quad[2].position = sf::Vector2f(410, 410);
    quad[3].position = sf::Vector2f(100, 410);

    sf::Shader shader;
    // the following line is the same as shader.loadFromMemory(pos, glsl);
    shader.loadFromMemory(glsl, sf::Shader::Fragment);
    shader.setUniform("u_resolution", sf::Vector2f(800, 600));

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear(sf::Color(244,244,244));

        window.draw(quad, &shader);

        window.display();
    }

    return 0;
}

Not sure what do to for now, but I guess that pos shader should affect how the rendering is done. Thanks!

Body:
Just some minor changes needed. I'm not exactly sure what's the best way to get it done in any more modern shader version, but if you omit any version markers (i.e. using legacy code), it's quick to change:

First of all, your individual vertices (or more specific the rendered fragments) don't know where they are relative to the quad being drawn. Luckily you can abuse texture coordinates for this. For example, define the top left as (0, 0) and the bottom right as (1, 1). This way their values will range from 0 to 1 based on where the fragment is. This is basically what your existing shader code calculates as pos.

So let's start by adding the texture coordinates:

quad[0].position = sf::Vector2f(100, 100);
quad[0].texCoords = sf::Vector2f(0, 0);
quad[1].position = sf::Vector2f(410, 100);
quad[1].texCoords = sf::Vector2f(1, 0);
quad[2].position = sf::Vector2f(410, 410);
quad[2].texCoords = sf::Vector2f(1, 1);
quad[3].position = sf::Vector2f(100, 410);
quad[3].texCoords = sf::Vector2f(0, 1);

Now all we have to do is assign the texture coordinates to pos (or better remove pos completely). For simplification I'll just go with the assignment:

vec2 pos = gl_TexCoord[0].xy;

However, this will cause the shader compiler to complain, since gl_TexCoord got removed. So for testing I just removed the precompiler line and the result looks like what you've had in mind I guess:


问:
python recursion return issue
Could you please explain to me why I can't catch return event in this case ??

```<code>s1 = "(){}[]"
s2 = "([{}])"
s3 = "(}"
s4 = "[(])"
s5 = "[({})]((]"

def validBraces(string):
    lst = ['()','{}','[]']
    for i in range(len(string)-1):
        braces = string[i]+ string[i+1]
        if braces in lst:
               validBraces(string[:i]+string[i+2:])

    if len(string) == 0:
        print("True")
        return True

    return False

print (validBraces(s1))
</code>```

So it's going to pass every time the return event, what is wrong here ?
So, I can print "True" but cant stop it and return True.....

答:
The following incorporates Tom's answer, along with a complete test and other improvements.</p>

```<code>s1 = "(){}[]"
s2 = "([{}])"
s3 = "(}"
s4 = "[(])"
s5 = "[({})]((]"

def validBraces(string):
    lst = ['()','{}','[]']
    for i in range(len(string)-1):
        braces = string[i:i+2]
        if braces in lst:
            return validBraces(string[:i]+string[i+2:])

    return not string

for s in (s1, s2, s3, s4, s5):
    print (validBraces(s))
# should be True, True, False, False, False
</code>```

Title: python recursion return issue

Body:
Could you please explain to me why I can't catch return event in this case ??

s1 = "(){}[]"
s2 = "([{}])"
s3 = "(}"
s4 = "[(])"
s5 = "[({})]((]"

def validBraces(string):
    lst = ['()','{}','[]']
    for i in range(len(string)-1):
        braces = string[i]+ string[i+1]
        if braces in lst:
               validBraces(string[:i]+string[i+2:])

    if len(string) == 0:
        print("True")
        return True

    return False

print (validBraces(s1))

So it's going to pass every time the return event, what is wrong here ?
So, I can print "True" but cant stop it and return True.....

Body:
The following incorporates Tom's answer, along with a complete test and other improvements.

s1 = "(){}[]"
s2 = "([{}])"
s3 = "(}"
s4 = "[(])"
s5 = "[({})]((]"

def validBraces(string):
    lst = ['()','{}','[]']
    for i in range(len(string)-1):
        braces = string[i:i+2]
        if braces in lst:
            return validBraces(string[:i]+string[i+2:])

    return not string

for s in (s1, s2, s3, s4, s5):
    print (validBraces(s))
# should be True, True, False, False, False