Why can't I move files from my Ubuntu desktop to other folders?

Question: When I try to move a file on my desktop to a folder (opened using Files), the file will not go into it. If I move it to a folder using the mouse pointer, it moves back to the desktop when I release the mouse button. If I right-click on the file, there is no "Move to" option on the menu. This also applies to external drives (e.g. expansion drive, flash drive stick). I have had this problem for a number of months now.
Comment: This would usually point to a permissions issue. Are you sure the account you're signed in with can write to the locations you're accessing?
Comment: Please indicate which version of Ubuntu you're using, because I might be able to give you a solution.
Comment: @Allan — For some reason, I didn't get a notification of your reply. I'll create an answer soon showing how I fixed it.
Comment: Matigo I am the only user of my PC - there is only one account. I can move files from folder to folder in Files, just not from the desktop. In fact, I can move files from Desktop to other files if I open the Desktop file inside of Files (which is a work-around); but it does not work if I try to move files straight from the Desktop on screen to another folder.
Comment: Paddy Landau - Thanks. The version is 20.04.1 LTS
Answer: The reason you cannot drag files is due to limitations in the support of desktop icons. Since a few Ubuntu versions, icons on the desktop are not anymore provided by nautilus file manager (aka "Files"). Instead, a Gnome Shell extension "Desktop Icons" has been created for that. This extension is rather new and still quite limited in its capabilities, in particular with respect to the interaction with the file manager.
This has happened because Gnome Shell does not support desktop icons. They consider the desktop not to be the appropriate place for folders and launchers. Most of the time, it is covered by your applications. Instead, users are encouraged to place frequently used launchers on the Dash, and launch applications from the Application overview. For files, users are encouraged to work from Files, or from within the applications, rather than placing a range of files in a single Desktop folder.
Consequently, at some point, Gnome developers removed the code to provide desktop icons from the file manager. Therefore, Ubuntu used an older version of nautilus file manager in Ubuntu 18.04, in order to continue providing desktop icons. Nowadays, they ship with an up-to-date version of nautilus, and support desktop icons through the Gnome Shell extension. Hopefully, with time, the extension will improve in replacing the former functionality of nautilus with respect to icons on the desktop.
Comment: The real why is, Gnome devs have been on a decades-long crusade against features. The more of them they can remove, the happier they are.
Comment: @hobbs, i think the Gnome devs end goal is to have just one feature: a single button that does nothing.
Comment: To just expand on the "why", I have recently read somewhere that Gnome developers are visioning their desktop to be used on a tablet; or at least to be 100% tablet-compatible out of the box. And on tablets, the desktop area is normally occupied by the thing we call "apps overview": the grid of app icons. They also have done away with right-clicking context menus as much as they could (because on touchscreens that's also problematic). That's why now there is that ultra-weird application-context-dependent extra dropdown thingy in the left side of the top panel.
Comment: Creating a good UI and dealing with all the "bug reports" of why it does/does not do certain thing is very, very annoying. That's even assuming you have a "good" UI, and with UI coming from multiple significantly different platforms (Windows, Mac, Mobile), what is "good" is usually foreign in another platform, and you'll have constant fights about which one is right. Gnome devs are sort of playing the nanny that says no to everyone...
Comment: Wow, that's silly. The desktop's been used, _on desktops_, a certain way for literally decades. The "just because it's been done that way before, means it _must not_ be done that way ever again" people should go away!
Answer: @vanadium has provided an exhaustive explanation of why we can no longer drag and drop to and from the Ubuntu desktop. (+1) I would only like to add that if you open the Desktop folder in Nautilus you can drag and drop anything to and from that and any other folder that is open in a separate Nautilus window. It's the best workaround that I have found so far.
Comment: Thanks, I discovered that work-around. It's just a lot easier if it can be done from the desktop on screen, especially when I have multiple other folders open.
Answer: The default desktop icons manager on Ubuntu 20.04 is a Gnome extension called Desktop Icons.
Desktop Icons is a pretty bad implementation, because it lacks the most important features.
The good news is that a revised version, Desktop Icons NG (DING), written by the same author, fixes this.
The bad news is that Desktop Icons is installed as part of Ubuntu, so you can't uninstall it! Using it at the same time as Desktop Icons NG (DING) causes problems.
The good news (!) is that there is a workaround.

First, some links

I reported a bug for this problem. If you agree with the bug report, please go to it; log in (or register) if you haven't already; and add your vote by selecting the green writing (at the top left of the bug report under the title).

The source for my solution comes from an answer to a related question.

The workaround
Disable Desktop Icons
As I already mentioned, you can't uninstall Desktop Icons. But, you can disable it.

Open a terminal (press Ctrl+T). Enter the following three commands, in order (you can use your mouse to copy-and-paste. Ctrl+C doesn't work as you might expect in the terminal). The second command will ask for your password; when you type the password, it will be invisible, so don't worry that nothing shows until you press Enter.

cd /usr/share/gnome-shell/extensions/desktop-icons@csoriano/
sudo mv extension.js extension.js.backup
sudo touch extension.js

Close the terminal (an easy way is to press Ctrl+D).

Before the next step, you need to restart your computer. (Really.)

Install Desktop Icons NG (DING)

Go to the Gnome extensions page.
You might be prompted to install the "Gnome shell extensions" (at the top of the page). If so, follow the instructions and install it.
Now go to the Desktop Icons NG (DING) page.
The black button on the right-hand side reads "Off". Select the button to turn it "On", and follow instructions if any.

Set up Desktop Icons NG (DING)

Right-click on your Desktop and select Settings. Change the settings if you want to.
To drag an icon from the desktop to an open app (e.g. an open Nautilus or Chrome window), even if it's on a different workspace:

Start dragging the icon.
Without letting go of the mouse, press Super+Tab. (On most keyboards, the Super key is the "Windows" key near the bottom left corner.)
Without letting go of the Super key, press Tab repeatedly until you have selected your required app.
Let go of the Super key.
Continue to drag your icon to where you want it.

Some notes

When you visit your personal Gnome extensions page, Desktop Icons will show "Error". Ignore that.

You might be prompted to update Desktop Icons NG (DING); you can try, but it won't succeed (due to version incompatibility, I believe), so ignore that as well.


Form action link goes to home page

Question: I'm trying to make a submit button link to one of my existing pages.
After clicking the button, my browser goes straight to localhost:8080/c2c/ instead of my target localhost:8080/c2c/?page_id=20
    <form action='http://localhost:8080/c2c/?page_id=20'>
        <input type="submit" value="New Buy Order" id="buySubmit"></input>
    </form>

My guess is because of my local server it isn't going to go to the link correctly. Just not sure.
Answer: http://localhost:8080/c2c/ IS the target of your form, so it's doing exactly what you're telling it to. You need to create a file inside the c2c directory, name it index.php and put the following code in index.php to see the page_id
<?php
echo (int) $_GET['page_id'];

Edit: of course this code is overly simplified, but it will show you what's happening...

Edit 2: revised code.
This is really how you should be doing it. Using method="get" in your form will show the query parameters in the URL string, as in your original form.
form.html
<form action="http://localhost:8080/c2c/index.php" method="get">
    <input type="hidden" name="page_id" value="20">
    <input type="submit" value="New Buy Order" id="buySubmit"></input>
</form>

index.php
<?php echo (int) $_GET['page_id']; ?>

Comment: Added the echo statement above. Same result. EDIT: It gives an error of undefined page index.

Form action link goes to home page


Do you know any good source for human-robot interactions?

Question: "In most cases, user experience design (UX or UXD or UED) fully encompasses traditional human-computer interaction (HCI) design, and extends it by addressing all aspects of a product or service as perceived by users."
In near future, I think that this area will be fruitful, especially for Robot assisted therapy related ones?
Is there any resource that is related to human-robot interaction for UX designers?
Answer: There are a bunch of references available on the internet.

Human robot interactions from the Interaction design foundation : To quote a small part of the article

Werry & Dautenhahn (2007) showed that an interactive, mobile robot
  engages children with autism better than a non-robotic conventional
  toy. A physician or physiotherapist may use robotic technology in
  order to find out about the nature of a particular medical condition
  or impairment, e.g. to find out about the nature of motor impairment
  after stroke, and may use an assessment robot to be tested with both
  healthy people and stroke patients. Similarly, a psychologist may
  study the nature of autism by using robotic artefacts, comparing,e.g.
  how children respond to social cues, speech or tactile interaction.
  Such artifacts would be tools in the research on the nature of the
  disorder or disability, rather than an assistive tool built to assist
  the patients — which means it would also have to take into
  consideration the patient's individual differences, likes and dislikes
  and preferences in the context of using the tool.

How User experience in  human-robot interaction change over time : This is another interesting article which talks about how our experience changes with more interaction with robots over time. To quote the abstract

This paper describes a User Experience (UX) study on industrial robots
  in the context of a semiconductor factory cleanroom. We accompanied
  the deployment of a new robotic arm, without a safety fence, over one
  and a half years. Within our study, we explored if there is a UX
  difference between robots which have been used for more than 10 years
  within a safety fence (type A robot) and a newly deployed robot
  without fence (type B robot). Further, we investigated if the UX
  ratings change over time. The departments of interest were the oven
  (type A robots), the etching (type B robot), and the implantation
  department (type B robot). To observe experience changes over time, a
  UX questionnaire was developed and distributed to the operators at
  three defined points in time within these departments. The first
  survey was conducted one week after the deployment of robot B (n=23),
  the second survey was deployed six months later (n=21), and the third
  survey was distributed one and a half years later (n=23). Our results
  show an increasing positive UX towards the newly deployed robots with
  progressing time, which partly aligns with the UX ratings of the
  robots in safety fences. However, this effect seems to fade after one
  year. We further found that the UX ratings for all scales for the
  established robots were stable at all three points in time

The robotics group in USC has some interesting projects on how robotics can assist in Human assistive technologies
I also recommend looking at this press post which talks about social robots and their influence on humans in an assistive aspect.To quote an excerpt from the article

Robots can also teach children with special needs how to play with one
  an- other. If a child is touching the robot inappropriately-slapping,
  say, instead of stroking-the robot may back away or emit a warning
  beep to encourage the child to change his behavior. Then, as the child
  begins to master interactive skills, the robot's behavior may become
  increasingly unpredictable, preparing the child for dealing with
  humans.
Dautenhahn has noticed that autistic children playing with Kaspar may
  also spontaneously begin interacting with their teachers. "One
  withdrawn boy who never played with other children or his teacher
  became very interested in Kaspar's eyes," she says. "He pointed to
  Kaspar's eyes, then to his own, and then, smiling, to his teacher's
  eyes. This was an invitation to share, and the boy and his teacher
  played together."
Children with physical disabilities, too, respond well to robots. In
  three schools in Austria, PlayROB gives children with cerebral palsy
  and other severe disabilities the chance to play independently.
  Controlling the robot with a joystick, buttons, their mouths or even
  just head movements, the chil- dren can direct it to build LEGO
  structures and do additional activities that let them experience the
  creative expression, spatial recognition and accomplishment that other
  children get from playing

Other articles worth exploring are given below

Experimental Design for Human-Robot Interaction with
Assistive Technology
Assistive Technologies and Children-Robot Interaction
Comment: [Georgia Tech](http://humanslab.ece.gatech.edu/humanslab/Home.html) has a lab looking at the area of research too.


Broken LED remote

Question: My sister stepped on my 44 button LED light remote and it stopped working , Is there any way I can replace the remote by just ordering a new one or will i have to manually repair it. If so, how should i go about doing that.
Comment: Welcome to DIY. It would certainly help to know what kind of remote you have.
Comment: Manufacturer? Model #? Pictures?
Comment: It was this model specifically https://www.amazon.com/Upgraded-Strip-Lights-32-8ft-Adhesive/dp/B07QDBW84F/ref=sr_1_3_sspa?crid=26VTNWBI1MPO1&keywords=led+strip+lights+60+feet&qid=1575010193&sprefix=led+strip+lights+60+%2Caps%2C143&sr=8-3-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFWNjc1VjE5N1dZRlgmZW5jcnlwdGVkSWQ9QTEwMzUyNjlUQldDSklCVUZQRDEmZW5jcnlwdGVkQWRJZD1BMDM3MzUyOFVKMzFOM0FONjRTWSZ3aWRnZXROYW1lPXNwX2F0ZiZhY3Rpb249Y2xpY2tSZWRpcmVjdCZkb05vdExvZ0NsaWNrPXRydWU=
Comment: All we could say would be "maybe", as the remotes may be universal, or may be configured for that specific LED strip.
Comment: if the remote looks the same it probably works the same.
Answer: Your product is a package that bundles several products also sold separately:

LED strip
power supply, and
controller/remote combo.

In particular, LED controllers are sold with their matching remote.   These are so cheap you'd be better off just buying this and attaching it.
Comment: So to clarify, I could buy just another power supply and remote since they come connected to each other?
Comment: @esher **controller** and remote. Not the thing that goes into AC power.  That box that sits between the power supply and the LEDs.  It might say "RGB control box".
Answer: I found a "Multi-function LED Remote Control" at Pier 1 and several led light remote control apps on the Google Play store, some for free.
I've used remote control apps on my phone to test & operate other devices I don't have remotes for.
Answer: You might browse the apps available for download to your smartphone.
Once, in a rental house, the DVD and television had a wrong brand remote which was almost totally incompatible with the devices.  Something like "power on" and "volume" worked, but nothing else did.
I was able to salvage the weekend by searching the Play app store and searching for "Visio control video" (there are dozens!) and try a few of them.  As I recall it took three or four tries before finding one which worked "well enough".

Broken LED remote


PHP REDIS/MYSQL, issue with concurrent connections

Question: I have worked on NodeJs and Redis before. Since NodeJs is a web server I could maintain a single connection to Redis and all the http requests use same Redis client to connect to Redis.
         But in PHP each page upon HTTP request creates a new connection to Redis Server and this is slowing down the performance. How do they maintain the connection state in PHP? It must be same issue with PHP-Mysql too so I guess there are solutions out there?
Answer: The way php works, it that it is a program, not a server. Every time you request a page on your web server, PHP is called to run the program. Once the page is done loading, the thread is ended. PHP is not a server, so once a page is done loading, all connections associated with it are terminated. Therefor, every time a page is requested, a new connection to the database has to be made. If you are noticing a performance issue when connecting, you should try php-redis if you are not already doing so.
Comment: PHP-Redis seems to be outdated. But I will try it. Thanks.
Comment: Hi Colum. How do I install PHP Redis on windows? Any links?
Comment: https://github.com/downloads/char101/phpredis/php_redis-2.1.0-php-5.3.5-vc9-ts.dll

Download it and add it to your php.ini file, and that should do it
Answer: Let says you are using php-fpm. php-fpm has a master process and run multiple worker process according the pool configuration.
Each worker process is independent (but can use shared resource such as opcache/APUc cache ...), consume CPU and memory (memory is most important factor to tune the pool configuration max-children property).
So yes, 1 HTTP query = 1 php-fpm worker (fresh or reuse) = 1 new socket connection (or reuse persistent connection), to scale:

Redis cluster
Proxy such as HAProxy between php and redis (so you can limit maxconn)
Use local cache such as APCu to limit Redis access (complicate but the most powerful)
Check OS ulimit and opened file descriptors


How to correctly save stream of bytes to file in Java/Scala? How to fix wrongly saved stream?

Question: Story
While conducting an experiment I was saving a stream of random Bytes generated by a hardware RNG device. After the experiment was finished, I realized that the saving method was incorrect. I hope I can find the way how to fix the corrupted file so that I obtain the correct stream of random numbers back.
Example
The story of the problem can be explained in the following simple example.
Let's say I have a stream of random numbers in an input file randomInput.bin. I will simulate the stream of random numbers coming from the hardware RNG device by sending the input file to stdout via cat. I found two ways how to save this stream to a file:
A) Harmless saving method
This method gives me exactly the original stream of random Bytes.
import scala.sys.process._
import java.io.File

val res = ("cat randomInput.bin" #> new File(outputFile))!

B) Saving method leading to corruption
Unfortunately, this is the original saving method I chose.
import scala.sys.process._
import java.io.PrintWriter

val randomBits = "cat randomInput.bin".!!

val out = new PrintWriter(outputFile)
out.println(randomBits)
if (out != null) {
  out.close()
  Seq("chmod", "600", outputFile).!
}

The file saved using method B) is still binary, however, is is approximately 2x larger that the file saved by method A). Further analysis shows that the stream of random Bits is significantly less random.
Summary
I suspect that the saving method B) adds something to almost every byte, however, the understanding of this is behind my expertise in Java/Scala I/O.
I would very much appreciate if somebody explained me the low-level difference between methods A) and B). The goal is to revert the changes created by saving method B) and obtain the original stream of random Bytes.
Thank you very much in advance!
Answer: The problem is probably that println is meant for text, and this text is being encoded as Unicode, which uses multiple bytes for some or all characters, depending on which version of Unicode.
If the file is exactly 2x larger than it should be, then you've probably got a null byte every other byte, which could be easy to fix. Otherwise, it may be harder to figure out what you would need to do to recover the binary data. Viewing the corrupted file in a hex editor may help you see what happened. Either way, I think it may be easier to just generate new random data and save it correctly.
Especially if this is for an experiment, if your random data has been corrupted and then fixed, it may be harder to justify that the data is truly random compared to just generating it properly in the first place.
Comment: It is not just `println` which is meant for text, but `Writer` and its subclasses in general: "Abstract class for writing to **character** streams" https://docs.oracle.com/javase/7/docs/api/java/io/Writer.html
Comment: Unfortunately, running new experiment is "expensive" for me. I need the stream of random numbers to evaluate the experiment.
Comment: In that case, good luck recovering the data! Hopefully it's as simple as a null byte every other byte.


