text:
Q: QDockWidget layout with no central widget I have a problem with QDockWidget. I'm using Qt Designer, and I would like to build an app with only dock-widgets, and have a small bar above for properties. The problem is that I cannot build the app without a main QWidget (I mean with only QDockWidgets).
Here is my screenshot:

Annotation 1) - this is the space that I can't remove. When I remove it from xml, Qt Designer crashes. If it is not removable, how can I set the left QDockWidget and the right QDockWidget to have half of the entire window width?

A: You can remove centralWidget using setCentralWidget(0);

A: This cannot be done from within Qt Designer. However, there is a Qt Forum Thread which suggests there may be a way to do it programmatically.
Firstly, you have to set the main-window dockNestingEnabled property to true in Qt Designer. Then, after you create the ui, programmatically delete the central widget, and then also remove, re-add and re-show all the dock widgets.
When I tested this, I found that I needed to show the dock-widgets with a single-shot timer, otherwise I couldn't resize them vertically. However, even with that little hack, I still found that resizing doesn't always work properly. So I'm not convinced that Qt really supports this way of using dock-widgets.

A: After creating GUI in Qt Designer and translating it to ui_file. Add one line in your __init___ call script:
self.ui.centralwidget.hide()

you may need to check if your central widget is called the as above

A: Remove all references to the central widget:
pyuic5 -x uifile.ui -o main.py
sed -i /centralwidget/d main.py

Running python3 main.py should get you the desired behaviour.


text:
Q: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128) I am building a web application using Flask and Google App Engine. One of the pages in this web application makes a call via YouTube APIs to get videos given a search term.
I get the following error when I try to query YoutubeVids.html.
This only happens when when I pass a certain parameter via Jinja2 templates to the page.
file "/Users/xxxxx/App-Engine/src/templates/YoutubeVids.html", line 1, in top-level template code
    {% extends "master.html" %}
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)

INFO     2014-01-27 22:39:40,963 module.py:612] default: "GET /xxx/yyyy HTTP/1.1" 500 291

A: Figured it out.
I put the following at the start of my python file
import sys
reload(sys)
sys.setdefaultencoding("utf-8")

A: From the docs: Jinja2 is using Unicode internally which means that you have to pass Unicode objects to the render function or bytestrings that only consist of ASCII characters.
A normal string in Python 2.x is a bytestring. To make it unicode use:
byte_string = 'a Python string which contains non-ascii data like €äãü'
unicode_string = byte_string.decode('utf-8')

More: http://blog.notdot.net/2010/07/Getting-unicode-right-in-Python

redpajama_set_name: RedPajamaStackExchange


text:
Q: 8GB memory stick not recognised on Gigabyte GA-B75M-D3V rev.2 I have currently running on my Win7 64-bit i3 system 2x 2GB 1333 sticks running well. I need to upgrade to 8 GB either 1600 or 1333 but have failed to get the system to boot up at all. when i replace them with the 2 x 2GB things go back to normal. Is there something I need to do to get the Mobo to reconise these new 8 gb sticks?

A: I would go with Corsair 1x8gb 1600 or 2x4gb 1600 or to max it out 2x8gb 1600. Of the 8gb sticks listed on the Memory Support List I would only use the Corsair brand as I feel the others are inferior in quality (totally opinion though). If the sticks you got are on the list running at 1600 and didn't work you can try to go into your bios and reduce the speed to 1333 and see if they work. If they do I would return them and get one of the ones I suggested. Then try those. If the Corsairs don't work at 1600  then I would once again return those and get Corsair running at 1333 until you can get your slots to run at the correct speed. Which is a different issue. Ex. messed settings in your Bios.


text:
Q: Jquery mobile toggle button data-theme on button press I have a buttons of a certain class

        Clear

</div

and I want to toggle the theme color onclick. The toggle ID changes and does the data-theme letter but the color doesn't change. This is all the things (trigger,create, refresh) I've tried based upon other posts
$(".prog-day a").click(function() {
    console.log("clicked a day button");
    progToggle = $(this).attr("progToggle");
    if ( progToggle == "1"  ) {
        $(this).attr("data-theme","b").refresh;
        $(this).attr("progToggle","0");
        $(this).trigger('create');
        $(this).trigger('refresh');
        $('.prog-day p').html($(this).attr("progToggle")+$(this).attr("data-theme"));
        progToggle = $(this).attr("progToggle");
     }
     else {
        $(this).attr("data-theme","d").refresh;
        $(this).attr("progToggle","1");
        $(this).trigger('create');
        $(this).trigger('refresh');
        $('.prog-day p').html($(this).attr("progToggle")+$(this).attr("data-theme"));
        progToggle = $(this).attr("progToggle");
    }
});

What am I missing here. Am I better off skipping this JQM stying stuff and just do it myself? I'd actually like the buttons to toggle on the down press, not the release. Perhaps you could fiddle with http://jsfiddle.net/PLx8v/3/

A: If you're checking for equality, make sure your if-statement has 3 equal signs
if( progToggle === '1' ) {}


text:
Q: Prove: $\lim_{n\to\infty}{\sum_{m=0}^{n}{\sum_{k=0}^{n-m}{\frac{2^{n-m-k}}{n-m+1}\,\frac{{{2k}\choose{k}}{{2m}\choose{m}}}{{{2n}\choose{n}}}}}}=\pi$ Consider the following limit:
$$\lim_{n\to\infty}{\sum_{m=0}^{n}{\sum_{k=0}^{n-m}{\left[\frac{2^{n-m-k}}{n-m+1}\,\frac{{{2k}\choose{k}}{{2m}\choose{m}}}{{{2n}\choose{n}}}\right]}}}=\pi$$
I cooked this up while playing around with power series (details below).
Is there a more direct way to prove this limit?

Consider the functions $f(x)=\frac{\tan^{-1}(\sqrt{1-x})}{\sqrt{1-x}}$, $g(x)=\frac{\pi/2-\tan^{-1}(\sqrt{1-x})}{\sqrt{1-x}}$. We write the power series:
$$f(x)=\sum_{n=0}^{\infty}{(s_n\pi-r_n)x^n},\qquad{g}(x)=\sum_{n=0}^{\infty}{(s_n\pi+r_n)x^n}$$
where computing the first few terms suggests that $r_n$, $s_n$ are rational.
Indeed, we have $\frac{\pi/4-\tan^{-1}(\sqrt{1-x})}{\sqrt{1-x}}=\frac{g(x)-f(x)}{2}=\sum{r_nx^n}$, and $\frac{1/4}{\sqrt{1-x}}=\frac{g(x)+f(x)}{2\pi}=\sum{s_nx^n}$.
Using $\frac{d}{dx}[\tan^{-1}(\sqrt{1-x})]=-\frac{1}{2(2-x)\sqrt{1-x}}$, we can use the power series for $\frac{1}{2-x}$ and $\frac{1}{\sqrt{1-x}}$ to calculate the power series for $(\pi/4-\tan^{-1}(\sqrt{1-x}))$, which consists of only rational coefficients. Combining this with the power series for $\frac{1}{\sqrt{1-x}}$ gives:
$$r_n=\frac{1}{2}\sum_{m=0}^{n-1}{\sum_{k=0}^{n-m-1}{\frac{{{2k}\choose{k}}{{2m}\choose{m}}}{(n-m)\cdot2^{k+m+n}}}}$$
We easily get $s_n=\frac{1}{2^{2n+2}}{2n\choose{n}}$.
Now, because no branch of $f(z)$ has singularities anywhere (the apparent singularity at $z=1$ is removable), the coefficients of the power series of $f$ must tend to zero.
Hence $\lim_{n\to\infty}{\frac{r_{n+1}}{s_{n+1}}}=\pi$, and the desired limit follows after simplifying.

Notes:
1) It is easily shown that:
$$s_n\pi-r_n=\int_{0}^{\pi/4}{\sin^{2n}{\theta}\,d\theta},\qquad{s}_n\pi+r_n=\int_{\pi/4}^{\pi/2}{\sin^{2n}{\theta}\,d\theta}$$
2) The above proof actually shows:
$$\lim_{n\to\infty}{\left(1+\frac{1}{2n+1}\right)\sum_{m=0}^{n}{\sum_{k=0}^{n-m}{\left[\frac{2^{n-m-k}}{n-m+1}\,\frac{{{2k}\choose{k}}{{2m}\choose{m}}}{{{2n}\choose{n}}}\right]}}}=\pi$$
which converges much faster than the given limit.

A:
I think OP did a really good job and this answer aims to indicate that it is plausible to obtain the specific type of generating functions like $\arctan$ as stated by OP. Here  we  start with the binomial expression
  \begin{align*}
q_n:=\sum_{m=0}^n\sum_{k=0}^{n-m}\binom{2k}{k}\binom{2m}{m}\frac{2^{n-m-k}}{n-m+1}\tag{1}
\end{align*}
  which corrresponds to OPs limit expression without the factor $\binom{2n}{n}^{-1}$ and derive from it a generating function.
Note that since $q_n=\frac{1}{4^n}r_{n+1}$ OPs claim can be stated as
  \begin{align*}
q_n\sim \pi\binom{2n}{n}\sim\sqrt{\frac{\pi}{n}}\cdot 4^n
\end{align*}
  where we use the asymptotic formula of the central binomial coefficient.

Two aspects:

*

*We use the coefficient of operator $[z^n]$ to denote the coefficient of $z^n$ in a series. Recalling the generating function of the central binomial coefficient we can write for instance
\begin{align*}
[z^n]\frac{1}{\sqrt{1-4z}}=\binom{2n}{n}\tag{2}
\end{align*}

*We can sum up coefficients $a_n$ by multiplication with $\frac{1}{1-z}$. If $A(z)=\sum_{n=0}^\infty a_nz^n$ we have
\begin{align*}
\frac{1}{1-z}A(z)&=\sum_{n=0}^\infty\left( \sum_{k=0}^na_k\right)z^n
\end{align*}
Somewhat more general by multiplication with $\frac{1}{1-pz}$ we have
\begin{align*}
  \frac{1}{1-pz}A(z)&=\sum_{n=0}^\infty \left(\sum_{k=0}^na_kp^{n-k}\right) z^n\tag{3}
  \end{align*}

We obtain
  \begin{align*}
