Can I keep using my Xbox One offline indefinitely without updating (after updating this one last time)?

Question: tl;dr version:
I haven't connected my Xbox One to the Internet for years, and it still plays all my old Kinect games perfectly.  But I have a new game (NHL 2021) that won't install unless I update it.  My question to you Arqade readers is: if I connect my Xbox One to the Internet again to update it, will the update make things worse by making the Xbox One stop working unless I keep reconnecting to the Internet?  Has anyone here tried disconnecting the Xbox One from the Internet, and found that they couldn't use it?
Longer version of my post as follow-up:
I love my Xbox One, which we bought many years ago for its Kinect so we could stay physically active at home.  I have a handful of games, most of which use the Kinect (it came with Kinect Sports Rivals, Dance Central Spotlight, and then I bought Kung-Fu for Kinect and Fru).
The Xbox One hasn't been connected to the Internet for years, which is the way I want it.  Once, about a year after I bought it, I did connect, and after it updated itself, our profiles and records for Kinect Sports Rivals disappeared, and we had to restart our achievements.  But that's not the main reason I separate it from the Internet.  The real reason is that I end up updating to a version that forces me to stay online and keep updating.
By nature, computers do repetitive tasks exactly as instructed, and a working computer should continue working forever unless something changes (memory fills up, or one of its chips finally breaks down after decades).  But this means that, once you buy a computer system which does everything you need, you never need to spend any more money on it.
Of course, the computer industry continues to make money because advances in technology and the way we do things mean that a computer syste will no longer "do everything I need" because the needs change.  But the computer itself ... think about the last computer/phone/device you replaced with a newer model.  That older computer ... exactly what does it no longer do that it did before?  Nothing.  (Unless the software stopped working because "it's time to upgrade", or "everyone uses 4G now so 3G is too slow for me" etc.)
But what if people's needs don't change?  There was a slowdown in the statistics of the PC industry a number of years ago, exactly for this reason.  Windows 7 was good enough, and computers worked well enough, and we users could coast for a long time.  The result was that people didn't upgrade to Windows 10.  So Microsoft forced people to upgrade (e.g. popping up a window in the middle of the night that said, "Okay, I'm giving you freedom of choice to cancel this automatic upgrade by clicking stop before 5am, ok?")

https://www.slashgear.com/windows-10-users-are-grumpy-over-forced-updates-and-unwanted-apps-18643135/
https://answers.microsoft.com/en-us/windows/forum/all/forced-windows-updates-ridiculous/070bdcc8-c2ff-43c8-a8d8-6c304765cb0f
https://www.techradar.com/news/some-windows-10-updates-will-soon-be-force-installed-whether-you-like-it-or-not
https://www.makeuseof.com/microsoft-windows-update-forced/
https://www.403tech.com/hijacked-by-windows-10-what-to-do-and-not-do-if-you-catch-your-computer-forcing-an-upgrade/