JMS MQ, XML tags in property header converted into entities

Question: I have an application based on Websphere and MQ, which expects in the JMS message headers a property which has an XML as value.
test="<any_value></any_value>"

This works ok on a messaging system like Sibus, but on MQ, it turns out like:
<test><any_value> </any_value></test>

and the consumer complains that is not able to find the property or more probably to parse the content.
I am not in control of the design and I know that such should be part of the body itself rather than the header. I wonder if someone else faced the same issue or there's a solution to leave the XML tags as they are.
Thanks
Comment: To clarify... if a JMS Message (text, bytes, object etc? or anytype) has a String Property set on it that is XML, when received this is modified as shown?

What versions of MQ JMS Clients are on either side, and what version is the QueueManager itself?
Comment: MQ server is v7.5, while the client used by WAS is 220.127.116.11.
Both producer and consumer are on the same cell, so they use the same connection. Both also the set the property as String.
Comment: As an update I have tried this locally and can't reproduce it; the behavior isn't as expected therefore I would suggest a formal problem report to IBM Service.
Answer: If it were possible to insert unmodified XML into the property then it would be possible to include the closing property tags and then insert arbitrary properties into the system folders.  So, without knowing how it works in the code, one must assume that the entities are properly converted as the value is placed into the message.  In other words, assume that both MQ and SIBus store the data with the XML special characters converted to entities.
If that is the case, then there are a couple of possibilities.  The most likely one being that of the two IBM products, only one properly decodes the entities as the property value is read back out.
With that in mind, the only answer I have to offer is to open a PMR and be sure to include the information that it works as expected with SIBus and fails with MQ.  If you describe just the MQ behavior in the PMR, you are likely to get back "working as designed" with a note telling you to parse the entities in your code.  But if you point out that the same function exhibits two different behaviors in two IBM products that implement the same JMS specification then you are more likely to receive an answer that reconciles the two different behaviors and some method or fix for the one that is broken.
With luck, that fix will make MQ work like SIBus and not the other way around. But anything is possible.