\color{blue}{\sum_{m=0}^n}&\color{blue}{\sum_{k=0}^{n-m}\binom{2k}{k}\binom{2m}{m}\frac{2^{n-m-k}}{n-m+1}}\\
&=\int_{0}^1\sum_{m=0}^n\sum_{k=0}^{n-m}\binom{2k}{k}\binom{2m}{m}2^{n-m-k}z^{n-m}\,dz\tag{4}\\
&=\int_{0}^1\sum_{m=0}^n\binom{2m}{m}z^{n-m}\sum_{k=0}^{n-m}\binom{2k}{k}2^{n-m-k}\,dz\tag{5}\\
&=\int_{0}^1\sum_{m=0}^n\binom{2m}{m}z^{n-m}[t^{n-m}]\frac{1}{(1-2t)\sqrt{1-4t}}\,dz\tag{6}\\
&=\int_{0}^1\sum_{m=0}^\infty\binom{2n-2m}{n-m}z^m[t^m]\frac{1}{(1-2t)\sqrt{1-4t}}\,dz\tag{7}\\
&=\int_{0}^\infty\sum_{m=0}^\infty[u^{n-m}]\frac{1}{\sqrt{1-4u}}z^m[t^m]\frac{1}{(1-2t)\sqrt{1-4t}}\,dz\tag{8}\\
&=[u^n]\frac{1}{\sqrt{1-4u}}\int_{0}^1\sum_{m=0}^\infty(zu)^m[t^m]\frac{1}{(1-2t)\sqrt{1-4t}}\,dz\tag{9}\\
&=[u^n]\frac{1}{\sqrt{1-4u}}\int_{0}^1\frac{1}{(1-2zu)\sqrt{1-4zu}}\,dz\tag{10}\\
&=[u^n]\frac{1}{\sqrt{1-4u}}\left.\frac{\arctan\left(\sqrt{1-4zu}\right)}{u}\right|_{z=0}^{z=1}\tag{11}\\
&\,\,\color{blue}{=[u^{n+1}]\frac{1}{\sqrt{1-4u}}\left(-\arctan\left(\sqrt{1-4u}\right)+\frac{\pi}{4}\right)}\tag{12}
\end{align*}
  and we also get when deriving generating functions directly from (1) the same function as OP. The scaling factor $4$ in $\sqrt{1-4u}$ is from formula (2) and indicates the connection between $q_n$ and $r_n$ as stated at the beginning of this post.

Comment:

*

*In (4) we use $\frac{1}{p+1}=\int_0^1z^{p}\,dz$ where $p\ne -1$.

*In (5) we do a rearrangement only.

*In (6) we apply the coefficient of operator by using (2) and (3) with $p=2$.

*In (7) we change the order of summation by $m\to n-m$ and we replace the upper index $n$ by $\infty$ without changing anything, since $\binom{2n-2m}{n-m}=0$ when $m>n$.

*In (8) we apply again  the coefficient of operator to $\binom{2n-2m}{n-m}$ according to (2).

*In (9) we use the linearity of the operators and apply the rule $[u^{p-q}]A(u)=[u^p]u^qA(u)$.

*In (10) we apply the substitution rule of the coefficient of operator with $t=zu$
\begin{align*}
A(z)=\sum_{m=0}^\infty a_m z^m=\sum_{m=0}^\infty z^m [u^m]A(u)
\end{align*}

*In (11) we integrate obtaining the $\arctan$ function.

*In (12) we finally evaluate the $\arctan$ function at lower and  upper  limit and apply again  the rule $[u^n]\frac{1}{u}A(u)=[u^{n+1}]A(u)$ as we did in (10).


text:
Q: What is the difference between $("#id div") and $("#id > div")? I'm confused with these two.
I have a table structure like following;

X

Y

I'm prepend something in the table with Jquery. Now when I'm doing $("#previewSection div") it gives me something like m.fn.init[253] but when I call $("#previewSection > div") actually gives me the html like this [
…
] which I originally wanted.
I've checked JQuery selectors and it said if I use > it gives direct child of the selector and if I don't use it all div of the selector; but both should give me the html why I'm getting objects?? Thank you in advance.

A: The difference between X Y and X > Y is that the latter will only select children (immediate descendants) of X.
Given this little snippet:

div a       - works
div span    - works
div > a     - works
div > span  - nope, no span is an immediate descendant (child) of a div


text:
Q: How can I split this string? I have this string:
a = "hy what are you doing [Zoho Reports] will you like? [Zoho Books] reply"

and I want to split it so the result is like this:
hy
what
are
you
doing
[Zoho Reports]
will
you
like?
[Zoho Books]
reply

How can I loop that string to achieve those results? I'm currently doing this:
a.split("")

but it splits up "[Zoho Reports]" into "[Zoho" and "Reports]", which I don't want.

A: In this case, you should use scan instead of split because it is easier to characterize what you want rather than what you want to throw out.
Similar to Bozhidar's answer, but you don't need the complication.
a.scan(/\[.*?\]|\S+/)

A: Not very pretty, but gets the job done:
a.scan(/(\S+)|(\[.+?\])/).map(&:compact).flatten

Later I noticed that the groups I used were not necessary at all and without them the solution could be simplified to:
a.scan(/\S+|\[.+?\]/)


text:
Q: For VS2010 (C++) what causes the long delay between clicking on "Build" and when the build actually starts? I have a simple one-project solution in C++. From the IDE I click on Build Solution and it takes 40 seconds before anything happens. Then 17 seconds to actually do the compiling and linking. If I click Build Solution again, there is another 40 second delay. devenv.exe is busy doing something as it is using 13% of my total CPU during this time.
If I call msbuild directly, it starts immediately. And it doesn't recompile unless it is truly out of date. So it doesn't seem to be a problem with msbuild at all.
I have Googled and chased down lots of articles, but most of them talk about why msbuild is slow or failing, not why the IDE is slow to call msbuild. I've even got an external tool setup using msbuild and it starts immediately. BTW, that tool is based on this:
http://www.hanselman.com/blog/HackParallelMSBuildsFromWithinTheVisualStudioIDE.aspx
I have checked for missing files using the devenv.exe.config change and I do get items like:
devenv.exe Information: 0 :
Project 'C:\Users\...\XFPMon\XFPMon.vcxproj' not up to date because 2 build outputs were missing.
devenv.exe Information: 0 :
up to date is missing: 'C:\WINDOWS\TEMP\AEXAM\AEX7C29.TMP'
devenv.exe Information: 0 :
up to date is missing: 'C:\WINDOWS\TEMP\AEXAM\AEX7C28.TMP'

The change to devenv.exe.config was to insert these:
<system.diagnostics>
    <switches>
        <add name="CPS" value="4" />
    </switches>
</system.diagnostics>

and then use DbgView to trace the output during the build. I cannot imagine why devenv.exe would think that TEMP files would be saved between builds.
I have even deleted the Debug and Release directories and compiled from scratch. Still the 40 second delay.
If I do a Rebuild Solution, another 40 second delay.
But if I do a Clean Solution, it runs instantly!
Does anybody have a clue as to what is causing the delay?
Thanks!
EDIT:
Further information. I have 8 cores, 12 GB RAM, and a 256 GB SSD, so this little machine has the raw horsepower.
When devenv.exe is in the 40 second delay period, it is drawing a total of 13% of the CPU. When the compilation starts, it drops to less than 1%. The memory usage changes very little. It starts at 458.2MB, rises to 459.9MB during the 40 second delay, and then jumps to 463.1MB immediately after the compilation (if any) finishes.

A: Well, I found the problem. An Addin was taking exponential time to process the .rc and .rc2 files. The Addin was put in many months ago and did not start showing this problem until the size of .rc file grew enough to cause the (poorly-designed) regex to run very slowly.
Worse, I wrote the Addin! And have been using it on several machines for about a year with no problems. Previous versions of the Addin were written in C++ using PCRE regular expressions and never had a problem (even after 5 years of use). But this was a rewrite using C# and .NET Regex, which apparently behaves differently.
I fixed the problem by rewriting the code to avoid the need for some of the backtracking. Simple enough to do, but irritating that it was necessary for C# Regex.
The key to discovering the problem was to start devenv.exe with the /resetaddin option. With this, a build starts immediately. Then it was just a matter of figuring out which addin. I just hadn't done this as I hadn't changed addins for months.
This problem showed up when the .rc file was as small as 12K. I have tested the new version on a 262K .rc file and it runs in 123 ms.
Sigh.


text: Q: iphone unlocked in bestbuy? I am in vancouver B.C. Is the iphone4 bought in bestbuy official unlocked?I saw that the network of iphone4 is telus but have a uncontract price on bb website. So can the iphone4 be used in other countries? thank you!


text:
Q: Python datetime module current time in HR:MIN:SEC It seems like i should be able to find some sort of documentation on this, but everything im finding isnt working. In Python (v. 3.3) how do you get the current time in HR:MIN:SEC format using the datetime module?

A: This should do it:
import datetime

now = datetime.datetime.now()
now.strftime('%H:%M:%S')

Other units of time can be found by using the directives found here.


text:
Q: How do you check to see if a specific tweet is retweeted using JavaScript or JQuery when displaying a twitter feed?
Possible Duplicate:
Telling Whether A Tweet Is A Retweet Or Not?

So I've been working on a twitter feed script that pulls in my feed. I'm wondering how would I go about checking to see if a specific tweet is retweeted, and then if it is retweeted I want to use the information from the retweeted tweet instead. Here's an example associative array of what the twitter API produces for a retweet.
Array
(
    [0] => Array
        (
            [created_at] => Sun Jan 06 08:28:39 +0000 2013
            [id] => 287838076443705345
            [id_str] => 287838076443705345
            [text] => RT @Fullscreen: Heads-up: many YT partners are reporting issues claiming their videos. It appears to be a YT bug. We will keep you posted.
            [source] => web
            ...
            [user] => Array
                (
                    [id] => 212642904
                    [id_str] => 212642904
                    [name] => Elias Ranz-Schleifer
                    [screen_name] => Xxplosions
                    ...
                )
                ...
            [retweeted_status] => Array
                (
                    [created_at] => Sun Jan 06 02:08:43 +0000 2013
                    [id] => 287742460824805378
                    [id_str] => 287742460824805378
                    [text] => Heads-up: many YT partners are reporting issues claiming their videos. It appears to be a YT bug. We will keep you posted.
                    ...
                    [user] => Array
                        (
                            [id] => 238110322
                            [id_str] => 238110322
                            [name] => Fullscreen, Inc.
                            [screen_name] => Fullscreen
                            ...
                        )
                        ...
                )

            [retweet_count] => 44
            ...
        )

)

So essentially I want to replace [text] => RT @Fullscreen: Heads-up: many... with [text] => Heads-up: many... only if it exists. If it doesn't exist then use the normal method of pulling the information from the tweets. I guess basically what I'm trying to get at is how do I check to see if [retweeted_status] exists then pull that information if not then pull the other information. I would like to avoid having the RT in there since it does appear to be possible and to use the information like id_str, text, screen_name, etc.
The code I use to get the information for the regular tweet pulling is:
id = tweets[i]["id_str"];
twitPic = tweets[0]["user"]["profile_image_url_https"];
content = tweets[i]["text"];
tweetTime = tweets[i]["created_at"];

where i is replaced by the index in a for loop. If you have any questions about what I'm trying to get at then let me know and I'll be happy to clear it up.