Gradually now, it has become accepted that software will stop working after a while, even though this is just artificially designed "planned obsolescence".  You have to keep updating programs such as WhatsApp, not because it becomes a security risk or people have moved on to better protocols, but just because it's programmed not to work after a certain date.
I don't want that to happen to my Xbox One, which currently doesn't know it's supposed to stop working after a while.  I am afraid that if I update, the Xbox OS will be updated so that I won't be able to stay off the Internet indefinitely.
On the other hand, it refuses to install NHL 2021 unless I upgrade.  It's not that much of a loss for me, but I'd like to be able to install it, and perhaps a few other games for now, and then I'd be happy to take the Xbox offline again for another few years.
So, I would like to draw on the collective wisdom of the StackExchange (Arqade) community to ask: if I connect my Xbox One online to update, will it get my Xbox One addicted to updating?
(I tried posting this to Reddit but for some reason it wouldn't let me.)
Comment: One of the reasons companies try to get you to update is that it makes technical support easier for them. If you call technical support and it turns out that you haven't updated in 4 years, it's entirely possible that the issue you're having was fixed in one of the updates you never downloaded. Even if it isn't, the support person might have a frustrating time digging through archived technical manuals to find the procedures that are right for the software version you're using.
Comment: Usually when an online app like WhatsApp stops working until you update, that's because of API changes on the backend, not because of a planned obsolescence timer.
Comment: Should this question be trimmed? Most of it isn't directly related to the question, and reads like a forum post
Comment: @TankorSmash I agree, there's a lot of unnecessary content in Reddit-style
Comment: Hey @Kevin, I'm interested in your argument about Whatsapp stopping working because the "API changes on the backend". Could you please elaborate? Or maybe should I ask a separate question elsewhere? If yes and you could point me to the most appropriate site, I'd highly appreciate it.
Comment: @LoremIpsum I'll explain at https://chat.stackexchange.com/rooms/133546/app-updates-and-apis
Answer: The Xbox OS that original Xbox One uses is still the same OS that the new generation of Series X|S consoles are using(which is probably the OS update that NHL 21 would be asking for). They can be played offline without any issue.
However, Kinect has been deprecated. The Series X|S are pretty incompatible, whether an OS Update solidified that or just hardware (the consoles do not have built in ports) is unknown. It may still function, but Xbox/Microsoft no longer support it and have it placed firmly in "end of life", so if an update does "break" it, because it's not tested for compatibility anymore. They don't have any obligation to fix it.
Comment: Thanks for the info!  But even with the same OS, will it get tweaked so it requires an update?  Have people had experience NOT updating for a long time, and the Xbox One still works? (with the games already installed -- I understand it might require an update if newer games are installed)

On the other hand, I am not that worried about the Kinect not working, because Just Dance 2022 came out for the Xbox One Kinect -- surprising, since most other games no longer use the Kinect.  But the existence of this game means the Kinect must still be working, if not updated for much longer.
Comment: apologies for not accepting the answer earlier


Debug desktop environment run

Question: I've installed a Pantheon desktop environment (the one from elementaryOS) over Ubuntu 18.04 and now I have an issue staring this DE from lightdm. Particularly when I'm choosing Pantheon DE from lightdm menu before login, enter password and then press enter/login, screen becomes dark, and it returns back to the lightdm.
How can I debug this issue? How can I run DE directly from the tty1 without running display manager and see what is going wrong?
Answer: Now I know how to:
<code>startx /usr/bin/ghome-session --session=pantheon
</code>

Debug desktop environment run


Playhouse Structural Question

Question: I have created a playhouse deck that is 8'x 8' and 5' off the ground. It is supported by 10' 4x4s on all four corners.
I want to place a 12' beam across the top of two of 4x4s in order to place a simple climbing rope.
Question:
Are there any charts or other guidance that I can use to determine:
1) Is this possible?
2) How much bracing is needed?
Comment: What's in the playhouse? Will you adopt me?
Comment: I'd be wary of a rope hanging from a [cantilever](http://en.wikipedia.org/wiki/Deflection_%28engineering%29) unless you poured footings for the playset. I recommend using [through-bolts and following Chicago's deck codes](http://diy.stackexchange.com/questions/44399/what-would-a-calculation-be-for-the-weight-bearing-capacity-of-6-x-2-studwork/44499?s=1|0.1069#44499).
Comment: Ha, I'm using a plan from Ana White's site as a base plan and then trying to increase the awesomeness as much as my HOA regs allow. http://ana-white.com/2011/03/kids-playhouse-and-slide
Comment: If I bring the 4x4 and the simpson strong ties to put in the rope, will you let me install a zip line on the other side ?
Answer: Simple in theory.  Assuming you are mounting the beam to the side of the post at the top.  You have an ideal situation for a cantilever.  It even follows the old rule of 1/3 (cantilever), 2/3 (back span).
To size it, find any floor joist chart and figure the span of 8'.  A 2x8 spans upward of 12'.
Load wise you will probably never hit over 200-300 lb on the rope swing so a couple 3/8"-1/2" through bolts at each post through the beam would be overkill.  With those loads, even 6-8 long screws would be more than enough (@ aprox 70-100lb+ per screw).
Biggest problem will be rot between the beam and the post over time as water gets trapped between the two.  For this we usually use the through bolts and put a small stack of galvanized washers (5-10) between the post and the beam.
As for bracing it laterally, using a wider member like a 4x would help.  So a 4x8 would probably be ideal, and a 4x6 should work well enough.  But then you need through bolts for sure.

Playhouse Structural Question


how to close mdiparent form from a dialogue form (like license form)

Question: I'm trying to close my main form if the user clicks on the exit button on license form or close it.
I try this code on exit button but didn't work:
//--------------------------------------------------------------------
<code>    private void button2_Click(object sender, EventArgs e)
    {
        Form1 aa=new Form1();
        aa.Close();
        this.Close();
    }
</code>
//--------------------------------------------------------------------
I'll be thankful if somebody can help me!
Comment: Use Environment.Exit() to ensure a program exits.
Answer: If that Parent form is the Main form in your application then you can use
<code>Application.Exit();
</code>
To know more go here.


Can't get ResponseStream from WebException

Question: I have a desktop client, that communicates with serverside via Http.
When server has some issues with data processing it returns description of an error in JSON in Http response body with proper Http-code (mainly it is HTTP-400).
When i read HTTP-200 response everithing's fine and this code works:
 using (var response = await httpRequest.GetResponseAsync(token))
                {
                    using (var reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                    {
                        return await reader.ReadToEndAsync();
                    }
                }

But when an error occures and WebException is thrown and caught there is this code:
 catch (WebException ex)
            {
                 if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    using (var response = (HttpWebResponse) ex.Response)
                    {
                        using (var stream = response.GetResponseStream())
                        {
                            using (var reader = new StreamReader(stream, Encoding.GetEncoding("utf-8")))
                            {
                                var json = reader.ReadToEnd();
                            }
                        }
                    }
                }
            }

I have already done something to it to maybe make it work, but the next happens:
response.ContentLength is valid (184)
but stream.Length is 0
and after that i can't read json (it's "")
I don't even know where to look, because everything looks like it should work.
What might be the problem?
Answer: After a month of almost everyday thinking I've found workaround.
The thing was that WebException.Response.GetResponseStream() returns not exactly the same stream that was obtained during request (can't find link to msdn right now) and by the time we get to catch the exception and read this stream the actual response stream is lost (or something like that, don't really know and was unable to find any info on the net, except looking into CLRCore which is now opensource).
To save the actual response until catching WebException you must set KeepAlive Property on your HttpRequest and voila, you get your response while catching exception.
So the working code looks like that:
            try
            {
                var httpRequest = WebRequest.CreateHttp(Protocol + ServerUrl + ":" + ServerPort + ServerAppName + url);

                if (HttpWebRequest.DefaultMaximumErrorResponseLength < int.MaxValue)
                    HttpWebRequest.DefaultMaximumErrorResponseLength = int.MaxValue;

                httpRequest.ContentType = "application/json";
                httpRequest.Method = method;
                var encoding = Encoding.GetEncoding("utf-8");

                if (httpRequest.ServicePoint != null)
                {
                    httpRequest.ServicePoint.ConnectionLeaseTimeout = 5000;
                    httpRequest.ServicePoint.MaxIdleTime = 5000;
                }
                //----HERE--
                httpRequest.KeepAlive = true;
                //----------
                using (var response = await httpRequest.GetResponseAsync(token))
                {
                    using (var reader = new StreamReader(response.GetResponseStream(), encoding))
                    {
                        return await reader.ReadToEndAsync();
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    using (var response = (HttpWebResponse)ex.Response)
                    {
                        using (var stream = response.GetResponseStream())
                        {
                            using (var reader = new StreamReader(stream, Encoding.GetEncoding("utf-8")))
                            {
                                return reader.ReadToEnd();
                                //or handle it like you want
                            }
                        }
                    }
                }
            }

I don't know if it is good to keep all connection alive like that, but since it helped me to read actual responses from server, i think it might help someone, who faced the same problem.
EDIT: Also it is important not to mess with HttpWebRequest.DefaultMaximumErrorResponseLength.
Answer: I remember facing similar issue before and there was something related to setting the stream's position. Here is one of my solutions for reading webResponse that worked for me earlier. Please try if similar approach works for you:-
private ResourceResponse readWebResponse(HttpWebRequest webreq)
    {
        HttpWebRequest.DefaultMaximumErrorResponseLength = 1048576;
        HttpWebResponse webresp = null;// = webreq.GetResponse() as HttpWebResponse;
        var memStream = new MemoryStream();
        Stream webStream;
            try
            {
                webresp = (HttpWebResponse)webreq.GetResponse();
                webStream = webresp.GetResponseStream();
                byte[] readBuffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = webStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                    memStream.Write(readBuffer, 0, bytesRead);
            }
            catch (WebException e)
            {
                var r = e.Response as HttpWebResponse;
                webStream = r.GetResponseStream();
                memStream = Read(webStream);
                var wrongLength = memStream.Length;
            }

            memStream.Position = 0;
            StreamReader sr = new StreamReader(memStream);
            string webStreamContent = sr.ReadToEnd();

            byte[] responseBuffer = Encoding.UTF8.GetBytes(webStreamContent);
//......
//.......

Hope this helps!
Comment: Thanks for trying, but it didn't help. I've rewritten everything, using your code with synchronious calls (I've thought about streams working weird in different threads) but still nothing: on HTTP-400 `e.Response.ContentLength` is `184` and `webStream.Length` is `0`


What is the tallest trees can grow in the Jungle Biome?

Question: Between what heights will "Jungle" biome trees grow to?  I'm curious because sometimes I get really short awkward trees, and at times I get huge trees with multiple layers of leaves.  Is there a minimum height or maximum height?
Comment: Maybe this question/answer will help? http://gaming.stackexchange.com/questions/52938/how-do-i-make-big-trees
Comment: Unfortunately, no.  I know how to grow jungle trees, but the heights in which they grow are often random....
Answer: According to Wikipedia there is no real limit found in the code with regard to the height cap. There is however a limit found in the number of logs of which a tree may exist of: 55.
Comment: Wikipedia, or the Minecraft Wiki?
Comment: so the max height of a jungle tree (2x2 saplings) is 13?
Answer: I've grown ones that are 31 in height, from ground to the top of their leaves. I doubt that's a maximum though.
As for a minimum, you could get at that by trying to grow trees under platforms of different heights.


R xlim ylim and coord_cartesian not functioning as expected

Question: p <- ggplot(data = df,aes(label1 = label1 , label2 = label2 , label3 = label3 , label4 = Label4 )) +
  geom_point(aes(point1, point2, color = color_column)) +
  theme(legend.text=element_text(size=rel(0.6))) +
  facet_wrap(~ color_column, nrow = 4, ncol = 2) +
  scale_color_manual("legend", values = my_colors)+
  xlim(0, 10) + ylim(0, 10)

  ggplotly(p,dynamicTicks = TRUE, width = 1000, height = 1000)

I am noticing that xlim and ylim does not function as expected and my charts have axis scales at random. Likewise, applying coord_cartesian does not fix the problem either.
Does anybody know the issue here?
Comment: It would be easier to help if you create a small reproducible example. A (example) dataset `df` and the vector `my_colors` are missing in your question but they are necessary to run your code. Here are some information about reproducible examples: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
Answer: It seems changing the final line to dynamicTicks = FALSE resolved the problem of ggplotly overwriting my ylim settings.


Binding to a List with Lightswtich

Question: I have a Lightswitch app which creates a series of survey questions, with answers.  I have 2 datagrids, 1 for the questions and 1 for the answers.  When the selected item in Questions changes, the datagrid for the answers updates.  I'd like to be able to preview what the data looks like for each question individually in my Silverlight control.
I'm binding the question property to the Screen.SurveyQuestions.SelectedItem.Question.  Now I'm not sure how to grab the answers.  If I bind my List<string> to Screen.SurveyAnswers, I get null every time, though I know there is data there.  Since SurveyAnswers is a complex object, I have a method that just pulls the Answer string and stores it in a list, which I have also tried binding too.  This works...the first time only.
Is there a way to RaisePropertyChanged or to break the binding and rebind?
Answer: sorry, I am a newby, but hope you will be more happy with my answer then with none :)
I would try to create new Query for the answers grid (if you don't have any yet) and then i would set a parameter for that answers query which would be bound to selected Question object (or to some of its properties). Query designed like that should keep en eye on a parametr change, so it should refresh the answers view.
Hope I ain't wrong and that it helps.

Binding to a List with Lightswtich


Git says that a deleted file would be overwritten by merge

Question: When I'm trying to git pull it won't let me, saying that local changes would be overwritten by merge. The thing is that the file it specifies, that it would be overwritten is deleted. I had it before but I deleted it and I can't see it neither from the editor tree view, nor from the file system. What kind of bug is that? How can I get rid of it and pull?
Comment: Please checkout specific file which gives overwrite error e.g. -  "git checkout -- app/webroot/css/alert.css"
Answer: Make sure you have committed all the changes. Otherwise, stash all the changes.
$ git add .
$ git stash
$ git pull origin <branch-name>

Comment: @TristanTzara: please add `git status` output to your original post, to show that there are no deletions yet to be committed. Otherwise I believe this is the correct answer: that you committed other changes, but not the deletion itself.
Comment: I definitely have all the changes committed
Comment: @TristanTzara Not just changes you've done while adding/modifying, but also changes while deleting. In this case, overwrite means that the file you've deleted will come back in the other branch, so you should stash/commit to preserve your changes to the working directory.
Comment: @TristanTzara you are right I have now the same case (after 6 years) when all changes are commited/stashed and the same problem
Answer: It's not a bug. It's a change, that will become ineffective if you pull(because your pulled branch will have different commits in it). Git wants you to preserve that change.
Stash that change using git stash or make a commit in another/new branch.
Answer: This isn't a bug as far as I know.  I believe this situation arose because you deleted a certain file which is still present in the branch which is incoming during the merge.
Merging via git pull won't work as you showed us, but it appears that pulling via rebase should work.  Try this:
git pull --rebase origin yourBranch

You will most likely get merge conflicts when you apply each of your commits on top of the new base.  And the conflicts may include a situation where the file in question appears there but should really be deleted.  In this case, if you want it gone the resolution may actually be to delete the file.
Here is a reference which mentions several possible solutions:
Git pull error: Your local changes to the following files would be overwritten by merge:


Copy a folder name into the name of its files

Question: I have a folder with the name "Mexico" and inside I have pictures in .jpg  . How do I copy the folder name into the filename.
thats current:
Mexico(folder)
1.jpg
2.jpg

thats what I want:
Mexico(folder)
 Mexico1.jpg
 Mexico2.jpg

And afterwards cut out the picture files and send them into a different folder called "Pictures" where I have other pictures. And delete the original Mexico folder. Both folders are unrelated. Let's say they are both on the Desktop seperate from each other.
End result:
Pictures
 -Mexico1.jpg
 -Mexico2.jpg
 -other.jpg
 -... .jpg

Didn't find a good answer online. Prefer simple solutions, I am newbie. And it should be automated so it can be used for many folders in a row. All folders have different names i.e 'Mexico', 'Spain'...It is too many folders & pictures to change the names by hand.
Thanks in advance
Comment: Is the Mexico folder inside the Pictures folder? Outside? If so where it it in relation to the Pictures folder?
Comment: Pictures folder is outside Mexico. Let's say on the Desktop. They have no connection, just 2 different folders.
Comment: If you can specify the relative location of the two, this could probably be done in one command. So if you have `~/Desktop/Mexico` and `~/Pictures`, something like: `cd ~/Desktop/Mexico; rename -n 's,^,../../Pictures/Mexico-,' *.jpg`
Comment: mexico: /home/user/Desktop/Mexico ; Pictures: /home/user/Desktop/Pictures
Answer: If both directories are located in the same parent directory, in Desktop as an example, you can use something like:
cd ~/Desktop
rename -n 's,^(.*)/,Pictures/$1-,' Mexico/*.jpg Spain/*.jpg

Note that this doesn't actually do any moving or renaming, it will just show you what will be done. Run the command without -n after you verify that everything looks good in the output to do the actual renaming.
Then you can delete these empty directories with:
rmdir Mexico Spain

Or even just:
rmdir */

This will fail to delete non-empty directories but delete empty ones.
Comment: Substitution replacement not terminated at line 1, in:
s,^(.*)/,Pictures/$1-                   ; the problem is also that all folders and files have different names, maybe I wasn't clear sry
Comment: @stony56 ah, sorry, there should be a comma at the end, fixed. Is there any pattern at all? At least if all files end with `.jpg`? If not, you'll have to list out the directory names one by one in the command like in the example.
Comment: thanks. no pattern other then .jpg of all files. It's ok this solutions would work for what I described.
Answer: In a Bash shell loop with mv:
for f in */*; do
  if [ "${f%/*}" != "Pictures" ]; then
    echo mv -nv -- "$f" "Pictures/${f%/*}${f#*/}"
    fi
  done

You'll need to cd ~/Desktop then run the loop and finally remove empty directories with rmdir */ ... Or do all at once:
{
cd ~/Desktop
for f in */*; do
  if [ "${f%/*}" != "Pictures" ]; then
    echo mv -nv -- "$f" "Pictures/${f%/*}${f#*/}"
    fi
  done
rmdir */
}

Notice that echo is added for a dry-run, so remove it when satisfied with the output to do the actual renaming.
Demonstration:
$ tree ~/Desktop
/home/ubuntu/Desktop
├── Mexico
│   ├── 1.jpg
│   └── 2.jpg
├── Pictures
│   ├── 1.jpg
│   └── 2.jpg
└── Spain
    ├── 1.jpg
    └── 2.jpg
$
$
$ {
cd ~/Desktop
for f in */*; do
  if [ "${f%/*}" != "Pictures" ]; then
    mv -nv -- "$f" "Pictures/${f%/*}${f#*/}"
    fi
  done
rmdir */
}
renamed 'Mexico/1.jpg' -> 'Pictures/Mexico1.jpg'
renamed 'Mexico/2.jpg' -> 'Pictures/Mexico2.jpg'
renamed 'Spain/1.jpg' -> 'Pictures/Spain1.jpg'
renamed 'Spain/2.jpg' -> 'Pictures/Spain2.jpg'
rmdir: failed to remove 'Pictures/': Directory not empty
$
$
$ tree ~/Desktop
/home/ubuntu/Desktop
└── Pictures
    ├── 1.jpg
    ├── 2.jpg
    ├── Mexico1.jpg
    ├── Mexico2.jpg
    ├── Spain1.jpg
    └── Spain2.jpg