Node Mongodb Driver: different result on aggregate

Question: how you doing?
I have a trouble making a aggregation in my project, my aggregation result is different in Robo3T and Node.
db.getCollection('companies').aggregate([
    { '$match': { _id: { '$eq': ObjectId("5e30a4fe11e6e80d7fb544a4")} } },
    { $unwind: '$jobVacancies' },
    {
      $project: {
          jobVacancies: {
              _id: 1,
              name: 1,
              city: 1,
              openingDate: 1,
              closingDate: 1,
              createdAt: 1,
              quantity: 1,
              steps: {
                  $filter: {
                      input: '$jobVacancies.steps',
                      as: 'step',
                      cond: {
                          $and: [
                              { $eq: ['$$step.order', 0] },
                              { $ne: ['$$step.users', undefined] },
                              { $ne: ['$$step.users', null] },
                              { $ne: ['$$step.users', []] },
                          ],
                      },
                  },
              },
          },
      },
  },
  { $match: { 'jobVacancies.steps': { $ne: [] } } },
])

In Robo3T this is returning 1 object, but in Node (the same aggregation) is resulting 6 objects. Can you help me? Thank you
EDIT
Nodejs:
The first match create the ObjectId match for company in context of GraphQL based on my filter.
const companies = await this.MongoClient.db
            .collection('companies')
            .aggregate([
                {
                    $match: await this.getFilterObject(
                        filters.filter(f => !f.field.includes('$$jobVacancy') && !f.field.includes('StepOrder')),
                    ),
                },
                { $unwind: '$jobVacancies' },
                {
                    $project: {
                        jobVacancies: {
                            _id: 1,
                            name: 1,
                            city: 1,
                            openingDate: 1,
                            closingDate: 1,
                            createdAt: 1,
                            quantity: 1,
                            steps: {
                                $filter: {
                                    input: '$jobVacancies.steps',
                                    as: 'step',
                                    cond: {
                                        $and: [
                                            { $eq: ['$$step.order', order] },
                                            { $ne: ['$$step.users', undefined] },
                                            { $ne: ['$$step.users', null] },
                                            { $ne: ['$$step.users', []] },
                                        ],
                                    },
                                },
                            },
                        },
                    },
                },
                { $match: { 'jobVacancies.steps': { $ne: [] } } },
            ])
            .toArray();