A: You can test if the key exists like this:
// by using the 'in' operator
content = ('retweeted_status' in tweets[i]) ?  tweets[i]["retweeted_status"] : tweets[i]["text"];
// or by using the method 'hasOwnProperty()'
if(tweets[i].hasOwnProperty('retweeted_status')) {
    content = tweets[i]["retweeted_status"];
} else {
    content = tweets[i]["text"];
}

You could also checking for undefined, but this is not an accurate way of testing whether a key exists (What if the key exists but the value is actually undefined?).

A: // save current tweet
var tweet = tweets[i];
var id = tweet.id_str;
var twitPic = tweet.user.profile_image_url_https;
var tweetTime = tweet.created_at;
var isRetweet = Object.prototype.toString.call(tweet.retweeted_status).slice(8, -1) === 'Object';
// try to use text from original tweet
var content = isRetweet ? tweet.retweeted_status.text : tweet.text;


text:
Q: IE11 select drop-down when there is one element I have a select drop-down which has a single element and the drop down allows to select one or more. Even though I selected a value, I see a message

You must choose an item from the list.

How do I get rid of this message anyways?


text:
Q: The graph api /me/apprequests return http error I use
FB.api('/me/apprequests/?access_token=' + access_token + '&date_format=' + escape('Y/m/d H:i:s eO'), function(response) {
    if(response.error)
    {

to get user's app requests.
but some times,some users cannot get the app requests list.
only get
    {"error":{"type":"http","message":"unknown error"}}
some users may get this error all the time.
I trace this error to my GA quality,Statistical results show some users get this error As many as tens of thousands of times.
the access_token is the current user's.
why some user get unknown error with type http?
I do not get this.
thank you.
thanks for your answer.
I think this error is not caused due to the permission.because I log the access_token when one error occurs.and use facebook debug tool check it.It shows
Issued:
1362702044 (about an hour ago)
Expires:
1367886044 (in about 2 months)
Valid:  True
Origin: Web
Scopes: email publish_actions user_games_activity

.So ,I do not known why those problem occur.

A: I have the same problem and it is resolved now.
The error message :  {"error":{"type":"http","message":"unknown error"}}
means FB API's response is broken because of some other action in the page.
In my scenario, I put a html tag :button in a form, and this button is to invoke FB.api. However, when a user clicks the button, the form will be submitted automatically and does not wait the response of FB.api.
The code is as below:
<form>
    <button onclick="test();">Test</button>
</form>

function test(){
 FB.api('/me', function(response) {
        alert(response.name);
    });
}

I add "return false;" in button's onclick method after it calls test() to avoid the form automatically submitting.
I suggest you to check the javascript in the page to confirm there is no action occurs during interactive function with FB.


text:
Q: How does Find method of Entity Framework work? I am learning Entity Framework and faced some moment with Find() method I can't understand.
Sample taken from book of Julia Lerman "Programming Entity Framework : Code First"
public class Destination
{
    public int DestinationId { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
    public string Description { get; set; }
    public byte?[]  Photo { get; set; }
    public ICollection<Lodging> Lodgings { get; set; }

    public Destination()
    {
        Lodgings = new List<Lodging>();
    }
}

public class Lodging
{
    public int LodgingId { get; set; }
    public string Name { get; set; }
    public string Owner { get; set; }
    public bool IsResort { get; set; }
    public Destination Destination { get; set; }
}

And I operate with the data in the following ways :
var destination = organizationDbContext.Destinations // case # 1
                .Include("Lodgings")
                .First(p=>p.DestinationId==1);

var destination = organizationDbContext.Destinations.Find(1); // case # 2

*

*Why I can't call Find() method in the first case after Include() call, but can use Where() and First()?

*If I use second case with Find(), here I can't call Include() method to Lodgings, so how should I load related lodgings?

My questions could be expressed in another way:

*

*What is the right way to do : find one object and load all related inner objects (one-to-many)?

*What is the right way to do : load all objects (set A) and inner related objects (set A.I) , then find one by id from (A)?

A: The problem is that we use different types and one of this types contains method Find while another one doesn't :
1.
var destination = organizationDbContext.Destinations // case # 1
                .Include("Lodgings") // type here is IQueryable<T> no method Find defined
                .First(p=>p.DestinationId==1);

2.
                                     // type here is DbSet<T> with defined method Find
var destination = organizationDbContext.Destinations.Find(1);

A: The point is that Find starts by searching in the local cache of the context. If no match are found then it sends a query to the db.

The Find method on DbSet uses the primary key value to attempt to find
  an entity tracked by the context. If the entity is not found in the
  context then a query will be sent to the database to find the entity
  there. Null is returned if the entity is not found in the context or
  in the database.

I think it's the inner explanation that there is no Find on IQueryable.
When you are using the following code EF send always a request to the db:
var destination = organizationDbContext.Destinations // case # 1
                .Include("Lodgings")
                .First(p=>p.DestinationId==1);

More infos : https://msdn.microsoft.com/en-us/data/jj573936.aspx


text:
Q: find two strings in output with && in bash I want to look for two strings if they exists in my output and then pipe to pass them as arguments in next command.
ex:
for X = 1 to 100
    cat logX.txt | grep -e string1 -e string2 | rm logX.txt

but i don't know how to achieve above.
i have to check this for 100 files and delete which ever has those two strings in it. if anyone strings exist then i don't want to delete file.

A: If you want to delete only files with both matches, awk -- being a full-fledged programming language which can be given an expression that checks for the flags independently -- is more appropriate than grep (which modifies its exit status based on whether any matches are found, not whether all expressions given are matched).
string1="first regex"
string2="second regex"
for ((x=1; x<=100; x++)); do
  file="log$x.txt"
  awk -v string1="$string1" -v string2="$string2" '
    BEGIN { found1=0; found2=0; }
    $0 ~ string1 { found1=1; }
    $0 ~ string2 { found2=1; }
    END { exit(!(found1 && found2)) }
  ' "$file" && rm -f -- "$file"
done

The grep equivalent would be much less efficient, since it has to read each file twice:
# MUCH SLOWER ON BIG FILES: Reads each file twice (up to the point where a match exists)
string1="first regex"
string2="second regex"
for ((x=1; x<=100; x++)); do
  file="log$x.txt"
  grep -q -e "$string1" -- "$file" && grep -q -e "$string2" -- "$file" && rm -f -- "$file"
done

A: You can do this with find:
find . -name 'log*.txt' -exec grep -E 'string1' {} \; -exec grep -E 'string2' {} \; -exec rm {} \;

This would find logN.txt, grep for string1, if match then grep for string2, and if a match remove the file.
As per the comment below, add -maxdepth 1 if you only want to find files the current directory.

A: Using GNU Parallel:
parallel 'grep string1 log{}.txt && grep string2 log{}.txt && rm log{}.txt' ::: {1..100}

If you want to look at all log*.txt files, then this is shorter:
parallel 'grep string1 {} && grep string2 {} && rm {}' ::: log*.txt


text:
Q: Call a url from javascript Is there a way to call a url and get a response using javascript?
I need the equivalent of ASP.NET:
WebRequest req = HttpWebRequest.Create("http://someurl.com");
WebResponse webResponse = req.GetResponse();

I have an external url that holds some information I need and I want to call this url from javascript and parse the response in order to determine what to do in my application.

A: var req ;

// Browser compatibility check
if (window.XMLHttpRequest) {
   req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {

 try {
   req = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {

   try {
     req = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e) {}
 }

}

var req = new XMLHttpRequest();
req.open("GET", "test.html",true);
req.onreadystatechange = function () {
    //document.getElementById('divTxt').innerHTML = "Contents : " + req.responseText;
}

req.send(null);

A: You can make an AJAX request if the url is in the same domain, e.g., same host different application.  If so, I'd probably use a framework like jQuery, most likely the get method.
$.get('http://someurl.com',function(data,status) {
      ...parse the data...
},'html');

If you run into cross domain issues, then your best bet is to create a server-side action that proxies the request for you.  Do your request to your server using AJAX, have the server request and return the response from the external host.
Thanks to@nickf, for pointing out the obvious problem with my original solution if the url is in a different domain.

A: Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.
In jQuery:
$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })

In plain vanilla javaScript (from w3c):
var xmlhttp;
function loadXMLDoc(url)
{
    xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for all new browsers
      xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE5 and IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
      xmlhttp.onreadystatechange=state_Change;
      xmlhttp.open("GET",url,true);
      xmlhttp.send(null);
  }
else
  {
      alert("Your browser does not support XMLHTTP.");
  }
}

function state_Change()
{
    if (xmlhttp.readyState==4)
      {// 4 = "loaded"
          if (xmlhttp.status==200)
            {// 200 = OK
             //xmlhttp.data and shtuff
            // ...our code here...
        }
  else
        {
            alert("Problem retrieving data");
        }
  }
}

A: If you need to be checking external pages, you won't be able to get away with a pure javascript solution, since any requests to external URLs are blocked. You can get away with it by using JSONP, but that won't work unless the page you're requesting only serves up JSON.
You need to have a proxy on your own server to get the external links for you. This is actually rather simple with any server-side language.
<?php
$contents = file_get_contents($_GET['url']); // please do some sanitation here...
                                             // i'm just showing an example.
echo $contents;
?>

If you needed to check server response codes (eg: 404, 301, etc), then using a library such as cURL in your server-side script could retrieve that information and then pass it onto your javascript app.
Thinking about it now, there probably could be JSONP-enabled proxies out there for you to use, should the "setting up my own proxy" option not be viable.


text:
Q: How to find the regression of a given input in java? I have a two array inputs of data. Call them p and t. I need to find the regression function of these columns so I can accuratly predict future values. Is there any way to do this with in java? If so, what is the best way?

A: I know of:
apache commons math (see stat.regression).


text:
Q: Models & Views in Backbonejs Can someone help me get this backbone view render working? The console is telling me "Uncaught ReferenceError: app is not defined," the javascript that I am running is below:
(function() {
    var App = {
        Router: {},
        Model: {},
        View: {}
    };

    /**
    ** Set states adding and removing classes (show and hide view)
    ** @Helper Template
    **/
    function template( id ) {
        return $('#' + id).html();
    }

    /**
    ** Set states adding and removing classes (show and hide view)
    ** @Router Main
    **/
    App.Router.Main = Backbone.Router.extend({
        routes: {
            '':'vignetteNavView',
            'discover': 'discoverView',
            'artists': 'artistsView',
            'milestones': 'milestonesView',
            'archive': 'archiveView',
            'about': 'aboutView'
        },

        hidePages: function() {
            var contentAll = $('.page');
                contentAll.removeClass('active');
        },

        vignetteNavView: function(){
            var contentVignetteNav = document.getElementById('vignetteNavWrapper');
                this.hidePages();
                contentVignetteNav.classList.add('active');
        },

        discoverView: function() {
            var contentDiscover = document.getElementById('discoverWrapper');
                this.hidePages();
                contentDiscover.classList.add('active');
        },

        artistsView: function() {
            var contentArtists = document.getElementById('artistsWrapper');
                this.hidePages();
                contentArtists.classList.add('active');
        },

        milestonesView: function() {
            var contentMilestones = document.getElementById('milestonesWrapper');
                this.hidePages();
                contentMilestones.classList.add('active');
        },

        archiveView: function(){
            var contentArchive = document.getElementById('archiveWrapper');
            this.hidePages();
            contentArchive.classList.add('active');
        },

        aboutView: function(){
            var contentAbout = document.getElementById('aboutWrapper');
            this.hidePages();
            contentAbout.classList.add('active');

        }

    });

    var mainRouter = new App.Router.Main();
    Backbone.history.start();

    /**
    ** Define the Data Model for An Artist
    **/

    //Artist

    App.Model.Artist = Backbone.Model.extend({
        defaults: {
            "firstName":"Jim",
            "lastName":"Nutt",
            "bio":"Born in Pittsfield, Massachusetts in 1938, Jim Nutt spent his childhood moving around the United States with his family, including a brief stop in the Chicago suburbs during high school. In 1957, after finishing high school, Nutt spent a year and a half studying architecture at the University of Pennsylvania before transferring to the School of the Art Institute of Chicago in 1960 to study painting. Soon after his arrival at SAIC he met fellow student Gladys Nilsson, and the two married one year later, in 1961. Nutt received his BFA in 1965.",
            "work":"A, B, C, etc...",
            id:1
        }
    });

    App.View.ArtistView = Backbone.View.extend({
        render: function(){
            console.log(this.model.get('firstName'));
        }
    });

    app.view.artistsView = new App.View.ArtistsView({model:App.Model.Artist});

    app.view.artistsView.render();

})();

I know it's not necessarily ideal to attempt to learn javascript while learning Backbone/an mvc framework, but I am trying nonetheless..so please excuse me if this is a fairly obvious issue...and...Thanks!
Now I'm trying the code below and receiving the same error:
(function() {
    /**
    ** @Namespacing
    **/
    var App = {
        Router: {},
        Model: {},
        View: {}
    };

    /**
    ** Set states adding and removing classes (show and hide view)
    ** @Helper Template
    **/
    function template( id ) {
        return $('#' + id).html();
    }

    /**
    ** Set states adding and removing classes (show and hide view)
    ** @Router Main
    **/
    App.Router.Main = Backbone.Router.extend({
        routes: {
            '':'vignetteNavView',
            'discover': 'discoverView',
            'artists': 'artistsView',
            'milestones': 'milestonesView',
            'archive': 'archiveView',
            'about': 'aboutView'
        },

        hidePages: function() {
            var contentAll = $('.page');
                contentAll.removeClass('active');
        },

        vignetteNavView: function(){
            var contentVignetteNav = document.getElementById('vignetteNavWrapper');
                this.hidePages();
                contentVignetteNav.classList.add('active');
        },

        discoverView: function() {
            var contentDiscover = document.getElementById('discoverWrapper');
                this.hidePages();
                contentDiscover.classList.add('active');
        },

        artistsView: function() {
            var contentArtists = document.getElementById('artistsWrapper');
                this.hidePages();
                contentArtists.classList.add('active');
        },

        milestonesView: function() {
            var contentMilestones = document.getElementById('milestonesWrapper');
                this.hidePages();
                contentMilestones.classList.add('active');
        },

        archiveView: function(){
            var contentArchive = document.getElementById('archiveWrapper');
            this.hidePages();
            contentArchive.classList.add('active');
        },

        aboutView: function(){
            var contentAbout = document.getElementById('aboutWrapper');
            this.hidePages();
            contentAbout.classList.add('active');

        }

    });

    var mainRouter = new App.Router.Main();
    Backbone.history.start();

    /**
    ** Define the Data Model for An Artist
    **/

    //Artist

    App.Model.Artist = Backbone.Model.extend({
        defaults: {
            "firstName":"Jim",
            "lastName":"Nutt",
            "bio":"Born in Pittsfield, Massachusetts in 1938, Jim Nutt spent his childhood moving around the United States with his family, including a brief stop in the Chicago suburbs during high school. In 1957, after finishing high school, Nutt spent a year and a half studying architecture at the University of Pennsylvania before transferring to the School of the Art Institute of Chicago in 1960 to study painting. Soon after his arrival at SAIC he met fellow student Gladys Nilsson, and the two married one year later, in 1961. Nutt received his BFA in 1965.",
            "work":"A, B, C, etc...",
            id:1
        }
    });

    var artist = new App.Model.Artist({});

    App.View.ArtistView = Backbone.View.extend({
        render: function(){
            console.log(this.model.get('firstName'));
        }
    });

    artistsView = new App.View.ArtistsView({model:artist});

    artistsView.render();

})();

A: To have ability to save into the object you have to create it. Add this below the App definition.
var app = {
    router: {},
    model: {},
    view: {}
};


text:
Q: 2D Green's function and 3D divergence I need to find the following exrpression for the green's function in 2D:
$G(\rho)=\frac 1 {2 \pi} ln(c \rho)$ where c is some constant.
So I initially used the laplace equation in order to find an expression for it, for G:
$G= Aln\rho + B$, whee A,B are some constants, which we can evaluate if we have some initial boundary conditions.
Now I use the divergence theorem in 3D :
$\int_V \nabla(\nabla G)dV=\int_{(V)}\nabla G d\vec A $
Now the problem I have is that my Green's function, since it's a 2D function, is not dependent from the z component. That's why I thought of using a cylindrical volume and dividing the left integral in the one that contains x and y, both expressed in polar coordinates which is multiplied with an integral that has the z component, if we assume that the z goes from (-h) to (h). But I don't know what to do with the right integral, since my green function has no z component. Any help as to how I should proceed would really help me


text:
Q: why use ObjectAnimationUsingKeyFrames for ToggleButton.IsChecked instead of BooleanAnimationUsingKeyFrames? For animating UIElement.IsEnabled we can use BooleanAnimationUsingKeyFrames. Then why we can't use the same for ToggleButton.IsChecked? What is the need of ObjectAnimationUsingKeyFrames here? Could somebody clarify this.

        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(ToggleButton.IsChecked)" Storyboard.TargetName="checkBox">
            <DiscreteObjectKeyFrame KeyTime="0">
                <DiscreteObjectKeyFrame.Value>
                    <System:Boolean>True</System:Boolean>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>

A: After an analysis I found the answer. The type of IsChecked is nullable of bool (i.e. bool?) whereas the type of IsEnabled is just a bool. So, null value is applicable for IsChecked. That is why ObjectAnimationUsingKeyFrames is applicable instead of BooleanAnimationUsingKeyFrames.


text:
Q: Use EXPECT_CALL on local object of function? Is there a way to use EXPECT_CALL on a local object of a function?
For example:
template<class T>
std::string doSomethingWithTheCar()
{
    T car;
    return "the color of the car is: " + car.color();
}

class Car
{
public:
    std::string color()
    {
        return "green";
    }
};

class MockCar
{
public:
    MOCK_METHOD0(color, std::string());
};

TEST(MockLocalObject, doSomethingWithCarTest) {
    EXPECT_CALL(car, color())
        .WillOnce(Return("red"));

    std::string color = doSomethingWithTheCar<MockCar>();
    EXPECT_EQ(color, "red");
}

Due to the template I can control if the real Car object will be used or the MockCar. But is there a way to use EXPECT_CALL on this?

A: I would do it like this:
class AbstractCar {
public:
    virtual ~AbstractCar() = default;
    virtual std::string color() = 0;
};

class Car: public AbstractCar {
public:
    ~Car() override = default;
    std::string color() override {
        return "green";
    }
};

class MockCar: public AbstractCar {
public:
    MOCK_METHOD0(color, std::string());
};

std::string doSomethingWithTheCar(AbstractCar* car)  // or even better - use std::shared_ptr
{
    return "the color of the car is: " + car->color();
}

TEST(MockLocalObject, doSomethingWithCarTest) {
    auto car = new MockCar;
    EXPECT_CALL(*car, color()).WillOnce(Return("red"));

    std::string color = doSomethingWithTheCar(car);
    // this test will fail, because actual string is:
    // "the color of the car is: red"
    EXPECT_EQ(color, "red");
    delete car;
}


text:
Q: Moving Textview Using Buttons Android What i'm trying to do is when you click any of the arrow buttons shown in the image, the TextView user_text will move a small amount in the respective direction.  For some reason using the Java code below when I click on the buttons, the text moves all the way to the absolute edge of the screen.  I wasn't sure why this was happening so I decided to try and use  user_text.getX() and user_text.getY() to get their X and Y coordinates but that didn't do anything.  After a little research, I found that I should've been using user_text.getLeft() and user_text.getTop() and/or user_text.getWidth().  After trying those, the android monitor/debug section of the studio said that those numbers were 0.  I'm not sure why this happened but if someone could tell me what I should be doing instead or how to get it so that every time you click the button it moves, that would be greatly appreciated.
Thanks
P.S. I wrote on the image so you would know what is being ID-ed as user_text

My relevant XML Code:
<TextView
    android:id="@+id/user_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:textColor="@android:color/black"
    android:textSize="18sp"
    android:elevation="20dp"
    android:paddingBottom="120dp" />
  .    <--- that is supposed to represent that there's other non-relevant code in between
  .
  .

<RelativeLayout
    android:id="@+id/move_Group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="5dp"
    android:layout_centerInParent="true"
    android:visibility="visible"
    android:gravity="center">

    <Button
        android:id="@+id/move_left"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:background="@mipmap/arrow"
        android:rotation="-90"
        android:layout_marginRight="20dp"
        android:onClick="moveLeft"/>

    <Button
        android:id="@+id/move_up"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/move_left"
        android:background="@mipmap/arrow"
        android:layout_marginRight="20dp"
        android:onClick="moveUp"/>

    <Button
        android:id="@+id/move_down"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/move_up"
        android:background="@mipmap/arrow"
        android:rotation="180"
        android:layout_marginRight="20dp"
        android:onClick="moveDown"/>

    <Button
        android:id="@+id/move_right"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/move_down"
        android:background="@mipmap/arrow"
        android:rotation="90"
        android:layout_marginRight="20dp"
        android:onClick="moveRight"/>

    <TextView
        android:id="@+id/move"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MOVE"
        android:textSize="20sp"
        android:layout_toRightOf="@id/move_right"
        android:textColor="@android:color/black"/>

</RelativeLayout>

My relevant Java Code:
TextView user_text = (TextView) findViewById(R.id.user_text);
.
.
.
public void moveLeft(View view)
{
    user_text.setX(userX + 10);
}

public void moveUp(View view)
{
    user_text.setY(userY + 10);
}

public void moveDown(View view)
{
    user_text.setY(userY - 10);
}

public void moveRight(View view)
{
    user_text.setX(userX - 10);
}

A: Get current X and Y of user_text in click function.
public void moveLeft(View view)
{
      user_text.setX(user_text.getX() - 10);
}

when move up: Y = Y - delta.
public void moveUp(View view)
{
       user_text.setY(user_text.getY() - 10);
}

when move down: Y = Y + delta
public void moveDown(View view)
{
    user_text.setY(user_text.getY() + 10);
}

This is example in MainActivity.java. I see it works
public class MainActivity extends AppCompatActivity {

    TextView user_text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        user_text = (TextView) findViewById(R.id.user_text);

    }

    public void moveLeft(View view)
    {
        user_text.setX(user_text.getX() - 10);
    }

    public void moveUp(View view)
    {
        user_text.setY(user_text.getY() - 10);

    }

    public void moveDown(View view)
    {
        user_text.setY(user_text.getY() + 10);

    }

    public void moveRight(View view)
    {
        user_text.setX(user_text.getX() + 10);
    }
}


text:
Q: Why is this JSON returning an empty string? My JSON should positively bring back a value. And a single value only... But when trying to decode and dispay, it shows up emty, like this ''.
Here's the code on the page:
 $schoolid = $_GET['schoolid'];
 $json_skool = file_get_contents("http://www.examscan.us/api/webapi.php?
 Oper2=getschoolname&schoolid=" . $schoolid);
 $json_skool = json_decode($json_skool);
 $skool = $json_skool->SchoolName;

 echo "

" .  $skool . " - Student List
"

And this is how it appears:
-- Student List
My question here.. Does anyone notice something wrong in the syntax? Or the way I use it?

A: You need this code :
$skool = $json_skool->data[0]->SchoolName

Demo : https://eval.in/521902


text:
Q: Trying to make a custom table I'm trying to make a table that looks like this:

But I'm not quite sure how to go about doing that.
The end result is supposed to look like this:

I was planning on having making a div, and then setting the background of the div to be the grey textured part, and then creating a table inside that div to organize the content. Is using a table in this situation correct? Or is there a better method? Thanks in advance.

A: Stick to a non-table markup.  Best practices today would suggest you should only use tables for tabular data, and this content is not tabular data.
There's several different methods you could use to get this going, including using floats, displaying inline-block, and others.  There's also considerations with the content wrapping around the images (if the content is long, for example).
But here's some sample code to get your rolling.
Styles:
div.left,
div.right {
    width: 400px;
    overflow: hidden; /* forces the div to clear the floated content */
}

div.left img,
div.right img {
    border: 2px solid #888;
}

div.left img {
    float: left;
    padding-right: 20px;
}

div.right img {
    float: right;
    padding-left: 20px;
}

The html markup:

Lorem Ipsump dolor sit amet

Lorem Ipsum dolor sit amet

A: Here is a DEMO
This should show you exactly what you need.

body {
    height:400px;
}
#topLeft {
    background-color:#000000;
    width:32%;
    height:32%;
    margin:5px;
    float:left;
}
#topRight {
    float:right;
    background-color: #000000;
    width:65%;
    height:32%;
    margin:5px;
}
#middleLeft {
    background-color:#000000;
    width:65%;
    height:32%;
    margin:5px;
    float:left;
}
#middleRight {
    float:right;
    background-color: #000000;
    width:32%;
    height:32%;
    margin:5px;
}
#bottomLeft {
    float:left;
    background-color: #000000;
    width:32%;
    height:32%;
    margin:5px;
}
#bottomRight {
    float:right;
    background-color: #000000;
    width:65%;
    height:32%;
    margin:5px;
}