Notice that this will not work on hidden files/directories that start with a dot . unless you explicitly set Bash's dotglob option.
Answer: The following script should work.
for file in $(find "./$1" -type f);
do
    cp $file "./Pictures/$1$(basename $file)"
    done

It goes through the files in the $1 (argument 1) directory, it then copies it to the Pictures directory with the prefix of $1. It copies rather than moves to make mistakes reversable. Argument 1 is the name, not path, of the directory of the photos and the prefix.
Edited as per @Dan's suggestion to use quotes, which you might want to keep in mind if you get more involved with scripts.
Comment: You should use quotes around your variables in case they contain spaces or other special characters
Comment: @Dan agreed - unfortunately `for file in $(find ...)` introduces word splitting from the get go which no subsequent quoting can undo - see for example [Why is looping over find's output bad practice?](https://unix.stackexchange.com/questions/321697/why-is-looping-over-finds-output-bad-practice)
Comment: I am new to scripts but I'll try it and report back later, thanks.


using single database file for multiple users

Question: I want to make a site in which every user has his own customers and products to manage.
Whats the best way to handle this??
Is it OK to use an additional field for each entry specifying the user this entry belongs to ? or there is a better way?
Im using sql server if it matters.
Thank You.
Comment: Just as a pro-tip, some people might be put off answering you because of the awful answer rate you have. Also, the way you make this sound is that the idea is to have different databases for each user? Is that correct?
Comment: @Arran thank you very much brother :)
im new here and i didnt notice..
Comment: @Arran im trying to avoid creating a new database for each user..
Answer: not really much info in the question... however:
it is much simpler to scale some more data in a single database than to create additional databases.  so YES - make one database.
the exact schema you choose is more subtle - normalize, and link rows to appropriate users
Comment: got it.. so the best way to do that is to add a field for each entry for specifying the UserId this entry belongs to, right ??
Answer: Do NOT I repeat do NOT create a database per user, not even a table per user.
Add a column UserID to any table that may need  to reference a person with a product or order.
Comment: got it.. so the best way to do that is to add a field for each entry for specifying the UserId this entry belongs to, right ??


calling class function in another class function in javascript

Question: I want to call posts() in refresh function.
Here is my code.
var TIMELINE = TIMELINE || (function (){

    /*** private ***/
    var _args = {};
    var self = this;

    return {

        init : function(Args){
            _args = Args;
        },  // init
        posts : function(data) {

            alert('posts called');

        },  // posts
        unsetMarkers : function() {

            alert('unsetMarkers called');

        },   // unsetMarkers
        refresh :   function(){
            self.posts;
        }

    };

}());

the problem is at this line self.posts;
I also tried self.posts({'data':'success','another':'thing'});
How I can use posts in refresh?
Comment: *"I want to call posts() in refresh function."* Cool. And what's your question?
Comment: call like "self.posts(data);" :D
You also have to pass in Data. But I do not see data constructed anywhere.
Comment: @FlixKling
the problem is at this line self.posts; I also tried self.posts(); How I can use posts in refresh?
Answer: There are two problems in your code:

self doesn't refer to the object with the property posts, i.e. not to the object you are returning from the function. You have var self = this; and this refers to window (assuming non-strict mode).
You are not even trying to call the function.

Instead of returning the object immediately, assign it to self:
// instead of `var self = this;`
var self = {
   // function definitions
};

return self;

and then you can call the method with
self.posts(); // note the parenthesis after the function name

If you are certain that the refresh function is always called as TIMELINE.refresh() (i.e. as a method of the TIMELINE object) , then you can also call the posts method with
this.posts();

and forget about self.

Further reading material:

MDN - this: Learn which value this has in different contexts.
Eloquent JavaScript - Functions: Learn how functions work.
Answer: refresh :   function(){
    this.posts();
}

JSFIDDLE


How do I apply a regex substitution in a string column of a DataFrame?

Question: I have a DataFrame called "Animals" that looks like this:
 Words
 The Black Cat
 The Red Dog

I want to add a plus sign before each word so that it looks like this:
 Words
 +The +Black +Cat
 +The +Red +Dog

I have tried this using regex but it did not work:
 df = re.sub(r'([a-z]+)', r'+\1', Animals)

Answer: You can use str.replace with the following regex to make the change to all rows of the column:
df.Words = df.Words.str.replace(r'(\b\S)', r'+\1')

The DataFrame then looks like this:
>>> df
              Words
0  +The +Black +Cat
1    +The +Red +Dog

Comment: Very good, thank for for the solution.  I know not part of the original question but was wondering whether this could also be adapted to remove white space between words?
Comment: @user3682157: no problem, glad it helped. To remove all of the whitespace you could perhaps use `df.Words.str.replace(r'\s', r'')`.


How to covert ddmlib.RawImage into bitmap or jpg image in android?

Question: I am trying to port Java code to android code. source code is here :
screenshot:java
here

RawImage raw=device.getScreenshot();

which captures screenshot of android screen and save it as RawImage.
this RawImage is defined in "ddmlib.RawImage" (ddms ) which is further converted into BufferImage. Now the problem is - android doesnt support java.awt.image.BufferedImage.
So, how this RawImage  can be coverted in Bitmap or any other android supported image format.
Alternatively , is there any way through which RawImage can be used directly either to display or to save in external storage ?
Comment: if (!ImageIO.write(image, "png", new File(filepath))) {
            throw new IOException("Failed to find png writer");
        }