EDIT 3
This is the result of console.dir (with {depth:null}) of the pipeline
[
   {
     '$match': {
       _id: {
         '$eq': ObjectID {
           _bsontype: 'ObjectID',
           id: Buffer [Uint8Array] [
              94,  48, 164, 254,  17,
             230, 232,  13, 127, 181,
              68, 164
           ]
         }
       }
     }
   },
   { '$unwind': '$jobVacancies' },
   {
     '$project': {
       jobVacancies: {
         _id: 1,
         name: 1,
         city: 1,
         openingDate: 1,
         closingDate: 1,
         createdAt: 1,
         quantity: 1,
         steps: {
           '$filter': {
             input: '$jobVacancies.steps',
             as: 'step',
             cond: {
               '$and': [
                 { '$eq': [ '$$step.order', 0 ] },
                 { '$ne': [ '$$step.users', undefined ] },
                 { '$ne': [ '$$step.users', null ] },
                 { '$ne': [ '$$step.users', [] ] }
               ]
             }
           }
         }
       }
     }
   },
   { '$match': { 'jobVacancies.steps': { '$ne': [] } } }
 ]

Comment: @Eduardo Santos I think you need to look over the pipeline step by step.At First, remove all the pipeline except $match and see the result if this matches only one document then, its Ok and then add next pipeline and so on.
Comment: Post please Nodejs code. Btw: `{ '$match': { _id: { '$eq': ObjectId("5e30a4fe11e6e80d7fb544a4")} } }` will return always 1 document
Comment: @Valijon I want to filter jobVacancies inside this document, thats why that $match
Comment: Is    this.getFilterObject(filters.filter(f => !f.field.includes('$$jobVacancy') && !f.field.includes('StepOrder')))  returns { _id: { '$eq': ObjectId("5e30a4fe11e6e80d7fb544a4")} } or something else
Comment: @MohammadFaisal Yes, returns the first $match of the aggregate
Answer: I think i found the solution, the document is created with properties:
jobVacancies: {
    steps: {
        users: []
    }
}