The body can be replaced with a wrapper and sized appropriately.
Code on jsFiddle

A: Fooey on those haters who say don't use tables. I would totally use a table for this.

    Lorem Ipsum...

    Lorem Ipsum...

    Lorem Ipsum...


text:
Q: Evento ApplicationEventPublisher que hace? El evento:
@Autowired
private ApplicationEventPublisher publisher;

envía:
eventPublisher.publish(new CreateParticipantEvent(conversation, participant));

¿Envía notificaciones a todos? ¿Cómo funciona?

A: Te permite publicar eventos que pueden ser recibidos por listeners configurados para ello.
Puedes utilizar los eventos publicados por el framework o personalizados, para lanzar tus propios eventos necesitas 4 partes:
Configuración
Declarar el publisher en el web.xml para que pueda publicar eventos en el contexto de la aplicación.
<listener>
    <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>

Evento
Clase que debe heredar de ApplicationEvent, en tu caso CreateParticipantEvent. Por ejemplo:
public class CreateParticipantEvent extends ApplicationEvent {

  private Object conversation;
  private Object participant;

  public CreateParticipantEventextends (Object conversation, Object participant) {

    super();
    this.conversation = conversation;
    this.participant= participant;
  }

  //GETTERS, TOSTRING...

}

También puedes utilizar eventos ya existentes, como por ejemplo, HttpSessionDestroyedEvent.
Publisher
El encargado de "lanzar" esos eventos, en este caso el origen de tu pregunta. Por ejemplo:
public class CreateParticipantEventPublisher {