Comment: have you noticed this thing which link you attached " screenshot:java"
Comment: @ A M : ImageIO is also not supported by android [link](http://stackoverflow.com/questions/16693011/cant-load-javax-imageio-imageio-lib-to-eclipse)
Answer: you can find the answer from the site
http://www.programcreek.com/java-api-examples/index.php?api=com.android.ddmlib.RawImage
u can test the source code(I have tested it ,it`s ok):
// convert raw data to an Image

BufferedImage image = new BufferedImage(rawImage.width, rawImage.height, BufferedImage.TYPE_INT_ARGB);

int index = 0;
int IndexInc = rawImage.bpp >> 3;
for (int y = 0 ; y < rawImage.height ; y++) {
    for (int x = 0 ; x < rawImage.width ; x++) {
        int value = rawImage.getARGB(index);
        index += IndexInc;
        image.setRGB(x, y, value);
    }
}

if (!ImageIO.write(image, "png", new File(filepath))) {
    throw new IOException("Failed to find png writer");
}


Bash - temporary files appear after sed

Question: in my script i edit a file by using "sed":
<code>sed -i -e /NumberOfEntries=*/d "$playlist_name" > /dev/null   # deletes "NumberOfEntries"-line
sed -i -e '/^$/d' "$playlist_name" > /dev/null   # deletes all empty lines
</code>
This works just fine but while execution (and shortly after) there are one or two temporary files named something like "sedJjHEt2" (the string after sed changes everytime i run the script). The file is marked with a lock and red X-Symbol.
Is there a way to turn this off or am I missing something that I need to adjust? Or is this because of the "-i" Option?
Thanks in advance!
Answer: Because of the "-i" Option.
once you use "-i", sed will create a temporary, and then replace the original file with the temporary file.

Bash - temporary files appear after sed


How can I get quake2 running on ubuntu without cd?

Question: When I launch quake 2 on my Ubuntu 15.04 I get the following error:

Missing data; see /usr/share/doc/quake2/README.DEBIAN

How do I fix this?
Answer: "Quake2 for debian" which is freely downloadable is just the game engine, you need the game data (found on game disk) as well to play Quake2.
Read that readme.debian to find information.
Comment: Read the top. Without CD
Comment: You want instructions for pirating a game. No.
Comment: Not exactly. If there is a demo or something that's what i'm looking for.  I have the demo, how do I build the data? When I launch it says, well, read the post


Gledhill 450 Torrent RE

Question: What is the top pipe connected to my Gledhill Torrent 450 RE thermal store?

It comes out of the very top of the tank. Not on the side but right on the top in the centre?
Answer: Looking at the installation and service manual, it appears to run to a feed and expansion tank to allow the water in your system to expand and contract safely as it heats and cools.

Gledhill 450 Torrent RE


Does x-ray lead paint detection find lead underneath latex topcoats?

Question: I have a 1921 home.  Guaranteed that the walls have lead paint somewhere beneath, right? All surfaces have been painted at least once if not 2 or 3 times since 2001.  The paint is all in good condition - no chipping. To my understanding, this is good encapsulation.
If we had someone do a lead survey with the xray gun, would these surfaces test positive for stuff beneath? Or does the gun ONLY test the surface layer?
I'm curious to know for sure that my surfaces are safe, but due to mandatory reporting/remediation, I don't want to risk testing positive from a sensitive instrument that picks up a signal from a very low risk and covered up surface.
Comment: No, it's not automatic that old paint has lead.  Lead oxides are only capable of making certain colors, and there were alternative pigments even then.
Comment: Ok sounds reasonable,  but white base was one of those colors, right? . As i understand,  lead paint was desirable as it went on smoother.  So wouldn't they have just added the pigment to white?
Comment: Yes, white base is one of the hues, but I was under the impression that it was a low quality white used in cheap paint. That jibes with its social legacy of being  found in tenements...
Answer: The short answer is Yes, X-ray lead paint detectors can 'see' lead through top layers of non-lead paint.
But it depends to some degree on the thickness of the layers of paint as well as the type of X-ray detector 'gun' used.
There are 2 types used for lead detection: K X-rays and L X-rays.
The K X-rays have higher energy than the L, which means that they are less attenuated by layers of paint.
So a K X-ray lead detector will be better able to detect lead in lower layers of paint than an L X-ray detector.
If you're concerned that you might get a positive reading from an X-ray lead detector, then you'd probably be better off having a chemical lead test done instead, since this should only be able to find lead in the surface paint layer.
Answer: XRF is testing the exposed surface it is pointed at, it does not "penetrate" to see if there is anything below that. It's not an "X-Ray" as in a medical X-ray that sees through things, it USES an X-ray beam generator to "fluoresce" (make glow) any metals on the surface it is aimed at; think in terms of a fluorescent light making a poster glow with different colors. The gun has a color analyzer that evaluates the colors that are reflected back as to the presence of specific metals, such as lead.
So if your painted surface has multiple layers of "clean" latex paint over the lead paint, the lead is covered up and not exposed to that x-ray beam. However if the latex is flaked off, chipped or worn down, the lead underneath may show up.
Edit; obviously brhans knows more about this than I do, I wasn't aware of there being two types.
Answer: In 2023, had a 1953 home XRF tested.  The crown molding (1x4) tested positive.  I personally had applied 2 coats of BEHR PRO semigloss over the painted surface w/o sanding in 2016.  The previous owner had applied at least 1 coat of latex ~2008. I conclude XRF has some depth of penetration.


Read java.util.Iterator parallely

Question: I am using the Cassandra java driver to read data from a Cassandra table. after i execute the query, I get a java.util.Iterator and I am reading it in a for loop.
I wonder if there is any possibility that I could read this iterator in-parallel rather than one item at a time in a for loop.
Can any of the N number of streaming APIs (FS2?) help me here?  (No I can't use Spark or Hadoop at this point of time.)
Answer: Did you try Java 8 Spliterator.

Spliterator  is an object for traversing and partitioning elements of a source. The
  source of elements covered by a Spliterator could be, for example, an
  array, a Collection, an IO channel, or a generator function.

If this is more of question to parallelize the given collection, as you  can create partitions and process each partition.
eg.
<code>Spliterator<CassandraRecord> cassandraRecordsSpliterator = recordsIterator.spliterator();

Spliterator<CassandraRecord> eachPartition = cassandraRecordsSpliterator.trySplit();

System.out.println(" " + eachPartition.estimateSize()); //will give you x
System.out.println(" " + cassandraRecordsSpliterator.estimateSize()); // will have N - x
</code>

Read java.util.Iterator parallely


Querying json field by array index and object property

Question: I have a column like:
[
   {
      "type":"menu",
      "prompt": {
            "type":"say",
            "message":"This is a menu. Pick option 1 or 2."
      }
   }
]

The first tier object could contain a variety of types and any number of types.  My objective (for automated testing, not production, so it can be inefficient) is to find a record with any column.*.type = menu.
Based on https://stackoverflow.com/a/22687653/197606 I understand I can provide a numeric index, but running the query SELECT * FROM my_table WHERE 'my_column'->0->'type' = 'menu' throws the error:
ERROR:  operator is not unique: unknown -> integer
LINE 1: SELECT * FROM my_table WHERE 'my_column'->0->'type' =...
                                                       ^
HINT:  Could not choose a best candidate operator. You might need to add explicit type casts.
Query failed
PostgreSQL said: operator is not unique: unknown -> integer
Hint: Could not choose a best candidate operator. You might need to add explicit type casts.

While specifying a numeric index of 0 would work for this specific use case and is an acceptable answer, I'd prefer an approach that isn't picky about the column index.
Comment: Do you need this: `SELECT * FROM my_table WHERE my_column->0->>'type' = 'menu'`  ?
Comment: @OtoShavadze Bingo, that was it!
Comment: @OtoShavadze Can you post this as an answer so I can give you credit?
Comment: Ok, I posted it as an answer ))
Answer: You can use this:
SELECT * FROM my_table WHERE my_column->0->>'type' = 'menu'

Answer: PostgreSQL does not allow to look in json array. Your solution might be something like this:
SELECT *
FROM my_table
WHERE EXISTS (
      SELECT 1
      FROM  jsonb_array_elements(my_column) AS j
      WHERE j->>'type' = 'menu'
)


Plot multiple y-axes in Plotly

Question: I have the following code for my layout:
<code>    var layout = {
        title:"Energy usage of green electrical appliances",
        plot_bgcolor:"#000",
        paper_bgcolor:"#000",
        showlegend:false,
        margin:"{l: 40, b: 40, r: 80, t: 40,}",
        xaxis:{
          title:"Date/Time",
          autoscale:"true",
          rangeselector: {
            bgcolor:"#555",
        },
        yaxis:{
          title:"Price",
          autoscale:"true",
          overlaying:"y2",
          side:"left",
        },
        yaxis2: {
          title:"Electricity Used",
          autoscale:"true",
          side:"right"
        },
        yaxis3:{
          title:"AiJ/day",
          autoscale:"true",
          side:right
        }
     }
</code>
and the following code for my data:
<code>        var tracePrice=                {name:"Price",type:"scatter",x:output[0]["datetime"],y:output[0]["price"],line:{color:"orange",width:2},};
        var traceElecUsed=                {name:"Elec",type:"bar",x:output[0]["datetime"],y:output[0]["Elec"],line:{color:"cyan",width:2},};
        var traceAiJ=           {name:"aij",type:"scatter",x:output[0]["datetime"],y:output[1]["aijpercent"],yaxis:"y2",marker:{color:"#fff"},line:{color:"#555",width:1}};
        return resolve([tracePrice,traceElecUsed,traceAiJ]);
</code>
The thing is, everything works fine until I plot traceElecUsed. The units it usesare in the thousands, whereas price is often under £5 and AiJ is a percentage of 0-100%. I don't know if this is the root of the issue. If I remove it everything works fine.
Answer: The stackoverflow curse has got me again; I struggle for hours with something then once I've posted it the answer appears.
For those of you in the future that need this info, it relies on 'overlaying'
<code>    yaxis3: {
      title:"Aij",
      autoscale:"true",
      overlaying:"y2",
      side:"right"
    }
</code>

Plot multiple y-axes in Plotly


Crack in moulding

Question: I just had new cabinets installed. I was inspecting crown moulding and found a crack where it was nailed. I showed contractor the crack. He filled it. Should I expect a new piece of moulding. Or is the filling of a crack acceptable?
Comment: Is this painted or stained? I know you can see the crack when you look for it, but would an impartial individual stand in your kitchen and see the filled crack at a glance? Generally, cracks and nail holes get filled, but sometimes it's a matter of degrees.
Comment: If the crack is purely aesthetic and minimal, then filling it is normal.  If the crack split the moulding for a significant length, is causing other issues and/or is obviously visible after remediation (filling, sanding, finishing, etc) you have a case for replacement.
Answer: filling a crack is SOP. it might need to be touched up so finishes match, but its entirely acceptable
Comment: I agree filling a crack is SOP but it should match.

Crack in moulding


Can you continue a save from the digital version with the disc version?

Question: I have the digital PSN version of Dragon Age Origins on PS3 as a recent PS Plus title.
If I were to start a game on this version and bought the retail "Ultimate Edition" of the game, which includes the base game and all add-ons on disc, could I continue my save file of the digital version with the disc version and use the save to play the add-ons?
Answer: Yes, this should work just fine.  When I did this on the Xbox 360, I just used the disc to install the DLC from the Ultimate Edition and then still played the digital copy on my hard drive.


Confusion regarding ASCII

Question: I understand that ASCII is a scheme of character encoding, where a Byte is assigned a certain decimal number, hexcode or a letter of our alphabet.
What I don't understand and couldn't find out via Google is how exactly the computer deals with ASCII behind the scenes. For instance when I write a text file with the text "hello world", what is the computer doing? Does it save the bytes in memory and where does the ASCII encoding come into play?
Answer: Almost anything that computers store on disk, transfer over the network or keep in their memory is handled as 8-bit chunks of data, called bytes.
Those bytes are just numbers. Anything between 0 and 255 *.
So a 100 byte file is just 100 numbers one after each other.
A network message is similar: it's just a bunch of numbers one after the other.
(We tend to abstract over those and call them something like "streams", because at some level it often doesn't matter if you read from a file on disk or receive a network message, they are fundamentally just finite streams of bytes).
If you want to display a file from the disk as text, something needs to convert those numbers to something meaningful for humans. Because if I tell you that a file contains the bytes 68 65 6c 6c 6f 20 77 6f 72 6c 64 0a, then chances are you don't really know what that means. (By the way, those are hex values which is already an interpretation, one could equivalently say that the file contains the decimal byte values 104, 101, 108, ...)
ASCII is a pattern of how to interpret those numbers. It tells you that 0x68 (decimal 104) represents the character h. And that 0x65 (decimal 101) represents e. And if you apply that mapping to those bytes you'll get hello world.
That decoding only has to happen when the computer wants to show the text to a user, because internally it doesn't care that 0x65 is h. So if the computer wants to display some text to you it looks up what letter 0x65 represents h, probably represented again via its Unicode codepoint which happens to be U+0065 and then it looks up how that character is represented in the font. The font then has a mapping of U+0065 to some instructions on how to draw the h.
And since we're talking about ASCII it should be mentioned that ASCII is not actually used an awful lot these days, mostly because it only supports a very limited set of characters (basically just barely enough to write English language text, and not even all of that). More commonly used encodings today are UTF-8 (which has the benefit of being ASCII compatible which means all valid ASCII text is also valid UTF-8 text, but not the other way around) and UTF-16. Other encodings that used to be popular, but are on the decline are the ISO-8859-* family (which are basically extended versions of ASCII, but still only support a small number of characters each).
* So technically even saying "those are numbers between 0 and 255" is already an interpretation. Technically they are 8 bits, each one of which can be off or on. Those can be interpreted as an unsigned number (0 to 255), a signed number (-128 to 127), a character (using something like the ASCII encoding) or potentially anything else you want. But the "unsigned number" interpretation is one of the most straightforward ones.
Comment: The mapping of those 8 bits to an (unsigned) number is simply interpreting them as a [binary number](https://en.wikipedia.org/wiki/Binary_number) in a specific order. Just as decimal (10 digits) and hexadecimal (16 digits) are number formats, so is binary (2 digits). So the binary 1101000 is the same as the hex 68 or the decimal 104, they are the same number.  This mapping is not itself defined by ASCII, that's considered a given. Also **technically** ASCII only needs 7 bits, but since computers work with 8-bit units now, everyone just assumes it uses 8 bits and the highest-value bit is 0.
Comment: Just to understand better: "Those bytes are just numbers. Anything between 0 and 255." These are the numbers assigned within the ASCII Tables right?  And when does the computer translate the 8 bit chunk into a number like 101?
Answer:
For instance when I write a text file with the text "hello world", what is the computer doing?

When you hit those keys on your keyboard, a certain protocol between the keyboard and computer lets the computer know which keys were hit. The computer translates that into a character, like "h", based on what keyboard layout is currently selected. It may also cause your video game character to move sideways or whatever else, there's no direct connection between a key and what it causes to happen. But let's say you're in a text editor and your computer interpreted your hitting the "h" key as "inputting the letter h". It now turns that into some internal, in-memory character representation. Often in-memory representations will be UTF-16 encoded bytes, so the computer can represent any and all possible Unicode characters.
When you hit File → Save as..., you select to store the file in ASCII encoding. The text editor now goes through the UTF-16 bytes stored in memory and converts them all into equivalent ASCII bytes, according to a UTF-16/Unicode → ASCII encoding table. Those bytes are stored on disk.
When you open that file again, the text editor reads those bytes from disk, probably turns them into its internal UTF-16 representation, and stores them in memory so you can edit the file. At this point you can typically think about each character as a character; it doesn't matter what bytes it's encoded as, that is abstracted away. An "h" is just an "h" at this point.
Each in-memory character is mapped to a glyph in a font, typically by its Unicode code point, to be able to display a graphical representation of it on screen for you.

Confusion regarding ASCII


Newbie IDE (IntelliJ IDEA) issue: .class files not all usable

Question: I'm working on a school project right now, and every time I have in the past, I always make a new Project in IntelliJ IDEA. However, this time she gave us some .class files that have methods in them that we can't see (she described what they do so we know how to use them) but need to use, so they have to be in the same folder, obviously.
SIDENOTE: I'm also new to using Macs, which is what I'm on at the moment.
Anyways, I put the .class files in my src folder that I found in the Project8 folder. I just made an array of the Book objects, which was one of the .class files I moved, and now I need to use a method from the other .class file, named BookInventory.class. I put that file in the src folder just like the other, but it won't let me use the only method in that class, which is LoadBooks.
Here is the LoadBooks signature:
public static void LoadBooks(Book[] b)
And here's the description of it that she gave to us:
"For each element in the array, accepts user input for the book, creates the Book object, and stores the object into the array."
So, when I made the array of Book objects, IDEA made an import statement up top all by itself, I didn't type it:
import java.awt.print.Book;

So why does IDEA recognize the Book.class file and allow me to use it in this .java file for my project, but it doesn't seem to notice the BookInventory.class file?
Any help appreciated, thanks ahead of time.
Comment: I think this should answer your question: http://stackoverflow.com/questions/854264/how-to-add-directory-to-classpath-in-an-application-run-profile-in-intellij-idea
Comment: Did she give them as individual .class files, or packaged in an archive like a `.jar` file?
Comment: Individual .class files. Since I posted the question, I've added them to a separate folder I called "class files" and made it a module in my project, and made it a dependency to my project. It's still not letting me call the method, so I have no idea what to do now.
Answer: What is happening is when you first typed the line with LoadBooks(Book[] b), IntelliJ could not "see" your class files (you have subsequently loaded them in "class files" and added that as a project library, I presume).
IntelliJ however searched for and found a Book class in the internal java libraries, java.awt.print.Book. Note that this is a different class to the one your teacher gave you, which might have been e.g. edu.myschool.homework.Book.
Firstly, try to delete the line including the import statement, or manually change it to the correct package (your teacher can inform you what it is).
If the same import comes back automatically, you can go into Settings -> Editor -> General -> Auto Import and untick Add unambiguous imports on the fly - this will cause intellij to prompt you before adding imports.
Also, I would ask your teacher to give you the class files in a jar file, since that's the usual approach.
Good luck.


AttributeError: 'builtin_function_or_method' object has no attribute 'pop'

Question: Here is my code
def allButMax():
    input_list=[]
    user_input = 0
    num_sum = 0
    max_num = 0

    while user_input != "end":
        input_list.append(float(user_input))
        user_input = input("Enter next number: ")

    input_list = input_list[1:]

    input_list = input_list.sort

    input_listnew = input_list.pop(-1)

    for num in input_list:
     num_sum = num_sum + num

    print("The num of all values except for the maximum value is: ", num_sum)

When I run the program, it says

AttributeError: 'builtin_function_or_method' object has no attribute 'pop'

This program computes the sum of all the values entered except for the maximum value in the series
I do not know where I went wrong
Answer: The problem is on this line
input_list = input_list.sort

input_list.sort is not actually being called. You are just storing a reference to the function in input_list and consequently nuking the list.
sort is an inplace method, it operates on the list itself, rather than returning a new sorted copy of the list (see sorted). It returns None therefore you should not try to assign from its return value.
replace
input_list = input_list.sort

with
input_list.sort()

Comment: Correct, but this question is off-topic and it should be closed. The error was raised just because *a typo*. I'd suggest delete this answer and post a comment instead.


Confidence intervals and different methods of sampling

Question: I have two samples collected from the same population, where each sample is collected using a different method of selection, and both samples are large enough for the distribution of the sample distribution of the mean to be normal.
Now, when calculating two 95% confidence intervals for the mean, using each of the two samples, I get two non-overlapping intervals, so I can be fairly confident that one of the two samples suggest a larger population mean than the other sample suggest, or in other words, they are suggesting two different population means even-though they are sampled from the same population.
So, my question is now, is it valid to conclude that one, or both, of the sampling methods are flawed due to the discrepancy in the population means predicted by the two methods?
Answer: If both samples were random samples, then you would expect the means to be equal and the confidence intervals to overlap. While the mean need not be equal due to small sample size, the confidence intervals---if computed correctly---account for the small sample size and should overlap even for small samples. Only in less than 5% of the cases would you have nonoverlapping confidence intervals if both sampling was random and the population means were the same.
Hence, yes, you can reject the hypothesis of random sampling at a lower than 5% level. Whether that means the sampling methods are flawed---I don't know, depends on what they are supposed to achieve. If they are supposed to give you a random sample, then you can indeed view at least one of them as flawed.
Comment: Can you please try answering a similar question [here](https://math.stackexchange.com/questions/2909908/why-sampling-without-replacement-gives-better-ci-performance) as I am stuck for days


jQuery slider avoid calling event too quick

Question: I have this event function in Javascript:
            var slider  = $('#slider'),
                tooltip = $('.tooltip');
        //Hide the Tooltip at first
        tooltip.hide();

        //Call the Slider
        slider.slider({
            //Config
            range: "min",
            min: 1,
            value: 35,

            start: function(event,ui) {
                tooltip.fadeIn('fast');
            },

            //Slider Event
            slide: function(event, ui) { //When the slider is sliding

                var value  = slider.slider('value'),
                    volume = $('.volume');

                tooltip.css('left', value).text(ui.value);  //Adjust the tooltip accordingly

                $.ajax({
                    dataType: "text",
                    type: "POST",
                    url: '/setVolume/',
                    data: { volume_to_set: ui.value},
                    success: function(data) {

                    }
                });

                if(value <= 5) {
                    volume.css('background-position', '0 0');
                }
                else if (value <= 25) {
                    volume.css('background-position', '0 -25px');
                }
                else if (value <= 75) {
                    volume.css('background-position', '0 -50px');
                }
                else {
                    volume.css('background-position', '0 -75px');
                };

            },

            stop: function(event,ui) {
                tooltip.fadeOut('fast');
            },
        });

Everything is working properly, but I've seen that that when I'm moving the slider, it could become a lot of requests, if I'm changing it for 10 to 30 it'll actually send 20 ajax requests. which is not so efficient... I'm trying to think of a way that it'll recognize only the "end" of the sliding motion and only then run the AJAX request. any ideas?
Comment: How is it not called? Does it not fade out? BTW you have a trailing comma.
Comment: it should work on stop event
Comment: Tried, didn't work at all, the event was never triggered...
Comment: @epascarello is giving a better solution than the timeout. Moving it to the stop function is the best option.
Comment: Thank you, it was supposed to be triggered in stop, but for some reason the tooltip isn't working (this is why I assumed that start and stop event aren't working)
Answer: Remove it from slide and add it to stop
stop: function(event,ui) {
    tooltip.fadeOut('fast');
    /* Ajax call here */
}

Answer: You could use a setTimeout(); and clearTimeout();.
I would suggest creating the timeout when you slide.
var myTimeout = setTimeout(function(){
    // Run your script here.
}, 500 );

and then on your slide function, you would clear the timeout:
clearTimeout( myTimeout );

This will basically cancel the ajax call if the slide action happens again within half a second (500 milliseconds). It would be best to not redeclare the timeout variable in the slide function. Maybe scope it to your object?
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.clearTimeout
http://www.w3schools.com/jsref/met_win_settimeout.asp
//Hide the Tooltip at first
        tooltip.hide();
    //Call the Slider
    slider.slider({
        //Config
        range: "min",
        min: 1,
        value: 35,

        start: function(event,ui) {
            tooltip.fadeIn('fast');
        },

        //Slider Event
        slide: function(event, ui) { //When the slider is sliding
            var setVolume;
            clearTimeout( setVolume );
            var value  = slider.slider('value'),
                volume = $('.volume');

            tooltip.css('left', value).text(ui.value);  //Adjust the tooltip accordingly
            setVolume = setTimeout( function(){
                $.ajax({
                    dataType: "text",
                    type: "POST",
                    url: '/setVolume/',
                    data: { volume_to_set: ui.value},
                    success: function(data) {

                    }
                }, 500 );
            });

            if(value <= 5) {
                volume.css('background-position', '0 0');
            }
            else if (value <= 25) {
                volume.css('background-position', '0 -25px');
            }
            else if (value <= 75) {
                volume.css('background-position', '0 -50px');
            }
            else {
                volume.css('background-position', '0 -75px');
            };

        },

        stop: function(event,ui) {
            tooltip.fadeOut('fast');
        },
    });

Comment: It won't disable the last setTimeout unless the user slides again, which is the intention, if I'm not mistaken.
Comment: I thought about this solution, the problem with this solution that it might disable the last set timeout, and that means that the wanted volume won't be set.


Bugzilla: bugs are not showing up (show up in DB and everything seems to be fine)

Question: I just installed Bugzilla locally and it seems that everything is fine. I can create new products and components. I can also file new bugs and they show up in the database.
But when I want to view them in the web interface, they won't show up.
Instead, at the top of the page this shows up:
<code>Product: ARRAY(0x3735378    Component: ARRAY(0x4275650)    Resolution: ARRAY(0x42755a8)
</code>
and then below the "Zarro Boogs found."
I couldn't find any information on that on the web, did anybody have similar issues? Thank you!
Comment: Even I am facing same issue, Did you get it fixed? let me know if yes please.
Answer: Please check the bugs table in techzilla database and verify if the bug details are getting updated.
The cgi file which corresponds to the listing of bugs is buglist.cgi.
Template file is:-global/message.html.tmpl
Answer: "Zarro Boogs found." is showing because, the values are not correctly entering in the query to display the buglist.
It is evident from the display,
       Product: ARRAY(0x3735378    Component: ARRAY(0x4275650)    Resolution: ARRAY(0x42755a8)
it is because of the looping problem.
check the display code in the template file or buglist file and correct the loop, then it will dsiplay properly
Answer: Jenifer,
Yes, It is because of the zero value in the query. We can check it, by printing the query and checking the value in DB.
Inserts a Named Query (a "Saved Search") into the database, or updates a Named Query that already exists..
Answer: We had similar problem. Bugs were not showing in search result list. The problem was in the name of the product when the name of the product was with diacritics (e.g. Czech, Slovak, etc...). When the name of the product is in US ASCII it is all Ok.


Software compatibility across various linux distros

Question: If a program is developed for Linux, why exactly does it matter what distro you are using? How does installing programs like Steam/Dropbox/Skype work across distros like Mint, eOS, Debian, Fedora, etc.
On Steam's site for example it says:

Currently, Steam for Linux is only supported on Ubuntu 12.04 LTS or 12.10 with the Unity, Gnome, or KDE desktop. Additional distributions will be examined for support as time permits. For more information on Steam for Linux, see https://wiki.ubuntu.com/Valve

Do you really have to be running those DEs? Is it assumed that Ubuntu-based OSes like Mint, eOS would work fine? As well as the various Ubuntu flavors?
Or if you were running Ubuntu and downloaded the Fedora or opensuse download link on the Skype website would it simply not work?
Answer: All distributions of Linux do not use the same packaging systems and formats. They also do not all use the same build and compilation options for the software they do include. In the case of Skype, the only probably difference between the download links for Fedora, OpenSUSE, Ubuntu, or some other Linux, would be in how the files are packaged and installed on the system. There would be no advantage to trying to run a version built for another distribution of Linux, on Ubuntu, nor the reverse.
The Steam for Linux statement of support is so that Valve can limit the amount of problems they have to deal with. It's possible to run Steam under a different configuration for sure, but it will not necessarily be supported by them. Claiming to only support specific versions of Ubuntu with a specific environment being used, means that there is a known stable reference configuration to deal with. Supporting any version of Linux with any configuration means that it would have to be tested on all of those configurations, and versions.


How important to require users to put details on About Us?

Question: I am creating this application where business users can have a vendor page by providing details ex. services, prices, this happens only after these vendors signed up as an onboarding process. I also have this area where they can input "About Us" information, I want them to onboard right away by providing only some details that are really critical to their services like Prices and Type of Services. This application also has customers profile where they are the one who can interact with vendors to get the product or the service the user needs. I am not sure if it can affect us, the platform provider for both customers and businesses. Do I need to require these vendors or just optional having the About Us details?
Example below:
Facebook having this information as optional.
Comment: Can you give us more context?
Comment: We can't really tell what your users will prefer. You should test your designs with the users.
Answer: Well it really depends and it`s not necessarily about your business users preference, could be your need as a website owner for this or future customer needs who might only buy from businesses that have an About Us section.
You should evaluate how the "About us" part is having an effect on driving sales or increasing trust, help your site with SEO  & if you consider it effective you can still have it optional but have incentives ( telling business owners that businesses who have details on about us have a better chance of making a sell.
Answer: I believe, what you are asking, is a question about diminishing returns. You want to sign people up to your website and you have, correctly, identified that often, asking for too much information upfront can be a barrier to getting those users to sign-up.
No one here can tell you whether the 'about us' field is required before signing up, only your users and the business requirements for the application can tell you that, the decision needs to be balanced against what that bit of data gives you, against the potential for turning people off and not getting them to join.
Comment: Thanks Darryl, you can create a vendor page only after these business person or owners have signed up
Comment: Hard to see how it is an issue then?


Prime or composite calculator errors when I enter a composite number

Question: num = int(input("Enter A NUMBER: "))

def primeornot():
  for i in range(2, num//2):
    if (num % i) == 0:
      print(num, "is not a prime number")
    elif (num % i) != 0:
      print("Its prime!")

primeornot()

Try entering a composite number, such as 55, it will print many results. It will say that it is not prime, and then say that it is prime.
Comment: You're printing the output in a loop. Are you expecting a single result because that's not how you've coded it
Comment: You can't know that the number is prime until you get to the end of the loop without finding a factor.
Answer: Use break if it satisfies if condition and else block if it is prime
num = int(input("Enter A NUMBER: "))

def primeornot():
  for i in range(2, num//2):
    if (num % i) == 0:
      print(num, "is not a prime number")
      break
  else:
      print("Its prime!")

primeornot()


gtk_init caused crash on ubuntu 16.04 if program run without sudo

Question: gtk_init caused crash on ubuntu 16.04 if run program without sudo. If run with sudo, then have not problem. On other ubuntu versions also have not problem with and without sudo.
Minimally reproducible example:
#include <gtk/gtk.h>

int main(int argc, char* argv[])
{
    gtk_init (&argc, &argv);

    for (int i = 0; i < 10; ++i)
    {
        printf("%d\n", i);
        usleep(1000 * 1000);
    }
    return 0;
}

Stacktrace:
Thread 2 "dconf worker" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0xb6567b40 (LWP 6735)]
0xb71bbfd0 in g_source_set_ready_time () from /lib/i386-linux-gnu/libglib-2.0.so.0
(gdb) bt
#0  0xb71bbfd0 in g_source_set_ready_time () from /lib/i386-linux-gnu/libglib-2.0.so.0
#1  0xb73e8bf4 in g_task_get_type () from /usr/lib/i386-linux-gnu/libgio-2.0.so.0
#2  0xb744b6a0 in ?? () from /usr/lib/i386-linux-gnu/libgio-2.0.so.0
#3  0xb743eb00 in ?? () from /usr/lib/i386-linux-gnu/libgio-2.0.so.0
#4  0xb73bd0e9 in g_initable_init () from /usr/lib/i386-linux-gnu/libgio-2.0.so.0
#5  0xb743f230 in g_bus_get_sync () from /usr/lib/i386-linux-gnu/libgio-2.0.so.0
#6  0xb668c314 in ?? () from /usr/lib/i386-linux-gnu/gio/modules/libdconfsettings.so
#7  0xb668c423 in ?? () from /usr/lib/i386-linux-gnu/gio/modules/libdconfsettings.so
#8  0x0807e22a in g_main_context_dispatch ()
#9  0x0807e638 in g_main_context_iterate.isra ()
#10 0x0807e700 in g_main_context_iteration ()
#11 0xb668c58b in ?? () from /usr/lib/i386-linux-gnu/gio/modules/libdconfsettings.so
#12 0x0809eabd in g_thread_proxy ()
#13 0xb7aaf295 in start_thread (arg=0xb6567b40) at pthread_create.c:333
#14 0xb79d10ae in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:114

I tried to compare strace output with sudo and without - without sudo is being created problem thread dconf worker, but if run with sudo it thread is not being created and programm work correctly
What can be done to fix this problem?

UPD: Stacktrace with `libglib2.0-0-dbg
Thread 2 "dconf worker" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0xb6567b40 (LWP 3574)]
0xb71bbfd0 in g_source_set_ready_time (source=0xb5c09938, ready_time=-1)
    at /build/glib2.0-2aRhhS/glib2.0-2.48.2/./glib/gmain.c:1786
1786    /build/glib2.0-2aRhhS/glib2.0-2.48.2/./glib/gmain.c: No such file or directory.
(gdb) bt
#0  0xb71bbfd0 in g_source_set_ready_time (source=0xb5c09938, ready_time=-1)
    at /build/glib2.0-2aRhhS/glib2.0-2.48.2/./glib/gmain.c:1786
#1  0xb73e8bf4 in g_task_get_type () at /build/glib2.0-2aRhhS/glib2.0-2.48.2/./gio/gtask.c:1907
#2  0xb73e8bf4 in g_task_get_type () at /build/glib2.0-2aRhhS/glib2.0-2.48.2/./gio/gtask.c:590
#3  0xb744b6a0 in _g_dbus_worker_new () at /build/glib2.0-2aRhhS/glib2.0-2.48.2/./gio/gdbusprivate.c:227
#4  0xb744b6a0 in _g_dbus_worker_new () at /build/glib2.0-2aRhhS/glib2.0-2.48.2/./gio/gdbusprivate.c:267
#5  0xb744b6a0 in _g_dbus_worker_new (stream=0xb5c016c8, capabilities=G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING, initially_frozen=0, message_received_callback=0xb7438400 <on_worker_message_received>, message_about_to_be_sent_callback=0xb7435eb0 <on_worker_message_about_to_be_sent>, disconnected_callback=0xb74359c0 <on_worker_closed>, user_data=0xb5c04818)
    at /build/glib2.0-2aRhhS/glib2.0-2.48.2/./gio/gdbusprivate.c:1649
#6  0xb743eb00 in initable_init (initable=0xb5c04818, cancellable=0x0, error=0xb6567068)
    at /build/glib2.0-2aRhhS/glib2.0-2.48.2/./gio/gdbusconnection.c:2573
#7  0xb73bd0e9 in g_initable_init (initable=0xb5c04818, cancellable=0x0, error=0xb6567068)
    at /build/glib2.0-2aRhhS/glib2.0-2.48.2/./gio/ginitable.c:112
#8  0xb743f230 in g_bus_get_sync (bus_type=G_BUS_TYPE_SESSION, cancellable=0x0, error=0xb6567068)
    at /build/glib2.0-2aRhhS/glib2.0-2.48.2/./gio/gdbusconnection.c:7254
#9  0xb668c314 in  () at /usr/lib/i386-linux-gnu/gio/modules/libdconfsettings.so
#10 0xb668c423 in  () at /usr/lib/i386-linux-gnu/gio/modules/libdconfsettings.so
#11 0x0807e22a in g_main_context_dispatch ()
#12 0x0807e638 in g_main_context_iterate.isra ()
#13 0x0807e700 in g_main_context_iteration ()
#14 0xb668c58b in  () at /usr/lib/i386-linux-gnu/gio/modules/libdconfsettings.so
#15 0x0809eabd in g_thread_proxy ()
#16 0xb7aaf295 in start_thread (arg=0xb6567b40) at pthread_create.c:333
#17 0xb79d10ae in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:114

Comment: Unfortunately, in google I did not find anything suitable for me. The forum found a link to the ubuntu, but this was not my case. Thanks for the advice, I'll try to ask also there
Comment: With [google "thread dconf worker"](https://www.google.com/search?q=thread+dconf+worker), I found this as first hit: [ubuntu forums: Thread: applications crash on terminal](https://ubuntuforums.org/showthread.php?t=2185226). It might be worth a look as well as other google hits. (Asking in ubuntu forum would've been my second hint.) ;-)
Comment: Hi! Could you install the libglib2.0-0-dbg package and take the stacktrace again? That could be really helpful
Comment: Added stacktrace with libglib2.0-0-dbg
Comment: What happens if you run your program with the two environment variables `MALLOC_CHECK_=2` and `G_SLICE=always-malloc` together? Check if you get any warning message in the terminal and if the stacktrace is different
Comment: I tried. There are no messages in terminal, stacktrace is no different
Comment: As a last try, add `g_type_ensure (G_TYPE_DBUS_CONNECTION);` `g_type_ensure (G_TYPE_TASK);` `g_type_ensure (G_TYPE_MEMORY_INPUT_STREAM);` before `gtk_init();`. Probably only the first is needed. See here: https://gitlab.gnome.org/GNOME/glib/issues/541
Comment: `error: 'g_type_ensure' was not declared in this scope`, `error: 'G_TYPE_TASK' was not declared in this scope`.
What should i include?
Comment: I include `#include ` but still get errors
Comment: Including `` should suffice. At least, works here
Comment: Headers in my toolchain from version 2.26, `g_type_ensure` appeared in 2.34
Comment: With `unset GTK2_MODULES unset GTK_MODULES unset GTK_IM_MODULE` before run program, program was not crashed. But I do not fully understand why
Answer: Unset GTK2_MODULES, GTK_MODULES and GTK_IM_MODULE fixed this problem, but i don't understend why it work
#include <gtk/gtk.h>

int main(int argc, char* argv[])
{
    unsetenv("GTK2_MODULES");
    unsetenv("GTK_MODULES");
    unsetenv("GTK_IM_MODULE");

    gtk_init (&argc, &argv);

    for (int i = 0; i < 10; ++i)
    {
        printf("%d\n", i);
        usleep(1000 * 1000);
    }
    return 0;
}


Determination of $f(x)$

Question: A continuous function $f$ satisfies $f(x+f(x))=f(x)$ for all $x\in[0,1]$. prove that $f(x)$ is constant.
$f(f(0))=f(0)$. I am unable to proceed further.
Comment: Are we to assume that $x+f(x)\in [0,1]$ $\forall x$?
Comment: @GhD   If $f$ is defined on all $\mathbb R$ but the functional equation only holds for $x\in [0,1]$ then $f$ does not need to be a constant.  Suppose $f(x)=1$ on $[-\infty,2]$ but $f(x)=3-x$ for $x>2$
Comment: @lulu This is not my question.
Comment: $f(x)=0$, i think.
Comment: @kingtut how does it give the result if f(x) is polynomial
Comment: I agree with John
Comment: @JohnLou $f$ can be any constant function!
Comment: @lulu No, we are not
Comment: @GHD Here's my issue with $f$ being any constant function. If that is the case, then $x+f(x)$ may not be in the domain of $f(x)$ when $x$ is and vice versa.
Comment: @GhD  Ok, then what does $f(x+f(x))$ mean?
Comment: @john lou domain of f(x) is R(all real)  it satisfies this functional equation when x is in[0,1]
Comment: @lulu It means value of $f$ on $x+f(x)$!!
Comment: @GhD, ah true.  In any case, I see that your posted counterexample is effectively the same as mine.  I think the problem is meant to require that everything stays in $[0,1]$.
Comment: @SiddharthaRaja  As you can see, you need to clarify the domain of your function and the region in which the functional equation is to hold.  Look at the counterexamples you have been given.  To exclude those you need to clarify your conditions.
Comment: @lulu yes. or perhaps in $\mathbb R_+$
Answer: Put $f(x)=0$ when $x\in\mathbb R_+\cup\{0\}$ and put $f(x)=x$ when $x\in\mathbb R_-$. This is not constant and satisfy youR question.
Comment: @TheSimpliFire  The problem is very poorly worded.  The OP insists that the functional equation is only meant to hold for $x\in [0,1]$ and the function here does indeed satisfy the functional equation there.
Comment: @TheSimpliFire: but if the functional equation does not hold outside of the given interval for $x$, then your comment does not apply...

Determination of $f(x)$


Postgres serial value incrementing by 2

Question: I have some tables in my postgres database, and a few of them inherit from each other.
For example:
CREATE TABLE parent_table(parent_table_id SERIAL PRIMARY KEY,
       my_col1 VARCHAR(16) NOT NULL,
       my_timestamp TIMESTAMP WITH TIME ZONE NOT NULL);
CREATE TABLE child_table() INHERITS (parent_table);
CREATE TABLE step_child_table() INHERITS (parent_table);

I have a trigger that will let me perform an insert on parent_table, and then figure out whether or not the data should really go into child or step_child table.
for example:
CREATE OR REPLACE FUNCTION my_parent_trigger() RETURNS TRIGGER AS $$
BEGIN
  IF (NEW.my_col1 > 100) THEN
      INSERT INTO child_table(my_col1, my_timestamp) VALUES (NEW.my_col1, NEW.my_timestamp);
  ELSE
      INSERT INTO step_child_table(my_col1, my_timestamp) VALUES (NEW.my_col1, NEW.my_timestamp);
  END IF;
  RETURN NULL;
END;
$$
CREATE TRIGGER my_trigger BEFORE INSERT ON parent_table FOR EACH ROW EXECUTE PROCEDURE my_parent_trigger();

The problem is that my indexes are incrementing by 2.  If I insert some data, and I do a select on parent_table, I see that my indexes start at 2, and go to 4, 6, 8, 10,...  If I do a select on the child_table, I will see my indexes (say 2, 8, and 10), and the rest will be in the other table.
Why is this?  Is there a way I can stop it?  The trigger is set up BEFORE the insert, so I dont see why the serial would get incremented twice.
Does it matter?
Thanks in advance.
Answer: Even if you get this code to only increment the sequence by one, you can't in general count on there being no gaps in a column initialized from a sequence: begin; insert into foo (...); abort will leave any sequences incremented even though the transaction was aborted.
A. Elein Mustain shows how to create a gapless sequence.
Answer: When you insert into the child table, you need to include the parent_table_id column, I think.
Right now, the sequence is stepped forward once for the parent insert, and the value from that is passed to your function in NEW. You then throw that away, and ask the system to generate a new one when you insert into the child table(s).
So try to just include parent_table_id in the list of columns, and insert the value of NEW.parent_table_id in it.
Comment: that seemed to solve my problem.  My inserts now look like "INSERT INTO child_table(parent_table_id, my_col1, my_timestamp) VALUES (NEW.my_parent_id, NEW.my_col1, NEW.my_timestamp);  It solved my problem, but is this a legal move?  I'm not screwing with any locks or anything by manipulating a serial value like this am i?
Comment: It is all right because child tables use the same sequence as parent table.
Comment: No, that is absolutely a legal move. If anything, it's "more legal" than what you originally did, because having defaults firing on the childs can lead do.. Eh. Interesting things. If not done right :-)

Postgres serial value incrementing by 2


How to keep everything in the correct position after having hidden widget shown?

Question: I am making a small music player using PyQt6.
I want to have the QListWidget hidden before I click on any of the four genre buttons and shown up after the click.
You may check the below pictures.
(before):

(what I expected to see after the button is clicked):

After I click on the smile (happy) button, the list appears but not in the right way. My tool buttons are compressed.
(what I see now):

Here is my code.
from PyQt6.QtWidgets import *
from PyQt6.QtGui import *
from PyQt6.QtCore import*
class atmoUI(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    def initUI(self):
        super().__init__()
        layout=QVBoxLayout(self)
        atmo_layout=QGridLayout(self)
        self.aggressive=QToolButton(self)
        self.aggressive.setFixedSize(100,100)
        self.aggressive.setIcon(QIcon('./img/aggressive.png'))
        self.aggressive.setIconSize(QSize(100,100))
        self.aggressive.setToolTip('aggressive')
        self.happy=QToolButton(self)
        self.happy.setFixedSize(100,100)
        self.happy.setIcon(QIcon('./img/happy.png'))
        self.happy.setIconSize(QSize(100,100))
        self.happy.setToolTip('happy')
        self.romantic=QToolButton(self)
        self.romantic.setFixedSize(100,100)
        self.romantic.setIcon(QIcon('./img/romantic.png'))
        self.romantic.setIconSize(QSize(100,100))
        self.romantic.setToolTip('romantic')
        self.sad=QToolButton(self)
        self.sad.setFixedSize(100,100)
        self.sad.setIcon(QIcon('./img/sad.png'))
        self.sad.setIconSize(QSize(100,100))
        self.sad.setToolTip('sad')

        atmo_layout.addWidget(self.aggressive,0,0)
        atmo_layout.addWidget(self.happy,0,1)
        atmo_layout.addWidget(self.romantic,1,0)
        atmo_layout.addWidget(self.sad,1,1)

        self.play=QPushButton(self)
        self.pause=QPushButton(self)
        self.play.setText('play')
        self.pause.setIcon(QIcon('./img/pause.png'))

        self.songlist=QListWidget(self)

        self.home=QPushButton(self)
        self.home.setText("home")
        self.home.setIcon(QIcon('./img/home.png'))
        layout.addLayout(atmo_layout)
        layout.addWidget(self.songlist)
        layout.addWidget(self.play)
        layout.addWidget(self.pause)
        layout.addWidget(self.home)
        self.play.setVisible(False)
        self.pause.setVisible(False)
        self.songlist.setVisible(False)
        self.setLayout(layout)

I am new to PyQt and I searched for a while but still couldn't find a solution. Does anyone know how to fix this?
Comment: Note (unlikely related to the issue): the argument on a layout constructor automatically sets that layout on the given parent, so: 1. atmo_layout should have no arguments: `atmo_layout=QGridLayout()`; 2. since `layout` has been created with the `self` parent, there's no need to call `self.setLayout(layout)`. Also, please add spaces around the equal sign and leave one empty line between functions and classes, as they make your code much more readable.
Answer: You have a lot of messy and redundant code so I will avoid analyzing it but will only point out a possible implementation.
In this case a QGridLayout can be used without the need for the QVBoxLayout.
from PyQt6.QtWidgets import (
    QApplication,
    QGridLayout,
    QListWidget,
    QPushButton,
    QToolButton,
    QWidget,
)
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import QSize

class Widget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.aggressive_button = self.create_button(
            QIcon("./img/aggressive.png"), QSize(100, 100), "aggressive"
        )
        self.happy_button = self.create_button(
            QIcon("./img/happy.png"), QSize(100, 100), "happy"
        )
        self.romantic_button = self.create_button(
            QIcon("./img/romantic.png"), QSize(100, 100), "romantic"
        )
        self.sad_button = self.create_button(
            QIcon("./img/sad.png"), QSize(100, 100), "sad"
        )
        self.songlist_widget = QListWidget()
        self.play_button = QPushButton(text="play")
        self.pause_button = QPushButton(icon=QIcon("./img/pause.png"))
        self.home_button = QPushButton(text="home", icon=QIcon("./img/home.png"))

        lay = QGridLayout(self)
        lay.addWidget(self.aggressive_button, 0, 0)
        lay.addWidget(self.happy_button, 0, 1)
        lay.addWidget(self.romantic_button, 1, 0)
        lay.addWidget(self.sad_button, 1, 1)
        lay.addWidget(self.songlist_widget, 2, 0, 1, 2)
        lay.addWidget(self.play_button, 3, 0, 1, 2)
        lay.addWidget(self.pause_button, 4, 0, 1, 2)
        lay.addWidget(self.home_button, 5, 0, 1, 2)
        lay.setRowStretch(6, -1)

        self.play_button.hide()
        self.pause_button.hide()
        self.songlist_widget.hide()

        self.resize(self.width(), 400)
        self.setFixedWidth(self.sizeHint().width())

        self.happy_button.clicked.connect(self.handle_happy_clicked)

    def create_button(self, icon, size, tooltip):
        button = QToolButton(icon=icon, iconSize=size)
        button.setFixedSize(size)
        button.setToolTip(tooltip)
        return button

    def handle_happy_clicked(self):
        self.songlist_widget.show()

if __name__ == "__main__":
    app = QApplication([])
    window = Widget()
    window.show()
    app.exec()


How to group array by user_id in Laravel 8

Question: I create the CRUD App. In this App, the user can add a contact, and include their birthday in that contact.
I have two tables in PHP MySQL: students and users. When their contact at the students' table has a birthday, the user will receive an email.
To test the email work, I'm using MailHog. It's was work.
I test that there are two users with a birthday in that contact.
One user has a notification email. Another one has two notification emails because that contact has two data that are two birthdays.
The problem is, that I want to send one notification to every user. So if one user has many contacts on that birthday, it will give the user one email notification, instead of many emails.
this is the notification in MailHog:

user john has two notifications, instead of one.
this is my code:
 public function handle()
{

    info('mail first');
    sleep(1);
    info('mail second');
    $student = Student::whereMonth('birth', date('m-d'))
                        ->whereDay('birth', date('d') )

                        ->get();

    foreach ($student as $mystudent) {

    $user = User::find($mystudent->user_id);

    Mail::to($user)->send(new WelcomeMail($mystudent));

    }

    // dd($userid);

    echo "check email";

}

this code in class WelcomeMail
public function __construct($students)
{
    $this->data = $students;
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{

    return $this->view('emails.welcome')->with('students', $this->data);
}

this is in view:
    {{ $students}}

I do this modiv in mail command:
 $userid = [];
    foreach ($student as $mystudent) {

    $user = User::find($mystudent->user_id);
    array_push($userid, $user);

    Mail::to($user)->send(new WelcomeMail($mystudent));

    }

At this point, it's still given me the result that the user has many emails for each contact.
hopefully, you help me train logic to solve this one.
+
this the database looks like:
Answer: You can start your query from the user, so you're sure that every user is present only once.
I'm assuming you have students() relation present on the User::class model
public function handle()
{
    $users = User::wherehas('students', function($studentQuery) {
        $studentQuery
            ->whereMonth('birth', date('m-d'))
            ->whereDay('birth', date('d'));
    })
        ->with('students', function($studentQuery) {
            $studentQuery
                ->whereMonth('birth', date('m-d'))
                ->whereDay('birth', date('d'));
        })
        ->get();

    foreach ($users as $user) {
        Mail::to($user)->send(new WelcomeMail($user->students));
    }

    echo "check email";
}

Comment: I just apply that code, it has given me just two emails, for one user and another, but in the user that has two contacts, just give first contact, instead of all contact Sir. And in the email, not contain, the contact that birthday, it has given the email with the first created
Comment: I just edited it to view the database that in PHP MySQL, in database api4, there were many tables including the students and users dude.
Comment: I did, it got, the email that one user has one notif, but the contact that does not has birthday included in that email dude
Comment: That's cool, you answer just like what my senior suggested. I still struggle with logic, like how to use looping properly and where I will do looping. Maybe you can recommend my resource so that I can learn logic, Sir.
Comment: that's something, thanks for your advice, I need more advice from others who experts in programming, tank's dude
Answer: $student = Student::whereMonth('birth', date('m-d'))
    ->whereDay('birth', date('d'))
    ->groupBy('user_id')
    ->get();

Comment: I was doing that, by following this documentation
https://laravel.com/docs/8.x/queries#grouping

it's using:

->groupBy

it's got an error dude


Is it legal in C++ to specialize std::minus for user-defined types?

Question: Does the standard library permit users to specialize function objects like std::plus and std::minus for custom types?
If the answer to my first question is yes, are users allowed to change the declaration of the call operator? For example, since C++14 std::minus::operator() is declared as follows:
constexpr T operator()( const T& lhs, const T& rhs ) const;

Would it be legal to change this operator such that it is no longer constexpr or returns double instead of T?
namespace std
{
    template <>
    struct minus<MyArrayType>
    {
        double operator ()(const MyArrayType& x, const MyArrayType& y) const
        {
            return l2_norm(x - y);
        }
    };
}   // std

Comment: Shouldn't you override `operator -` instead?
Comment: Then you should use a different functor instead of std::minus. Make a mentalmushroom::l2_norm_minus instead
Comment: @user253751 Suppose, the operator - for this type is already defined, but I'd like to alter it's behavior such that it could be used differently.
Comment: @user253751 Well, makes sense, but imagine for my particular needs it would be more convenient to specialize std::minus. Moreover, I have a general curiousity :)
Comment: More interesting question is: WHY? Which algorithm uses this templates? Is this algorithm/template yours?
Answer: The rules for extending namespace std says:

It is allowed to add template specializations for any standard library class template to the namespace std only if the declaration depends on at least one program-defined type and the specialization satisfies all requirements for the original template, except where such specializations are prohibited.

(emphasis mine)
So in your case, adding a specialization for the program-defined type MyArrayType would work.
However, the return type of the member operator() must be MyArrayType, not double. Also, the member operator() must be constexpr.
Violating either of these means the specialization doesn't satisfy the requirements of the primary template.
Comment: Thanks, how do you understand the phrase "requirements for the original template"? Where are they described?
Comment: I'm not sure where the term "requirements for the original template" are written exactly. However, you can see that the requirements on the original(primary) template are that the return type and the parameter types must match. Also, the primary template must be callable in a `constexpr` context (from C++14). Another example would be that the member `operator()` must be const-qualified.
Comment: "Meaning" might also be part of "requirements" [arithmetic.operations#plus](https://eel.is/c++draft/arithmetic.operations#plus). But some other templates have clearly requirements/pre-conditions which seems not be the case here...
Comment: Interesting question : https://stackoverflow.com/questions/52760580/will-specialization-of-function-templates-in-std-for-program-defined-types-no-lo


NLog file target writes only one record

Question: Whenever my application runs on the Test, Preprod or Prod server (Windows 2012 R2) on the infrastructure of our hosting provider, all file targets write exactly one log entry, and then stop working without any indication of the reason. If I delete the log file (or if it gets archived, for example on the next day), a new log file is written, but again with only one log record.
The same problem is described on the NLog forums here, but without a workaround or explanation: http://nlog-forum.1685105.n2.nabble.com/Only-one-entry-written-to-log-file-td7399596.html
I tried the following things:

Enabled the internal logging of NLog. Same problem here, the log file with the internal logging contained exactly one log item. Internal logging can only be set up with a file target, so there was no way to listen to the internal logging on another target (like DebugView).
Listened with Sysinternals DebugView for internal error messages of NLog, but nothing.
Checked the log files read-only attribute, but it was set to false.
Switched all targets to async. No effect.

Any other ideas? I cannot run Visual Studio on those servers, so there's no way I can debug it with the NLog source.
Would be a pity to switch to log4net because of a silly bug.
EDIT: I have to add that the other targets (like DebugView or ADO.NET) work fine, it's really a problem of the file target. And because the internal logging is restricted to a file target, I cannot see how to find the cause of the problem
Answer: Seems to be a permissions problem. Once I granted the users group IIS_IUSRS write rights to the logs folder, everything was working as expected.
I'm just wondering, why could it write the log file with the one entry?
I never thought about a permissions problem because I saw that IIS could write the log file.
EDIT: As suggested in the comments, I switched on the ${identity} log, and received the following values:
first 3 lines:
notauth::

all following lines:
auth:ApplicationCookie:{LOGIN_OF_CURRENT_USER}

`{LOGIN_OF_CURRENT_USER} is the e-mail address of the user which is currently signed in.
EDIT 2: Here's the icacls result:
D:\IIS_Server\wwwroot\tgw\logs NT AUTHORITY\IUSR:(OI)(CI)(F)
                               BUILTIN\IIS_IUSRS:(OI)(CI)(F)
                               NT AUTHORITY\IUSR:(I)(OI)(CI)(RX)
                               BUILTIN\IIS_IUSRS:(I)(OI)(CI)(RX)
                               NT SERVICE\WMSVC:(I)(OI)(CI)(F)
                               NT AUTHORITY\SYSTEM:(I)(OI)(CI)(F)
                               BUILTIN\Administrators:(I)(OI)(CI)(F)
                               BUILTIN\Users:(I)(CI)(AD)
                               BUILTIN\Users:(I)(CI)(WD)
                               BUILTIN\Users:(I)(OI)(CI)(RX)

Please note that this is after I explicitly granted IIS_IUSRS write rights to the folder.
Comment: That's interesting - it seems that the first log is written using a different account then the subsequent ones. Could you add to the log information about the current thread identity?
Comment: You mean `${identity}` ? Going to add that on the next server update and see what's its output.
Comment: yes, `${identity}` should reveal what's going on :) Please post the results afterwards.
Comment: Partiallly yes :) But I still don't understand why previously only one message was logged (not three). I need to check which permissions are checked when the thread is impersonated (when user is signed in, because that was probably the reason why logs were not created). Could you paste the current log folder privileges: `icacls `? - strip any info you consider confidential

NLog file target writes only one record