But sometimes users array is undefined in mongodb, so I verify with
{ '$ne': [ '$$step.users', undefined ] }
I think JS undefined is different then mongodb undefined, so I initialized all steps with an empty array of users, and removed this verification and worked! –


20 years since I was in high school. How do I break this down?

Question:
$-5 = 2x + 5$

I want to "re-start" my mathematical education.  I am needing it more and more at work.  A co-worker asked me to break that down (he couldn't remember either).
Where should I start?  What books?
Thanks!
Answer: This is an equation, because it says "Left hand side = Right hand side".
Think ow an equation as a scale in perfect balance. Now you have to rearrange everything, without destroying the balance, so that the $x$ will appear at one side alone. Because then you know what $x$ is.
For example, if you take away the same amount from both sides, the scale will remain in balance. So, let us take away $5$ from both sides, and we end up with
$-10 = 2x$
Now, if the scale is in balance now, it will remain in balance when we make each side half as big, because if two things are equal, then their halves are equal as well. This leaves us with
$-5 = x$
The scale is in balance, on the left side we have a $-5$ and on the right side we have $x$. Therefore, $x$ has to be $-5$.
Now, to re-start your education: The problem above is elementary algebra, so I'd pick up with an algebra book that starts from the beginning. Something like "Math for Dummies" might be a nice idea as they are fun to read.
Comment: @cbmeeks: And a good habit is that once you think you've found the right value of $x$, you put it back into *the equation that you started with* in order to see that the equation really is satisfied. In your case, the "$2x+5$" on the right-hand side becomes $2 \cdot (-5)+5$ when you let $x=-5$, and this expression simplifies to $-5$. Thus the right-hand side agrees with the "$-5$" that you had on the left-hand side, so we have verified that our solution $x$ indeed is a solution.
Answer: Hint: In general for such one variable problems, where you need to find the value of the variable from a given single equation, you collect terms in the variable on one side of the equation and terms not containing the variable on the other side. Then divide the equation by the coefficient of the variable ($x$ in this case) to solve for it.
Answer: This is elementary algebra, there are Schaum's books on that.
Anyway, you solve for $x$ like this:
$-5 - 5 = 2x + 5 - 5$ (substract 5 from each side), this gives $-10 = 2x$. Now divide both sides by $2$ to get $-10/2 = 2x/2$ so $x = -5$.


Access Picamera2 within a surrounding class on Raspberry Pi

Question: I am working on a robot, and am in the process of connecting to the hardware through python on a raspberry pi. All of my mini test programs work, but I am having issues merging them into 1 class that contains all hardware interactions. Everything works except the Picamera2 camera. Please see class below. Running this directly through idle as the main class works no problem. Calling this class and making an object in another results in the error
Traceback (most recent call last):
  File "/home/sox/Documents/Sox/main.py", line 6, in <module>
    soxHardware = Hardware()
  File "/home/sox/Documents/Sox/utils/HardwareUtils.py", line 72, in __init__
    self.picam2 = Picamera2()
  File "/usr/lib/python3/dist-packages/picamera2/picamera2.py", line 249, in __init__
    raise RuntimeError("Camera __init__ sequence did not complete.")
RuntimeError: Camera __init__ sequence did not complete.

Class code
#NOTE: ALL FUNCTIONS CAN BE BYPASSED
#Just call the object directly
#import time
import board

import digitalio
import time

#for battery
import smbus
import struct

#for gyro
import adafruit_mpu6050

#for touch
import adafruit_mpr121

#for servoDriver
from adafruit_pca9685 import PCA9685
from adafruit_motor import servo

#for camera
from picamera2 import Picamera2

class Hardware:

     def __init__(self):
          #setup all IO ports
          self.ledRed = digitalio.DigitalInOut(board.D11)
          self.ledGreen = digitalio.DigitalInOut(board.D9)
          self.ledBlue = digitalio.DigitalInOut(board.D10)

          self.ledEars = digitalio.DigitalInOut(board.D22)
          self.ledLaser = digitalio.DigitalInOut(board.D27)

          self.speakerMute = digitalio.DigitalInOut(board.D17)

          #set port direction as output
          self.ledRed.direction = digitalio.Direction.OUTPUT
          self.ledGreen.direction = digitalio.Direction.OUTPUT
          self.ledBlue.direction = digitalio.Direction.OUTPUT

          self.ledEars.direction = digitalio.Direction.OUTPUT
          self.ledLaser.direction = digitalio.Direction.OUTPUT

          self.speakerMute.direction = digitalio.Direction.OUTPUT

          #i2c setup
          i2c = board.I2C()  # uses board.SCL and board.SDA
          #gyro
          self.gyro = adafruit_mpu6050.MPU6050(i2c, 0x69)
          #touch
          self.touch = adafruit_mpr121.MPR121(i2c)
          #servoDriver
          pca = PCA9685(i2c)
          pca.frequency = 50
          self.servo0 = servo.Servo(pca.channels[0])

          #battery
          self.I2C_ADDR    = 0x36
          self.bus = smbus.SMBus(1) # 0 = /dev/i2c-0 (port I2C0), 1 = /dev/i2c-1 (port I2C1)

          #set up camera
          self.picam2 = Picamera2()
          camera_config = self.picam2.create_preview_configuration()
          self.picam2.configure(camera_config)
          self.picam2.start()
          time.sleep(2)

     def readVoltage(self):
          read = self.bus.read_word_data(self.I2C_ADDR, 2)
          swapped = struct.unpack("<H", struct.pack(">H", read))[0]
          voltage = swapped * 1.25 /1000/16
          return voltage

     def readCapacity(self):
          read = self.bus.read_word_data(self.I2C_ADDR, 4)
          swapped = struct.unpack("<H", struct.pack(">H", read))[0]
          capacity = swapped/256
          return capacity

     def laser(self, status):
         self.ledLaser.value = status
         return True

     def flashlight(self, status):
         self.ledRed.value = status
         self.ledGreen.value = status
         self.ledBlue.value = status
         return True

     def ears(self, status):
         self.ledEars.value = status
         return True

     def muteSpeaker(self, status):
         self.speakerMute.value = status
         return True

     def checkBatteryStatus(self):
         print(self.readVoltage())
         print(self.readCapacity())
         return True

     def readGyro(self):
         print("Acceleration: X:%.2f, Y: %.2f, Z: %.2f m/s^2" % (self.gyro.acceleration))
         print("Gyro X:%.2f, Y: %.2f, Z: %.2f rad/s" % (self.gyro.gyro))
         print("Temperature: %.2f C" % self.gyro.temperature)
         print("")

     def getTouch(self, index):
         return self.touch[index].value

     def getTouchArray(self):
         array = [False]*12
         for i in range(12):
             array[i] = self.touch[i].value
         return array

     def takeImage(self,path):
          self.picam2.capture_file(path)

if __name__ == '__main__':
     hardware=Hardware()
     hardware.checkBatteryStatus()
     hardware.readGyro()
     print(hardware.getTouch(0))
     print(hardware.getTouchArray())

     hardware.takeImage("img.png")

     while True:
         hardware.servo0.angle = 0
         time.sleep(1)
         hardware.servo0.angle = 180
         time.sleep(1)

Test program that crashes with the error mentioned above
from utils.HardwareUtils import Hardware

soxHardware = Hardware()

I am also willing to refactor this entire section to make it more friendly, and know that there are probably some bad practices in it. I have used python as a scripting language extensively, but not as an object oriented language
Answer: i`ve tested your code. its OK:
import time

#for camera
from picamera2 import Picamera2

class Hardware:

     def __init__(self):

          #set up camera
          self.picam2 = Picamera2()
          camera_config = self.picam2.create_preview_configuration()
          self.picam2.configure(camera_config)
          self.picam2.start()
          time.sleep(2)

     def takeImage(self,path):
          self.picam2.capture_file(path)

if __name__ == '__main__':
     hardware=Hardware()

     hardware.takeImage("img.png")

the error usually appears when u didnt close (picam2.close()) camera from the last use of it.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Python requests library giving me a list error when trying to retrieve a value using a key

Question: I am calling an endpoint
results = get(ENDPOINT, params=url_parameters).json()

and get the following JSON packet
{"status":"success","results":1,"data":[{"companyName":"International Business Machines Corporation","tradeName":"IBM","website":"ibm.com","timeZoneId":"America/New_York","timeZoneName":"Eastern Daylight Time","utcOffset":"-04:00","dstOffset":1,"confidence":77,"isISP":0,"isWifi":0,"isMobile":0}]}

I try and access the data like this
domain = results["data"]["website"]

and I get the following error
TypeError: list indices must be integers or slices, not str

I am not sure why it is using a list rather than a dict and not sure how I can reference the data I am trying to retrieve any help greatly appreciated
Answer: results['data'] is a list. What you need is results['data'][0]['website']
Comment: thankyou, that is very helpful and worked, I'm new to Python and still working out the data structures.


Fake proof that $(5)$ is a prime ideal in $\mathbf{Z}[i]$

Question: Here's a (false) proof that $(5)$ is a prime ideal in $\mathbf{Z}[i]$. I've been trying to spot the mistake, but I can't seem to find it.
Here's how the proof goes: to show that $(5)$ is a prime ideal, we will show that the quotient $\mathbf{Z}[i]/(5)$ is a field. Since we can write $\mathbf{Z}[i] \cong \mathbf{Z}[x]/(x^2 + 1)$, we have
$$(\mathbf{Z}[i])/(5) \cong (\mathbf{Z}[x]/(x^2 + 1))/(5) \cong \mathbf{F}_5[x]/(x^2 + 1) \cong \mathbf{F}_5, $$
where the last isomorphism follows since $x^2 +1$ is reducible in $\mathbf{F}_5$. Since $\mathbf{F}_5$ is a field, this shows that $(5)$ is prime. Where's the mistake?
I'm thinking that the isomorphism $(\mathbf{Z}[x]/(x^2 + 1))/(5) \cong \mathbf{F}_5[x]/(x^2 + 1) $ isn't correct, but I'm fairly sure that when quotienting by two ideals, we can switch the order like this; i.e: quotienting by $(x^2 + 1)$ and then by $(5)$ is the same as doing it in the opposite order. Any corrections would be most welcome. Thanks!
Answer: If $K$ is any field, $x^2+1$ being reducible in $K[x]$ does not imply $K[x]/(x^2+1) \simeq K$. (Just note that the left hand side has $K$-dimension $2$, as $\dim_K (K[x]/(f)) = \deg(f)$ in general.) Rather, this is $\simeq K \times K$ (unless $\mathrm{char}(K)=2$, but even then it's not $K$, see below).
Actually, check for yourself that if $p = (x-a_1)(x-a_2)...(x-a_n) \in K[x]$, with distinct $a_i$, then $K[x]/(p) \simeq K \times ... \times K$ ($n$-fold product).
Added: It's asked in a comment whether the above is still true for more general rings $R$ instead of a field $K$. Note that we certainly have $R[x]/(x-a) \simeq R$ (via $x \mapsto a$) for any $a \in R$. But since the proof of $K[x]/\prod(x-a_i) \simeq \prod K[x]/(x-a_i)$ is basically the Chinese Remainder Theorem (a.k.a. Sun-Tsu theorem), that depends on whether its conditions still hold for $R$ instead of $K$.
Well, for any commutative ring $R$ and elements $a,b \in R$, the ideals $(x-a)$ and $(x-b)$ in $R[x]$ are coprime if and only if $a-b \in R^\times$. So if all pairwise differences $a_i - a_j (i \neq j)$ are units in $R$, then the conclusion still holds. (Note how for $R=K$ this reduces to the above condition that all the $a_i$ are different from each other.)
In the particularly easy example of $x^2-1=(x-1)(x+1)$ we see that as soon as $2 \in R^\times$, we get $R[x]/(x^2-1) \simeq R[x]/(x-1) \times R[x]/(x+1) \simeq R \times R$. In particular, this is true for all $R= \mathbb Z/n$ with odd $n$.
However if $2 \notin R^\times$, this can fail; indeed, as alluded to above, already for a field $R=K$ with $\mathrm{char}(K)=2$, the ring $$K[x]/(x^2-1) \simeq K[x]/(x^2+1) \simeq K[x]/(x-1)^2 \; \stackrel{x-1 \;\mapsto \,t}\simeq \; K[t]/(t^2)$$
is not isomorphic to $K \times K$: they share the same underlying additive group, but unlike $K \times K$, the ring above contains an element $x\neq 1$ with $x^2=1$ (or an element $t \neq 0$ with $t^2=0$).
Consequently, we also have $R[x]/(x^2-1) \not \simeq R \times R$ for any ring $R$ such that $R/(2)$ is a field (because such an isomorphism would, modulo $2$, induce an isomorphism in the case of a field which we just excluded). This includes all the $R=\mathbb Z/n$ with even $n$.
As a last remark, I suspect there are rings $R$ with $2 \notin R^\times$ where $R[x]/(x^2-1) \simeq R \times R$ still holds, "accidentally" i.e. in spite of a proof via the Chinese Remainder Theorem failing. I do not have a concrete example for that (in spite of what I wrote here earlier, the candidate I proposed there failed I think), but there are rings $R$ which happen to be $\simeq R \times R$; there are rings $R$ such that $R[x]/(x^2-1) \simeq R$; and I see no reason why there should not be some weird big ring where both these isomorphisms hold, simultaneously, accidentally.
Comment: Ah I see, thank you. I should have guessed -- the proof is basically the Sun-Tsu theorem!
Comment: Will follow up with an edit soon, already prepared that with an edit regarding characteristics in the field case. I think yes, this is true over any ring in which $2$ is a unit, which of course includes any $\mathbb Z/n\mathbb Z$ for odd $n$.
Comment: A (late) follow-up question to this: does this result still hold if we replace $K$ with a ring $R$? For example, do we have $\mathbf{Z}/25\mathbf{Z}[x]/(x^2 -1) \cong \mathbf{Z}/25\mathbf{Z} \times \mathbf{Z}/25\mathbf{Z}$? (Note that $x^2 - 1$ splits into linear factors in $\mathbf{Z}/25\mathbf{Z}$. ) Or is the result only true for fields?


Algebraic Geometry: How to compute the intersection number for concrete examples?

Question: I am working on the following exercise:

Let $K$ be an algebraically closed field and let $x \in K$.

Compute $i_x(P,Y)$ for $P := Y^2-X^2(X+1)$ and $x \in Z(P,Y)$.
Compute $i_x(P,L)$ for an arbitrary line $L$.
Compute $i_x(P,Y)$ for $Q := Y^2-X^3$ and $x \in Z(Q,Y)$.

Here are the required definitions:

We defined $Z(P)$ as the set of zeroes of a given polynomial $P$. $m_x$ is the kernel of the evaluation homomorphism $\varepsilon_x: K[X,Y] \ni P \mapsto P(x) \in K$. The intersection number for a given $x \in K$ and $P,Q \in K[X,Y]$ is defined as
$$i_x(P,Q) := \dim_K(K[X,Y]_{m_x}/(P,Q)_{K[X,Y]_{m_x}}).$$

I do not see through these formulas yet. Could you please give me a hint on how to start here?
Comment: Write down the quotient you want to compute. For instance, the first one, if we take $x=(0,0)$ then the quotient is $k[x,y]_{(x,y)}/(y,y^2-x^2(x-1))$. But this is isomorphic to $k[x]_{(x)}/(x^2(x-1))$ by sending $y\mapsto 0$, and now since $x-1$ is a unit this is isomorphic to $k[x]_{(x)}/(x^2)$, which is isomorphic to $k[x]/(x^2)$ which clearly has dimension two. Is that helpful?
Comment: Here are some other posts with examples of computing intersection numbers: [1](https://math.stackexchange.com/questions/2120270/intersection-number-between-two-projective-curves), [2](https://math.stackexchange.com/questions/1696061/checking-the-intersection-multiplicity-for-two-curves), [3](https://math.stackexchange.com/questions/4033736/finding-intersection-multiplicities-of-a-tangent-line-and-a-quartic)
Answer: Maybe you would enjoy knowing some of the algebraic properties of the number $i_x(P,Q)$:
$$i_x(P,Q) = i_x(Q,P)$$
$$i_x(P, Q_1Q_2) = i_x(P,Q_1)+i_x(P,Q_2)$$
$$i_x(P+QR,Q) = i_x(P,Q)$$
Which allow you to simplify a lot of problems. Sometimes it is easier to deal with power series, to use inverses for polynomials, in which case you can use that
$$i_x(P,Q) = \dim_K ( K[[X,Y]]/(P,Q))$$
Note that the questions you pose are not difficult to answer because the intersection multiplicity of a curve and a line can be obtained parametrizing the line and seeing the multiplicity of the zero that you obtain:

the line is $t \mapsto (t,0)$, so substituting in the equation of $P$ you get $-t^2(t+1)=0$. therefore you have intersection multiplicirty 2 at $t=0$ and $1$ at $t=-1$
the line is again $t \mapsto (t,0)$ so you obtain $-t^3=0$, which implies multiplicity 3


Why do I turn into super Mario instead of fire Mario when I touch a fire flower AS SMALL Mario in Super Mario Bros 1?

Question: When I was playing Super Mario Bros 1, I - as Super Mario - hit a block containing a fire flower. I then got hit by an enemy, changing me into small Mario, but the fire flower was still on-screen.
When I touched the fire flower as Small Mario, it just turned me into Super Mario instead of Fire Mario.
Why does this happen?
Comment: Meta post about this question: [Why is this question about a game mechanic off topic?](https://gaming.meta.stackexchange.com/q/15671/4797)
Answer: For a technical explanation, if we look at the disassembled code for Super Mario Bros, we can see that the routine for collecting fire flowers and super mushrooms is exactly the same.
<code>HandlePowerUpCollision:
  jsr EraseEnemyObject    ;erase the power-up object
  lda #$06
  jsr SetupFloateyNumber  ;award 1000 points to player by default
  lda #Sfx_PowerUpGrab
  sta Square2SoundQueue   ;play the power-up sound
  lda PowerUpType         ;check power-up type
  cmp #$02
  bcc Shroom_Flower_PUp   ;if mushroom or fire flower, branch
  cmp #$03
  beq SetFor1Up           ;if 1-up mushroom, branch
  lda #$23                ;otherwise set star mario invincibility
  sta StarInvincibleTimer ;timer, and load the star mario music
  lda #StarPowerMusic     ;into the area music queue, then leave
  sta AreaMusicQueue
  rts

Shroom_Flower_PUp:
  lda PlayerStatus    ;if player status = small, branch
  beq UpToSuper
  cmp #$01            ;if player status not super, leave
  bne NoPUp
  ldx ObjectOffset    ;get enemy offset, not necessary
  lda #$02            ;set player status to fiery
  sta PlayerStatus
  jsr GetPlayerColors ;run sub to change colors of player
  ldx ObjectOffset    ;get enemy offset again, and again not necessary
  lda #$0c            ;set value to be used by subroutine tree (fiery)
  jmp UpToFiery       ;jump to set values accordingly
</code>
I would say this is intended behavior. If you somehow could get a super mushroom onscreen while you were Super Mario, he would turn into Firey Mario. Most likely, the rationale is to save space on the ROM.
Answer: Yes as the weakened Mario the game script only allows 1 stage progression from in level items so anything for small Mario(1 hit to kill) go to super mario(2 hit to kill), then only if the item is tir 3 fire flower will grant the special mario(3 hit to kill).
Answer: I always saw it as a 3 stages of Mario
Mini - Big - Fire
And the powerups do not just do +1 to the stage counter. They just boost you up to the appropriate stage (if the stage is higher than the current.)
Like if you get a mushroom and already is on the Big stage, you will not go up to fire, you stay big.
So when you touch a fire flower, that you would be Mini or big it boosts you up to Fire stage. Its like if the mushroom is always included in the flower.
Comment: The question is why does it _not_ work the way you've described.
Comment: How is this an up voted answer ? OP clearly states it did not work like this in his interaction. I am so confused by this site sometimes.
Comment: https://www.youtube.com/watch?v=v2lVgHaRDf8 demonstrates that they are two separate flags, with hilarious results if you mess around with them.


Global handler to catch when new window is shown in WPF

Question: The root problem I'm trying to solve is to gather all users input on my application. Clicks, keystrokes etc. And log element which got that input.
In order to achieve this I've added PreviewKeyDown and PreviewMouseDown handlers to the main window and it works fine. But my application is based on a big framework and this framework may display some dialogs. I need a way to handle such dialogs and attach handler to them. Is there a way to create one centralized handler for this?
Comment: You might have to get the process details of your application then use it look up for any window for that process. The captured keystrokes and mouse events can be captured globally and checked with the process details of your application and take necessary action.
Answer: Since UI-Events are generally RoutedEvents, you can simply register a method of your own to handle every invocation of that event. If you for example want to see how your PreviewKeyDownEvent tunnels through your UI:
EventManager.RegisterClassHandler(
    typeof(UIElement),
    UIElement.PreviewKeyDownEvent,
    new RoutedEventHandler(localMethod));

With this you could "trace" a MouseDown event tunnel down and bubble up your visual tree when you click a Button:
static UiEventHandler()
{
    EventManager.RegisterClassHandler(
        typeof(UIElement), UIElement.PreviewMouseDownEvent,
        new RoutedEventHandler(PreviewMouseDown));
    EventManager.RegisterClassHandler(
        typeof(UIElement), UIElement.MouseDownEvent,
        new RoutedEventHandler(MouseDown));
}

private static void MouseDown(object sender, RoutedEventArgs e)
{
    Debug.WriteLine("MouseDown on " + sender.GetType());
}

private static void PreviewMouseDown(object sender, RoutedEventArgs e)
{
    Debug.WriteLine("PreviewMouseDown on " + sender.GetType());
}

Output:
//Event hits Window and tunnels through the visual tree
PreviewMouseDown on WpfApplication10.MainWindow
PreviewMouseDown on System.Windows.Controls.Border
PreviewMouseDown on System.Windows.Documents.AdornerDecorator
PreviewMouseDown on System.Windows.Controls.ContentPresenter
PreviewMouseDown on System.Windows.Controls.Grid
PreviewMouseDown on System.Windows.Controls.Button
PreviewMouseDown on Microsoft.Windows.Themes.ButtonChrome
PreviewMouseDown on System.Windows.Controls.ContentPresenter
PreviewMouseDown on System.Windows.Controls.TextBlock
//Nobody handled the event, so it bubbles back up
MouseDown on System.Windows.Controls.TextBlock
MouseDown on System.Windows.Controls.ContentPresenter
MouseDown on Microsoft.Windows.Themes.ButtonChrome
//ButtonChrome handled the event as a 'Click'

Comment: Thank you! This is what I need. I only added deduplication check, so I don't get notified for every step of the same event in the VisualTree
Comment: @VladimirPerevalov If you need other Input Events (like Touch, Stylus, MouseWheel, Focus, etc.) you can find a very extensive list [here on MSDN](https://msdn.microsoft.com/en-us/library/system.windows.uielement(v=vs.110).aspx) in the section "Fields".