  @Autowired
  private ApplicationEventPublisher publisher;

  public Notify(Object conversation, Object participant) {

    eventPublisher.publish(new CreateParticipantEvent(conversation, participant));

  }

}

Listener
El encargado de estar escuchando determinados eventos. Por ejemplo,
public class CreateParticipantEventListener implements ApplicationListener<CreateParticipantEvent > {

  @Override
  public void onApplicationEvent(CreateParticipantEvent event) {

    System.out.println("Fired event: " + event);

  }

}

Para utilizar los existentes, simplemente tienes que crear un listener para ellos.
Como información adicional, te dejo aquí un recurso (en Inglés) con una guía de buenas prácticas para la publicación de eventos.


text:
Q: How best to parse a comma separate list in PEG grammar I'm trying to parse a comma separated list. To simplify, I'm just using digits. These expressions would be valid:
(1, 4, 3)
()
(4)
I can think of two ways to do this and I'm wondering why exactly the failed example does not work. I believe it is a correct BNF, but I can't get it to work as PEG. Can anyone explain why exactly? I'm trying to get a better understanding of the PEG parsing logic.
I'm testing using the online browser parser generator here:
https://pegjs.org/online
This does not work:
list = '(' some_digits? ')'
some_digits = digit / ', ' some_digits
digit = [0-9]

(actually, it parses okay, and likes () or (1) but doesn't recognize (1, 2)
But this does work:
list = '(' some_digits? ')'
some_digits = digit another_digit*
another_digit = ', ' digit
digit = [0-9]

Why is that? (Grammar novice here)

A: Cool question and after digging around in their docs for a second I found that the / character means:

Try to match the first expression, if it does not succeed, try the
  second one, etc. Return the match result of the first successfully
  matched expression. If no expression matches, consider the match
  failed.

So this lead me to the solution:
list = '(' some_digits? ')'
some_digits = digit ', ' some_digits / digit
digit = [0-9]

The reason this works:
input: (1, 4)

*

*eats '('

*check are there some digits?

*check some_digits - first condition:

*

*eats '1'

*eats ', '

*check some_digits - first condition:

*

*eats '4'

*fails to eat ', '

*check some_digits - second condition:

*

*eats '4'

*succeeds

*succeeds

*eats ')'

*succeeds

if you reverse the order of the some_digits conditions the first number is comes across gets eaten by digit and no recursion occurs. Then it throws an error because ')' is not present.

A: In one line:
some_digits = '(' digit (', ' digit)* ')'
It depends on what you want with the values and on the PEG implementation, but extracting them might be easier this way.


text:
Q: String is not string Thinking of string as String works. However thinking of String as string is broken:
var str1:String = "asdf";
var str2:String = new String("asdf");
var str3:string = "asdf";
var str4:string = new String("asdf"); // Error

Try It
Also:
var interfaceBased:String = "123";
var keywordBased:string ="123";
interfaceBased=keywordBased;
keywordBased=interfaceBased; // Error

Try It
Is this a known compiler bug?

A: String is a Javascript type while string is a Typescript type. I don't think it's a bug so much as a quirk. Mainly because there's absolutely no reason to use the String() constructor over string literals.
See here: Typescript: difference between String and string

A: This stems from a JavaScript quirk: there are primitive strings and object strings. A primitive string is, well, your everyday string:
typeof "Hi! I'm a string!"  // => "string"

However, any time you use new, you create an object rather than a primitive:
typeof new String("Hi! I'm a string!")  // => "object"

JavaScript also implicitly creates an object string out of a primitive string whenever you access a property, since only objects can have properties:
var s = "Hi! I'm a string!";
s.property = 6;  // s implicitly coerced to object string, property added
console.log(s.property);  // => undefined
// property was added to the object string, but then the object string was
// discarded as s still contained the primitive string. then s was coerced again
// and the property was missing as it was only added to an object whose reference
// was immediately dropped.

You almost never want an object string because of its quirks (e.g., an empty object string is truthy), so rather than using new String, you almost always want String instead. String without new can even convert an object string back into a primitive string:
typeof String(new String("Hi! I'm a string!"))  // => "string"

I don't know if this issue surfaces in TypeScript, but the primitive/object distinction and especially the truthiness issue becomes very odd with Boolean. For example:
var condition = new Boolean(false);
if(condition) {  // always true; objects are always truthy
    alert("The world is ending!");
}

In short, it's because of the object/primitive distinction. You almost always want primitives where you have the option.


text:
Q: How does predictive model for the Eurovision Song Contest work? I've encountered interesting prediction of  Eurovision Song Contest http://mewo2.com/nerdery/2013/05/12/eurovision-2013-first-predictions/ it based on some kind of Bayesian model I assume but I don't understand how it works (the description is too sketchy for me).
Along the lines it says that it uses Markov Chain Monte Carlo sampler but what exactly does it sample?


text:
Q: Change UISearchBar cancel button text in iOS 8 I'd like to change the text from "Cancel" to "Done" of the Cancel button inside the UISearchBar in iOS 8. I am using UISearchController. I've tried different approaches for iOS 6 and iOS 7 and they do not work. Has anybody done this?

A:  for view in (UISearchBar.subviews[0]).subviews{
             if let button = view as? UIButton{
             button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
             button.setTitle("Cancel", forState:.Normal)
            }
     }

self.subviews[0]).subviews contain UISearchBarBackground,UISearchBarTextField,UINavigationButton in which UINavigationButton is subclass of UIButton.Check for View as UIButton and if yes then change property of UIButton.

A: Objective-C:
[searchBar setValue:@"customString" forKey:@"_cancelButtonText"];

Swift:
searchBar.setValue("customString", forKey:"_cancelButtonText")

A: I was having trouble getting this to work for a UISearchBar within a UISearchController. The text didn't change the first time the cancel button was shown but it did the second time.
That is until I saw @polo987's answer. Here's what I did that worked:
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "Done"

A: For iOS 13 Support:
Swift:
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "Whatever"

Objective C:
    [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:[NSArray arrayWithObject:[UISearchBar class]]] setTitle:@"Whatever"]

A: In Swift:
searchBar.setValue("customString", forKey: "_cancelButtonText")

Based on Burhanuddin Sunelwala answer.

A: In Swift4
Change Title:
(searchBar.value(forKey: "cancelButton") as! UIButton).setTitle("Done", for: .normal)
Change Color:
(searchBar.value(forKey: "cancelButton") as! UIButton).setTitleColor(UIColor.blue, for: .normal)

A: This worked for me in ios8 through ios13, did not try in ios7, but should do the trick, beware of placing this line in the early times of the app cycle (eg : appDelegate)
[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:@"Annuler"];

and as of ios9 you could also use
[[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTitle:@"Annuler"];

Swift version:
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "Annuler"

Hope that helps ;)

A: I have added titleLabel.font to the mix...
This goes straight into my ViewDidLoad() {
        let searchFont = UIFont(name: "BrandonGrotesque-Medium", size: 12)
        let textFieldSearchBar = self.searchBar.valueForKey("searchField") as! UITextField
        textFieldSearchBar.font = searchFont
        let cancelButton = searchBar.valueForKey("cancelButton") as! UIButton
        cancelButton.setTitle("Done", forState: .Normal)
        cancelButton.titleLabel!.font = searchFont

A: Swift 4.2, 4.0+
A custom class to customize the most common elements in search bar.
class SearchBar: UISearchBar {

    private enum SubviewKey: String {
        case searchField, clearButton, cancelButton,  placeholderLabel
    }

    // Button/Icon images
    public var clearButtonImage: UIImage?
    public var resultsButtonImage: UIImage?
    public var searchImage: UIImage?

    // Button/Icon colors
    public var searchIconColor: UIColor?
    public var clearButtonColor: UIColor?
    public var cancelButtonColor: UIColor?
    public var capabilityButtonColor: UIColor?

    // Text
    public var textColor: UIColor?
    public var placeholderColor: UIColor?
    public var cancelTitle: String?

    // Cancel button to change the appearance.
    public var cancelButton: UIButton? {
        guard showsCancelButton else { return nil }
        return self.value(forKey: SubviewKey.cancelButton.rawValue) as? UIButton
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        if let cancelColor = cancelButtonColor {
            self.cancelButton?.setTitleColor(cancelColor, for: .normal)
        }
        if let cancelTitle = cancelTitle {
            self.cancelButton?.setTitle(cancelTitle, for: .normal)
        }

        guard let textField = self.value(forKey: SubviewKey.searchField.rawValue) as? UITextField else { return }

        if let clearButton = textField.value(forKey: SubviewKey.clearButton.rawValue) as? UIButton {
            update(button: clearButton, image: clearButtonImage, color: clearButtonColor)
        }
        if let resultsButton = textField.rightView as? UIButton {
            update(button: resultsButton, image: resultsButtonImage, color: capabilityButtonColor)
        }
        if let searchView = textField.leftView as? UIImageView {
            searchView.image = (searchImage ?? searchView.image)?.withRenderingMode(.alwaysTemplate)
            if let color = searchIconColor {
                searchView.tintColor = color
            }
        }
        if let placeholderLabel =  textField.value(forKey: SubviewKey.placeholderLabel.rawValue) as? UILabel,
            let color = placeholderColor {
            placeholderLabel.textColor = color
        }
        if let textColor = textColor  {
            textField.textColor = textColor
        }
    }

    private func update(button: UIButton, image: UIImage?, color: UIColor?) {
        let image = (image ?? button.currentImage)?.withRenderingMode(.alwaysTemplate)
        button.setImage(image, for: .normal)
        button.setImage(image, for: .highlighted)
        if let color = color {
            button.tintColor = color
        }
    }
}

Usage:
class ViewController: UIViewController {

    @IBOutlet private weak var searchBar: SearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        searchBar.clearButtonColor      = .purple
        searchBar.cancelButtonColor     = .magenta
        searchBar.searchIconColor       = .red
        searchBar.placeholderColor      = .green
        searchBar.textColor             = .orange
        searchBar.capabilityButtonColor = .green
    }
}

Result:

A: Found it!. in iOS 8, the cancel button is under the key "cancelButton". I used UISearchBar delegate searchBarTextDidBeginEditing to make the change.
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    let uiButton = searchBar.valueForKey("cancelButton") as UIButton
    uiButton.setTitle("Done", forState: UIControlState.Normal)

}

A: I know this may seem to be a bit irrelevant but in my opinion this is safer than using private apis and more efficient than taking a dive into the unknown views. This solution makes sense only if you have your own localisation engine and you do want Apple to follow your mechanism all over the app.
Basically my idea is to switch the language the iOS SDK uses to localise the button by altering the "AppleLanguages" key in the NSUserDefaults. You can go here for more information about how this works.
[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:@"en", @"fr", nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize];

Put this code to use the English localisation and a French fallback no matter what language is set on the phone. This only takes effect within the app.

A: Swift 3.0:
In your AppDelegate add this:
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "my text"

A: Here is Swift solution:
for (view) in _searchController.searchBar.subviews {
    for (subview) in view.subviews {
        if (subview.isKindOfClass(UIButton.self)) {
            let cancelButton = subview as! UIButton
            cancelButton.setTitle("BlaBla", forState: .Normal)
            break
        }
    }
}

A: let uiButton = searchBar.value(forKey: "cancelButton") as! UIButton
uiButton.setTitle(NSLocalizedString("Cancel", comment: ""), for: .normal)


text:
Q: Connecting to MySQL server with Unity3d? I am trying to create an Android game that needs to send information to be stored in a remote database. The MySQL database is stored on my university's server, which I usually access through SSH. What I'm trying to do right now is to use ODBC to connect to the database, but I am having trouble getting it to interact with Unity3d (C#). If anybody has experience with this, I would appreciate any help or direction to get my past this hurdle!

A: Unity Wiki have defined a complete procedure (Server side high score) with PHP, MySql and C#/JavaScript. Hope this will solve your problem.

A: The recommended solution is not directly connecting your app with the DB, but to implement that via some layer of API or backend service.
One of the simplest approaches is to use Parse.com, which is free if your traffic is not very large.
Example code:
ParseObject gameScore = new ParseObject("GameScore");
gameScore["score"] = 1337;
gameScore["playerName"] = "Sean Plott";
Task saveTask = gameScore.SaveAsync();

Another similiar cloud storage or service might be Firebase, which offers JSON based API for you to read/write your own data. Example usage:
public class Item
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

var data = new Item(...); // or List<Item>() whatever
var str_data= JsonConvert.SerializeObject<Item>(data);
Firebase fb = new Firebase(new Uri("https://abcdefg.firebaseio.com/"));

//Write
string path = "/path";    // where to keep data in firebase
string id = fb.Post(path, data);

//Read back
string jsonData = fb.Get(path);
var data2 = JsonConvert.DeserializeObject<Item>(jsonData);


text:
Q: Asp.Net C# Mutliptle submit button not working with multiple asp.net panel default button I need some help about Asp.Net C# Mutliptle submit button not working with multiple asp.net panel default button.
I have used two asp.net panel with default button and textbox required field validator.
when I click the first panel button automatically both panel textbox required filed validator required.
when I click the second button automatically both panel textbox required field validator required.
remember that all working code inside master page.


text:
Q: Printing arabic value to console passed from URL I am using below code to print the arabic value to console but it is giving junk values i have tried using so many ways but nothing worked, can anyone please help me out. Below is my code.    URL is as below     smsapi.jsp?SENDER=Interner&MOBILE=&TEMPLATEID=0&MSG=مرحبا شباب&DC=8
<jsp:scriptlet>
   ServletContext context = getServletContext();
   String MESSAGE = null;
   MESSAGE =new String(request.getParameter("MSG").getBytes(),"Cp1256");            out.println("Message**"+MESSAGE);
</jsp:scriptlet>   </form> </html>

Thanks in Advance.


text:
Q: Bootstrap4 col-xs does nothing I've noticed that in BS4  alpha, col-xs-x does not do a darn thing. Even on their official site
https://v4-alpha.getbootstrap.com/layout/grid/
If you were to go in and change a class from col to col-xs-5 for example, no class is applied. Change it to col-sm-5, works as intended. Whats the deal?


text:
Q: Changes to PostgreSQL source code I was working around with Postgres a bit. I am trying to get familiar to editing the source code of the same.
One of the suggested exercise was to change the buffer replacement policy of the system of Postgres 7.4. (It was in one of the homeworks of some university. First few links of google. I am just using them to get familiar to the code.)
I understand parts of it but I am not able to fully understand how to modify the system. I mean, I know the particular files,buffer folder files in the src/backend/storage location as the files where I have to make changes, but how to implement my own scheme and test it, is going over my head.
So my question is, can anyone help me with some basic code snippet understanding? (Probably, give me idea how to solve the question mentioned above? and how to test it ( most important). ) (This is not a homework of any sort, promise. I am just trying to get a hang of things.)
If not, can anyone refer me to some book which can help me with modification of the postgresql source code? There are books to use postgresql, but I couldn't find any that could help to modify the source code.
P.S: I know the online documentation of PGSQL source code resides at: http://doxygen.postgresql.org/
But I am not able to understand a lot from there. I need a book that can help the layman!
Any help is much appreciated!

A: Apart from the Developer FAQ your best starting point will be the PostgreSQL mailing lists.
You might start with posting to http://archives.postgresql.org/pgsql-novice/ ("No question is too simple for this list")
And if you really start changing the source code you will need to subscribe to http://archives.postgresql.org/pgsql-hackers/ as well.
And don't use the 7.x source code. PostgreSQL is at Version 9.1 now and I'm sure studying the ancient history won't be very helpful.


text:
Q: Load ajax data NOT in a div or other element first of all, sorry for my bad english, I speak spanish.
Well, I need some help in this case:
I made a microsoft excel POI report using java, this report is in a servlet that I call when do a clic in a href, por example:
Report

Until here, all ok, but I need to call this report using an event (it could be .load()) from jQuery, but this event only works assigning the data result to a div or other element. I not need assign the result to any element because my report is generated and open through in excel, if I assign it to a div, in this div appears rare simbols.
I need too add a loading imagen until my report is ready and opened.
I have a bad code, please I need some help.
$("#mylink").click(function(){
    $("#contenidoo").empty().html('');
    $("#result").load("ServletReport");
});

I not need to put the result in a div $("#result"), I dont need to put the result in any place, I want to do clic and wait until my report is generated but viewing the loading image.

A: use the jquery .ajax function instead of .load: http://api.jquery.com/jQuery.ajax/

A: Use jQuery ajax() or get()
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.get/

A: You can use the .get method to fire an HTTP GET request to the server, and use a callback function to do something once it has completed:
$("#mylink").click(function() {
    $("#contenidoo").empty().html('');
    $.get("ServletReport", function() {
        $("#contenidoo").empty(); //Remove the image you appended above
    });
});

A: I found this very useful:
$("#mylink").click(function() {
  $("#contenidoo").empty().html('');
    $.get("ServletReport", function() {
     $("#contenidoo").empty(); //Remove the image you appended above
  });
});

But I dont want to put the result in any place, and using the method above the reslult of my servlet (my excel doc) is not opened. I think its lacking some little thing.
I hope your help.


text:
Q: Casting string type with GetDlgItemText() for use as string buffer in C++ I am stumped by the behaviour of the following in my Win32 (ANSI) function:
(Multi-Byte Character Set NOT UNICODE)
void sOut( HWND hwnd, string sText ) // Add new text to EDIT Control
{
 int len;
 string sBuf, sDisplay;

  len = GetWindowTextLength( GetDlgItem(hwnd, IDC_EDIT_RESULTS) );
  if(len > 0)
  {
   // HERE:
   sBuf.resize(len+1, 0); // Create a string big enough for the data
   GetDlgItemText( hwnd, IDC_EDIT_RESULTS, (LPSTR)sBuf.data(), len+1 );
  } // MessageBox(hwnd, (LPSTR)sBuf.c_str(), "Debug", MB_OK);

  sDisplay = sBuf + sText;
  sDisplay = sDisplay + "\n\0"; // terminate the string
  SetDlgItemText( hwnd, IDC_EDIT_RESULTS, (LPSTR)sDisplay.c_str() );
}

This should append text to the control with each call.
Instead, all string concatenation fails after the call to GetDlgItemText(), I am assuming because of the typecast?
I have used three string variables to make it really obvious. If sBuf is affected then sDisplay should not be affected.
(Also, why is len 1 char less than the length in the buffer?)
GetDlgItemText() corretly returns the content of the EDIT control, and SetDlgItemText() will correctly set any text in sDisplay, but the concatenation in between is just not happening.
Is this a "hidden feature" of the string class?
Added:
Yes it looks like the problem is a terminating NUL in the middle. Now I understand why the len +1. The function ensures the last char is a NUL.
Using sBuf.resize(len); will chop it off and all is good.
Added:
Charles,
Leaving aside the quirky return length of this particular function, and talking about using a string as a buffer:

The standard describes the return value of basic_string::data() to be a pointer to an array whose members equal the elements of the string itself.

That's precisely what's needed isn't it?

Further, it requires that the program must not alter any of the values of that array.

As I understand it that is going to change along with the guarantee that all bytes are contiguous. I forget where I read a long article on this, but MS already implements this it asserted.
What I don't like about using a vector is that the bytes are copied twice before I can return them: once into the vector and again into the string. I also need to instantiate a vector object and a string object. That is a lot of overhead. If there were some string friendly of working with vectors (or CStrings) without resorting to old C functions or sopying characters one by one, I would use them. The string is very syntax friendly in that way.

A: The data() function on a std::string returns a const char*. You are not allowed to right into the buffer returned by it, it may be a duplicated buffer.
What you could do instead is to used a std::vector<char> as a temporary buffer.
E.g. (untested)

std::vector<char> sBuf( len + 1 );
GetDlgItemText( /* ... */, &sBuf[0], len + 1 );

std::string newText( &sBuf[0] );
newText += sText;

Also, the string you pass to SetDlgItemText should be \0 terminated so you should used c_str() not data() for this.
SetDlgItemText( /* ... */, newText.c_str() );

Edit:
OK, I've just checked the contract for GetWindowTextLength and GetDlgItemText. Check my edits above. Both will include the space for a null terminator so you need to chop it off the end of your string otherwise concatenation of the two strings will include a null terminator in the middle of the string and the SetDlgItemText call will only use the first part of the string.
There is a further complication in that GetWindowTextLength isn't guaranteed to be accurate, it only guarantees to return a number big enough for a program to create a buffer for storing the result. It is extremely unlikely that this will actually affect a dialog box item owned by the calling code but in other situations the actual text may be shorter than the returned length. For this reason you should search for the first \0 in the returned text in any case.
I've opted to just use the std::string constructor that takes a const char* so that it finds the first \0 correctly.
The standard describes the return value of basic_string::data() to be a pointer to an array whose members equal the elements of the string itself. Further, it requires that the program must not alter any of the values of that array. This means that the return value of data() may or may not be a copy of the string's internal representation and even if it isn't a copy you still aren't allowed to write to it.

A: I am far away from the win32 api and their string nightmare, but there is something in the code that you can check. Standard C++ strings do not need to be null terminated and nulls can happen anywhere within the string. I won't comment on the fact that you are casting away constantness with your C-style cast, which is a problem on its own, but rather on the strange effect you are
When you initially create the string you allocate extra space for the null (and initialize all elements to '\0') and then you copy the elements. At that point your string is len+1 in size and the last element is a null. After that you append some other string, and what you get is a string that will still have a null character at position len. When you retrieve the data with either data() (does not guarantee null termination!) or c_str() the returned buffer will still have the null character at len position. If that is passed to a function that stops on null (takes a C style string), then even if the string is complete, the function will just process the first len characters and forget about the rest.
#include <string>
#include <cstdio>
#include <iostream>
int main()
{
   const char hi[] = "Hello, ";
   const char all[] = "world!";
   std::string result;
   result.resize( sizeof(hi), 0 );
   // simulate GetDlgItemText call
   std::copy( hi, hi+sizeof(hi), const_cast<char*>(result.data()) ); // this is what your C-style cast is probably doing
   // append
   result.append( all );

   std::cout << "size: " << result.size() // 14
      << ", contents" << result // "Hello, \0world!" - dump to a file and edit with a binary editor
      << std::endl;
   std::printf( "%s\n", result.c_str() ); // "Hello, "
}

As you can see, printf expects a C-style string and will stop when the first null character is found, so that it can seem as if the append operation never took place. On the other hand, c++ streams do work properly with std::string and will dump the whole content, checking that the strings were actually appended.
A patch to your append operation disappearing would be removing the '\0' from the initial string (reserve only len space in the string). But that is not really a good solution, you should never use const_cast (there are really few places where it can be required and this is not one of them), the fact that you don't see it is even worse: using C style casts is making your code look nicer than it is.
You have commented on another answer that you do not want to add std::vector (which would provide with a correct solution as &v[0] is a proper mutable pointer into the buffer), of course, not adding the extra space for the '\0'. Consider that this is part of an implementation file, and the fact that you use or not std::vector will not extend beyond this single compilation unit. Since you are already using some STL features, you are not adding any extra requirement to your system. So to me that would be the way to go. The solution provided by Charles Bailey should work provided that you remove the extra null character.

A: This is NOT an answer. I have added it here as an answer only so that I can use formatting in a long going discussion about const_cast.
This is an example where using const_cast can break a running application:
#include <iostream>
#include <map>
typedef std::map<int,int> map_type;
void dump( map_type const & m ); // implemented somewhere else for concision
int main() {
   map_type m;
   m[1] = 10;
   m[2] = 20;
   m[3] = 30;
   map_type::iterator it = m.find(2);
   const_cast<int&>(it->first) = 10;
   // At this point the order invariant of the container is broken:
   dump(); // (1,10),(10,20),(3,30) !!! unordered by key!!!!
   // This happens with g++-4.0.1 in MacOSX 10.5
   if ( m.find(3) == m.end() ) std::cout << "key 3 not found!!!" << std::endl;
}

That is the danger of using const_cast. You can get away in some situations, but in others it will bite back, and probably hard. Try to debug in thousands of lines where the element with key 3 was removed from the container. And good luck in your search, for it was never removed.


text:
Q: Dart program exits without executing last statement I'm trying to understand Streams and wrote some code.
Everything seems to work, the program exits with status code 0. But it doesn't print the 'loop done' and 'main done' strings. I can't figure out why.
import 'dart:async';

Stream<int> countStream(int to) async* {
      for (int i = 1; i <= to; i++) {
              yield i;
      }
}

class Retry {
    StreamController<int> _outgoing;

    Retry(Stream<int> incoming) {
        _outgoing = StreamController<int>();
        _outgoing.addStream(incoming);
    }

    Future<void> process() async {
        await for (final i in _outgoing.stream) {
            print("got $i");
        }
        print('loop done'); // Not printed
    }
}

void main() async {
  var stream = countStream(4);
  var retry = Retry(stream);
  await retry.process();
  print('main done'); // Not printed
}

A: The _outgoing.stream is never closed, so code after the await for will never execute. The VM does notice that there also won't be any new events on that stream so nothing else will ever happen, and it can exit. You could fix the bug with:
_outgoing.addStream(incoming).whenComplete(() {
    _outgoing.close();
});


text:
Q: Past real condition I'd like to know if the following sentence is correct (concerning the verb forms):
"If the Indians refused to convert to Christianism, they were killed."
As this is a real past condition, can I use preterit in both propositions?
Thanks.

A: When referring to a past outcome, it is common to use if with simple past in the if-clause, and to use simple past again in the main clause:

If they complained, they were fired.
If they complained, they got nothing.

It is a statement of a past fact.  if pretty much means when there. Those statements could be roughly paraphrased as follows:
Those who complained got fired.
Those who complained got nothing.
P.S. But "if they complained" could refer to a present-future possibility or condition:

If they complained, would City Council change the plan?


text:
Q: Strange NullReferenceException on ExecuteReader when I try to execute the folowing code, a NullReferenceException is raised on the ExecuteReader:
static public IDataReader executeReader(string query, string connectionString, string databaseType)
    {
        switch(databaseType)
        {
            case "SqlServer":
                //stuff for Sql Server
            case "DB2":
                iDB2Connection myConnectionDB2 = new iDB2Connection(connectionString);

                iDB2Command sqlCommandDB2 = new iDB2Command(query,  myConnectionDB2);
                sqlCommandDB2.CommandTimeout=0;
                try
                {
                    sqlCommandDB2.Connection.Open();
***The exception is raised here...***
                    return sqlCommandDB2.ExecuteReader(CommandBehavior.CloseConnection);
                }
                catch (Exception e)
                {
                    sqlCommandDB2.Dispose();
                    myConnectionDB2.Close();
                    throw new Exception("Error in DBHelper:ExeSQL()-> " + e.ToString());
                }
            default:
                //stuff for Oracle
        }
    }

Here is the message exception:

System.NullReferenceException: La référence d'objet n'est pas définie
  à une instance d'un objet. at
  Microsoft.Win32.Win32Native.CopyMemoryUni(StringBuilder pdst, IntPtr
  psrc, IntPtr sizetcb) at
  System.Runtime.InteropServices.Marshal.PtrToStringUni(IntPtr ptr) at
  IBM.Data.DB2.iSeries.MPHostCol.setHostColInfo(MpDcHostColumnInfo
  dcHostColInfo)
  blahblahblah until the line above.

Every parameter is filled, the query execute correctly with SQL-view, the connection string is correct and the database type is ok...
As every static method, nothing else have to be set... i'm sure it's somethin' stupid, but can't figure what.

A: Damn, the update from V5R3 to V5R4 has solved the bug. A simple 15 minutes update solved 3 days of head banging. Glad to have contributed :)


text:
Q: How to wait until buffered channel (semaphore) is empty? I have a slice of integers, which are manipulated concurrently:
ints := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

I'm using a buffered channel as semaphore in order to have an upper bound of concurrently running go routines:
sem := make(chan struct{}, 2)

for _, i := range ints {
  // acquire semaphore
  sem <- struct{}{}

  // start long running go routine
  go func(id int, sem chan struct{}) {
    // do something

    // release semaphore
    <- sem
  }(i, sem)
}

The code above works pretty well until the last or last two integers are reached, because the program ends before those last go routines are finished.
Question: how do I wait for the buffered channel to drain?

A: You can't use a semaphore (channel in this case) in that manner. There's no guarantee it won't be empty any point while you are processing values and dispatching more goroutines. That's not a concern in this case specifically since you're dispatching work synchronously, but because there's no race-free way to check a channel's length, there's no primitive to wait for a channel's length to reach 0.
Use a sync.WaitGroup to wait for all goroutines to complete
sem := make(chan struct{}, 2)

var wg sync.WaitGroup

for _, i := range ints {
    wg.Add(1)
    // acquire semaphore
    sem <- struct{}{}
    // start long running go routine
    go func(id int) {
        defer wg.Done()
        // do something
        // release semaphore
        <-sem
    }(i)
}

wg.Wait()

A: Use "worker pool" to process you data. It is cheeper than run goroutine for each int, allocate memory for variables inside it and so on...
ints := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

ch := make(chan int)

var wg sync.WaitGroup

// run worker pool
for i := 2; i > 0; i-- {
    wg.Add(1)

    go func() {
        defer wg.Done()

        for id := range ch {
            // do something
            fmt.Println(id)
        }
    }()
}

// send ints to workers
for _, i := range ints {
    ch <- i
}

close(ch)

wg.Wait()

A: Clearly there is no one waiting for your go-routines to complete. Thus the program ends before the last 2 go-routines are completed. You may use a workgroup to wait for all your go-routines complete before the program ends. This tells it better - https://nathanleclaire.com/blog/2014/02/15/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing/

A: You can wait your "sub-goroutines" with the current goroutine in a for loop
semLimit := 2
sem := make(chan struct{}, semLimit)

for _, i := range ints {
  // acquire semaphore
  sem <- struct{}{}

  // start long running go routine
  go func(id int, sem chan struct{}) {
    // do something

    // release semaphore
    <- sem
  }(i, sem)
}

// wait semaphore
for i := 0; i < semLimit; i++ {
  wg<-struct{}{}
}

Optionnaly it is also possible to program a minimalistic "semaphored waitgroup" with the economy of import sync
semLimit := 2
// mini semaphored waitgroup
wg := make(chan struct{}, semLimit)
// mini methods
wgAdd := func(){ wg<-struct{}{} }
wgDone := func(){ <-wg }
wgWait := func(){ for i := 0; i < semLimit; i++ { wgAdd() } }

for _, i := range ints {
  // acquire semaphore
  wgAdd()

  // start long running go routine
  go func(id int, sem chan struct{}) {
    // do something

    // release semaphore
    wgDone()
  }(i, sem)
}

// wait semaphore
wgWait()

A: Here is a working example. The for loop at the end forces the program to wait
until the jobs are done:
package main
import "time"

func w(n int, e chan error) {
   // do something
   println(n)
   time.Sleep(time.Second)
   // release semaphore
   <-e
}

func main() {
   a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
   e := make(chan error, 2)
   for _, n := range a {
      // acquire semaphore
      e <- nil
      // start long running go routine
      go w(n, e)
   }
   for n := cap(e); n > 0; n-- {
      e <- nil
   }
}


text:
Q: Disable Spring logging on Payara web server for certain packages I am deploying a Java 11 Spring Application (version 4.3.10) on Payara 5.2020.6. The problem is Spring logs all invocation to REST endpoints, causing the Payara logs to occupy a lot of disk space, which runs out very quickly.
The format of a message is something like this:
[2021-04-05T12:53:08.794+0300] [Payara 5.2020.6] [INFO] [] [] [tid: _ThreadID=90 _ThreadName=http-thread-pool::http-listener-1(2)] [timeMillis: 1617616388794] [levelValue: 800] [[
  3294283 [http-thread-pool::http-listener-1(2)] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher  - Checking match of request : '/rest/somepath/v1/someendpoint'; against '/rest/someotherpath/v1/someotherendpoint'
]]

I have tried to filter out this package from the Payara web console administration but the problem is the package name is included in the message itself (together with the log level) and Payara offers no option on filtering out based on this criterion (only the possibility to search upon a string contained within the message, in the LogViewer).
Does anyone know how can I configure Payara so that certain messages are being excluded from the Payara logs?


text:
Q: Using 2 different blade root template for Vue, with Laravel 8 and Inertia? So I am working on a Laravel 8 app, with Inertia and Vue.
The idea is that most of the pages are Laravel + Blade (good for SEO, fast loading etc...), but for selected pages that need a lot of user interactions, I insert a Vue component in the Blade Template where the interactions need to happen.
With Inertia, this is done by calling the Vue component with return Inertia::render('vueComponent') in the Controller that is called by the Laravel Route. Data can be passed to the Vue instance, and even to the Blade template, so this is good (see below).
namespace App\Http\Controllers;
use Inertia\Inertia;

class RangePageController extends Controller
{
    public function show(string $lang='fr')
    {
        // Strip the trailing slash from $lang
        $lang = Str::before($lang, '/');

        return Inertia::render('ProductsGallery', ['bar' => "Hello World"])->withViewData(['lang' => $lang]);
    }
}

And by default, the file "/resources/views/app.blade.php" is rendered with the Vue component replacing the @inertia directive (plus some Vue Data). Neat.
By default, the Blade layout file "app.blade.php" is used. The doc specifies that the default can be changed: Inertia\Inertia::setRootView('name');.
The Question: rather than changing the default, is there a way to choose different Blade layout files when calling different pages from the Controller (and inject the Vue component as above)? For instance I would like to use one Blade layout for my e-commerce basket, and a different one for my admin pages. Like choosing "app1.blade.php" for a page, and "app2.blade.php" for another.
Many thanks!
E.

A: Found a solution, for what it is worth.

*

*I create 2 new /Http/Middleware, extending the "HandleInertiaRequest.php"
middleware.

*In each extended class, I set the "protected $rootView" to point to the
custom Blade layout file in /resources/views. For instance
protected $rootView = 'admin.app';, to point to
/resources/views/admin/app.blade.php, and the same for the 'web'
app.blade.php.

*Then I create a second "admin" middleware group in
Kernel.php replicating the list in the "web" group, and I replace
the default "\App\Http\Middleware\HandleInertiaWebRequests::class"
lines with the extended classes (in the "web" and the "admin" groups).

*And I create an "admin" route file in the "routes" folder to host
the routes that will use the "admin" layout. The routes in the
default "web" route file will use the Blade layout that sits in "resources/views/web/".

Probably some better solutions, but this one seems to work.
Note: I have seen a discussion on GitHub to do the same, but in addition to have 2 different Vue instances: one for "web", and one for "admin". Not sure what this brings, but I am still looking for a way to do it! If anybody has an idea...

A: Just a little bit update your HandleInertiaRequests
public function version(Request $request)
    {
        // Add the root view tho the version hash.
        // This forces inertia to make a hard reload when the template changes.
        return $this->rootView . parent::version($request);
    }

public function handle(Request $request, \Closure $next, $rootView = null)
    {
        if ($rootView) {
            $this->rootView = $rootView;
        }

        return parent::handle($request, $next);
    }

Also remove HandleInertiaRequests from global middleware and add it as named middleware
    protected $routeMiddleware = [
         ...
        'inertia' => \App\Http\Middleware\HandleInertiaRequests::class,
    ];

and now you can populate routes, routes groups as you need
Route::group(['middleware' => ['Admin:Client.Dashboard.app']], function () {
    Route::get('/admin/dashboard', [
        'as'   => 'admin.dashboard',
        'uses' => 'Admin\DashboardController@index',
    ]);
});
Route::middleware('inertia:app')
    ->group(base_path('routes/auth.php'));

A: You can change the root template of interia in middleware(HandleInertiaRequest.php) using property and also with method
// Set root template via property
protected $rootView = 'app';

// OR
// Set root template via method
public function rootView(Request $request)
{
    return 'app';
}

Now filter the request in rootView() method and change the root template according to your need just using a simple if-else conditions.


text:
Q: Sharing JDO classes between google app engine and other platforms I have a perfectly running GAE project using JDO 2. I use IntellJ to develop with.
I want to move some of my awesome code onto platforms other than GAE, like Jetty. So, I want to create a module that can be used by both the GAE project and the jetty project to pretty much the same thing on the data layer. Structured as:

*

*GAEProject

*JettyProject

*SharedModule

I'm moving my PersistenceCapable JDO Classes to the SharedModule, everything compiles ok. JettyProject works just fine persisting data to a mysql db using the same code that once persisted to the app engine data store..
When I go to run the GAEProject, i get an error:
Google AppEngine Enhancer: SEVERE: Bundle "org.datanucleus.api.jdo" requires "org.datanucleus" version "3.2.4" but the resolved bundle has version "3.2.4" which is outside the expected range.
not helpful. It's a problem with the enhancer. I think I need to figure out how to get GAE Enhancer to enhance the classes in the second module. When i use IntellJ to configure the enhancer, it won't let me set directories to enhance to those outside the GAEProject.


text:
Q: What is the difference between armcc and armclang? armcc and armclang are the compilers for embedded C and C++ code. Recently, armclang has been gaining popularity as an alternative compiler.
What is the difference between armcc and armclang? Is there an advantage to using armclang?

A: The difference is what you'd expect if you give two different groups of people the same task like, "implement a compiler for this language" or "build a house from this blueprint".
The observable behavior of programs compiled with either compiler should be the same (and most often is) but there will be differences in how the final program achieves the observable behavior.
You can look at the executable's size, the assembly code and do performance measurements (benchmarking) to notice these differences - and then decide which one that suits your needs the best.


text:
Q: Best way to implement Sockets in Android to build a messaging application I am learning about Socket programming in Android basically to create a simple messaging app for learning purpose.
I have found out a lot of helpful materials online to get started with it. Like this one for eg.
However, in the above article, we need to manually enter the server ip address in the client to establish a connection between both of them.
I would like to know whats the best way of making this process automatic?.
One way I thought of was by using GCM. When a device A wants to communicate with device B, A will first send its ip address and port number (where it will be listening for incoming msgs)to B via GCM and B also does the same thing.
Now both the devices know each others ip address and port number on which they are listening, from here onwards they can start communicating with each other.
[Note: I am not considering GCM as a primary way of messaging as I have read in many blogs its not that fast for instant messaging].
This is just a thought. I would like to know what is the best way of doing this for a messaging application. Thanks.