'int' object has no attribute 'mouse_x' referring to self.mx

Question: I have a mouse sprite that updates the x and y positions of the mouse each iteration of the game loop, but I am not quite sure what the error message found below: "'int' object has no attribute 'mouse_x', seems like its referring to 'self' as an int object, and 'mouse_x' to be its attribute?
import pygame

class mouse_sprite(pygame.sprite.Sprite):

    def __init__(self, x, y, screen):
        self.screen = screen
        self.mouse_x = x
        self.mouse_y = y

        self.update_rect(self.mx, self.my)

    def update_rect(self):
        self.rect = pygame.Rect(self.mouse_x, self.mouse_y, 1, 1)

    def update(self, x=None, y=None, screen=None):
        **#ERROR: 'int' object has no attribute 'mouse_x' Line 24: self.mouse_x = x**
        if x is not None:
            self.mouse_x = x

        if my is not None:
            self.mouse_y = y

        if screen is not None:
            self.screen = screen

        self.update_rect()

mouse = mouse_sprite
mx, my = pygame.mouse.get_pos()
mouse.update(mx, my)

Answer: You're not creating a new object. You're just calling class method like a static method
Instead of
mouse = mouse_sprite

do
object = mouse_sprite(...)  # Pass init parameters
object.update(...)          # Pass method parameters

When you call a method on created object, first parameter gets passed as self. In your case, you've not created a new object so the first parameter mx is getting assigned to self which of type int. And it doesn't have field mouse_x.


Opacity Gradient Applied to CALayer?

Question: I basically want the opacity of every layer in my UITableView instance to "fade out" at the top 10 or so pixels.
Is there any way to fade out a CALayer (or more generally, a UIView)'s opacity? It'd be similar in effect to adding a shadow with a CAGradientLayer but instead of covering the table view's other layers with another, it would apply a filter to them to make them transparent according to a gradient.
Answer: Yes, by using the CALayer's mask property, but it's rather inefficient. Typically this sort of effect is done by overlaying a gradient that goes from transparent to the background color on top of your view (but this only works if you know what your background is).
Comment: Perfect - thanks! Unfortunately, my background isn't a solid colour but a dynamic image. I'm only doing this for one view onscreen at a time, but I'll check it out in Instruments before I ship.

I had to create a CALayer to hold an opacity CAGradient layer for the fade and another plain CALayer for the rest of the view to be visible, but it looks fantastic!

Thanks again!
Comment: @AshFurrow: Glad to hear it worked. `mask` is relatively expensive, but when you need it, it tends to do the job. If you're having performance issues and you're not animating anything you might want to look into the `shouldRasterize` flag. That can help static content perform better under certain circumstances. But of course if you're animating then it's not going to be good.

Opacity Gradient Applied to CALayer?


If I have the same package name in Nexus private repo as it is in the npm publish repo, which one takes priority when I install?

Question: I am setting up nexus npm repository, and created npm-group = npm-private+npm-registry (proxy to npm offical registry).
It comes to me thinking that if I publish my own package and name it say "jest" to my private repo,
what happens if I do npm install jest? Does it take the private fake one or the one published in official site?
Thanks
Answer: You need to use scopes for your  private packages. You prefix them with @yournamespace (for instance: <code>"name": "@yournamespace/jest"</code>), and you adjust your npmrc accordingly:
<code>; Set a new registry for a scoped package
@yournamespace:registry=https://mycustomregistry.example.org
</code>
Using this scheme, you could use separate npm repositories, one for the proxy to the official npmjs repo, and one for your private packages.
Otherwise, if you override a package name, it will shadow the one that is proxified, so you will fetch your private package instead of the official one.
Comment: Thank you, I really like this approach, it gives me a peace of mind and don't need to worry about conflicts and you also answered me which one take precedence. Thank you!


TF2- how to deal with Roof Wranglers

Question: A Roof Wrangler is an engineer that uses the Wrangler to jump up to a high point--e.g. the roof above the Sniper area on ctf_doublecross--
-- use his Rescue Ranger to get his sentry, dispenser and teleporter on the roof, and proceed to Wrangle everyone from afar (usually accompanied by a second Engineer).
Another example of where this occurs is in cp_5gorge:

Now, there seem to be no ways of countering this behaviour:

Scouts, Snipers, Heavies and Pyros are useless, as they can't get up on the roof, nor do they have any weapons capable of destroying the nest from afar).
Soldiers and Demoman still have a hard time, since the Wrangled sentry is resistant to most damage, and, if there's another Engineer, turtling on the roof, who has a Short Circuit, he makes these two classes redundant.
Although Spies can enter the enemy's teleporter, the rooves are usually quite small, so it's easy to identify a Spy (or at least get rid of his sapper).

In the case of ctf_doublecross, Roof Wranglers become even harder to take down when they are on the enemy's roof (e.g. in the case of the above picture, a BLU engineer Roof Wrangling onto RED's roof).
Now, what is an effective way to deal with these Roof Wranglers?
Comment: why not just get a sniper and pop the engies heads off and yell open season?
Answer: The key to taking these down is teamwork (although admittedly there is little of that on TF2 nowadays). The best way to do it by far is a combination of spy, soldier and demoman.
Step 1: The spy disguises and enters the teleporter.
Step 2: The spy saps the engineer's stuff.
Step 3: (This should happen as soon as the spy exits the teleporter). The soldier and demoman come out and begin firing at the sentry. The sentry should be sapped by now, so the solly distracts the engineer(s) while the demoman launches stickybombs.
Step 4: Explosions!: The demoman detonates his stickies while the solly continues firing.
Step 5: Everything is destroyed. You can continue eating sandwiches and showing off your cool new hat.
It should also be noted that (as with everything else on this game), more players = greater chance of success.
Answer: First, reference this old but useful set of strategies for dealing with any sentry nest.  Some of the advice won't be applicable due to how difficult it is to reach, but it should help guide you in the correct path.

Ideally, you will be working together as a team to take down the sentry nest - which means spies taking the engie's teleporter to sap/backstab, spam from demomen, soldiers and heavies, snipers headshotting the engineers, scouts bonking to distract or force the engine to wrangle his sentry, your engineers wrangling their own sentries to attack the nest, and pyros airblasting rockets back for additional damage, while your team also keeps the enemy repelled.  While medics provide support with ubers.
Getting every member of your team to commit to this is difficult enough when the entire rest of the enemy team is fighting you, to say nothing of trying to get it organized in a public server.
On a team that has coordination, you're going to want to devote at least half of your team to keeping the enemy offense distracted while you take care of their 'impenitrable' defense.  Scouts and Pyros are better suited for distraction, and can definitely be spared while putting your attack together. While Snipers can attempt to headshot pretty much anyone they like, or if there's no enemy to headshot, aide the spam to destroy the sentry nest.  The Heavy can also focus on the enemy team, since his minigun spread means his bullets mostly won't reach the sentry nest.
On a public server, barring some miracle, you'll mostly be on your own.  The spy is best suited for taking care of this nest, but if the Engie is smart and destroys his teleporter once he's up there, there's no much a Spy can do to help.
Snipers should of course be sniping at the Engie, though if he's turtling his head might be guarded.  You can try to snipe at some of his equipment, like his dispenser, to get him to switch his focus to make his head pop out.
Spam as a demo and a soldier is always helpful.  The Lock-n-Load and Direct Hit are ideal if you can get a clear shot, but the regular grenade launcher or a splash-frinedly rocket launcher are better if you can't get a bead on him.
And of course a heavy can help, though the minigun spread is going to make hitting his equipment much harder, and might be better off trying to keep the enemy team at bay.

Overall though, the main thing you want to do is at least try to take it down - if you start trying to take the nest down, it'll encourage other teammates to try as well.

TF2- how to deal with Roof Wranglers


Characterize $\frac{df}{dx}(x)f(x)f(x)=x$

Question: can you help me characterize $\frac{df}{dx}f(x)f(x)=x$? Should be 1st order, not-linear, not elliptic, parabolic, hyperbolic.
Solution with characteristics not possible because not (quasi)linear.
Any ideas for characterization/solution theory?
Thanks!
Comment: After editing, I realised that $*$ could have meant convolution instead of product. If you meant that, you can revert my edit, but also please add a note saying that it is convolution
Answer: This is an example of a separable ODE. Note that $f'f^2 = (f^3/3)'$. So just set $g=f^3/3$, then the equation is simply $g'=x$. We can solve by just integrating both sides
$$ g(x) = \frac{x^2}2 + C$$
i.e. the general solution is
$$ f(x)= \left(\frac{3x^2}2 + C\right)^{1/3}$$
Comment: This also amounts to just separating variables $y^2 dy = x dx$ and integrating both sides.
Comment: @Ned ah yes, separable ODE, that was the name I was looking for. Thanks!


Help me to get rid of unmet dependencies

Question: when I try to install it shows this. Help me to get rid of it. I tried to install codeblocks once with dpkg command.  I am using ubuntu 20.04
reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
 codeblocks-contrib : Depends: libboost-system1.62.0 but it is not installable
                      Depends: libhunspell-1.4-0 but it is not installable
                      Depends: libwxgtk3.0-0v5 (>= 3.0.2+dfsg) but it is not installable
                      Depends: libwxsmithlib0 (= 20.03) but 20.03-3 is to be installed
                      Depends: codeblocks (= 20.03) but it is not going to be installed
                      Recommends: valgrind but it is not going to be installed
                      Recommends: cppcheck but it is not going to be installed
                      Recommends: cscope but it is not going to be installed
                      Recommends: cccc but it is not going to be installed
 codeblocks-dev : Depends: libcodeblocks0 (= 20.03) but 20.03-3 is to be installed
 codeblocks-libwxcontrib0 : Depends: libwxgtk3.0-0v5 (>= 3.0.2+dfsg) but it is not installable
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

Comment: The error message tells you what to do, twice. "`You might want to run apt --fix-broken install`". Do that.
Comment: But with sudo before that command
Comment: I tried, But it did not work.
Answer: I suggest you do the following commands that might install the software and remove the error message
sudo apt --fix-broken install

sudo apt update

sudo apt-get upgrade

sudo apt install codeblocks

Answer: Step 1:
Firstly I would suggest trying the whole installation procedure using aptitude, since it provides solutions that most of the time work.
sudo apt update
sudo apt install aptitude

And then try downloading your package using aptitude:
sudo aptitude install <package-name>

Step 2:
If that doesn't work, try downloading the dependencies one by one to see if the problem goes away.
sudo apt install -f libcodeblocks0=20.03 # -f flag means fix broken
sudo apt install -f libwxgtk3.0-0v5=3.0.2+dfsg
sudo apt install -f libboost-system1.62.0
sudo apt install -f libhunspell-1.4-0
sudo apt install -f libwxsmithlib0=20.03

Step 3:
If the above steps don't cut it either (which I guess might happen since some packages are marked as not installable), try downloading those packages from Ubuntu registry for your computer architecture (I'll list for amd64)
Links:
libwxgtk3.0-0v5
codeblocks
libcodeblocks0
libhunspell-1.4-0 (right, under downloadable files)
libwxsmithlib0
libboost-system1.62.0
Hope this solves the problem. If not, comment below.


Make sure async methods execute in same order as they were called

Question: Let's say I have 3 async methods which all do the same thing: send some data to a server and add the response data to an array (all of them add to the same array).
I call these methods at the same time, but they send different amounts of data to the server.
If the first method sends more data to the server than the third method, the third method will get the response back sooner, thus add the data to the array sooner. The response data consits of coordinates, so the order in which they are in the array matters.
How can I make sure, that even if the third method gets the repsonse sooner than the first or the second one, it won't add the data to the array before the previous methods did? Thus, preserving the order of the coordinates in the array.
The methods are NSURLConnections and they all send an async request.
EDIT: Here is the working code:
 //Array of snapped points from the JSON
            NSArray *snappedPoints = [result objectForKey:@"snappedPoints"];

            NSMutableArray *locationsArray = [[NSMutableArray alloc] init];

            //Loop through the snapped points array and add each coordinate to a temporary array
            for (int i = 0; i<[snappedPoints count]; i++) {
                NSDictionary *location = [[snappedPoints objectAtIndex:i] objectForKey:@"location"];

                double latitude = [[location objectForKey:@"latitude"] doubleValue];
                double longitude = [[location objectForKey:@"longitude"] doubleValue];

                CLLocation *loc = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];

                [locationsArray addObject:loc];

            }

            //Add these temporary location arrays to the dictionary with the key as the request number
            [tempLocationDictionary setObject:locationsArray forKey:[NSString stringWithFormat:@"%i",requestNumber]];

            //If all requests have completed get the location arrays from the dicitonary in the same order as the request were made
            if([tempLocationDictionary count] == numberOfRequests){

                //Just a path because I am drawing these coordinates on a map later
                GMSMutablePath *path = [GMSMutablePath path];

                //Loop through the dictionary and get the location arrays in the right order
                for (int i = 0; i<[tempLocationDictionary count]; i++) {
                    //Create a dummy array
                    NSArray *array = [tempLocationDictionary objectForKey:[NSString stringWithFormat:@"%i",i+1]];

                    //Get the coordinates from the array which we just got from the dictionary
                    for (CLLocation *location in array) {
                        [path addCoordinate:location.coordinate];

                    }
                }

Comment: Update your question with relevant code so people can point you in a good direction.
Comment: Depends on what the methods are doing that makes them asynchronous. Are these `NSURLSession` calls? `NSOperationQueue`? Something else?
Comment: NSURLConnection with an async reauest!
Answer: One way would be to replace NSURLConnection with NSURLSession and its related classes. It's newer and generally a superior choice. For your specific situation, it's possible to use a custom NSURLSessionConfiguration where you would set HTTPMaximumConnectionsPerHost to 1. That way the connections would be forced to run in order, solving your problem.
Of course, not having simultaneous connections might slow things down. In that case you'll have to accumulate the data temporarily without adding it to your array and only update the array when all the connections are complete. There are various ways you might do this depending on exactly what data comes back from the server.
One relatively simple way: If you know you'll always have three connections, use an NSMutableDictionary with integer NSNumber objects as the keys. After each connection you'd do something like
mutableDictionary[@1] = // your server data here

Use @2 or @3 for the other connections. Every time you add data, check to see if you have results for all three, and if so, add everything to your array. There are lots of other ways around this, the key is to have some kind of temporary structure where you can (a) accumulate data until all the connections are complete, and (b) keep track of which data came from which connection, either simply by number, or by URL, or by some other unique data that the server provides.
Comment: The latter half of this answer is what I had in mind and why I asked the OP to post some relevant code. Then a more concrete solution could be offered.
Comment: Thanks! I had something similar in my mind as well. The only problem was with (b) keeping track of which data came from which connection. I thought about assigning a number to each connection (increasing the number by one for each connection), and adding their data to the dictionary with the connection's assigned number. Than add the data to the array from the dictionary based on their keys, starting from number 1. Would this work?
Comment: Yes, indeed this idea worked. I updated the code to reflect this! Thanks, again!
Answer: This is a problem to be solved with NSOperationQueue and dependencies.
Check out Advanced NSOperations [transcript] from WWDC 2015:

When the WWDC app starts up, there's a bunch of setup that we need to do.
First, we are going to download a small configuration file, and this file will tell us small things like what's the most recently supported version of the application, what features we have enabled, and so on.
So after we download this file, we are going to perform a version check to make sure that you are running the latest version of the WWDC app.
And then after we check the version of the app, we can start downloading useful pieces of information, such as the news that we show in the News tab and the schedule for the conference.
After we've downloaded the schedule, then we can start importing any favorites that you've saved to iCloud, any feedback that you've submitted so you can see it in the app, and we are also going to start downloading the list of videos.

Applying dependencies as they describe for these operations should sort you nicely.
Comment: Its a useful technique and thanks for the pointer to the interesting presentation, but in this case I don't believe that there is a dependency between the three tasks, so Tom's suggestion of collating the data correctly after the operations complete will provide the required outcome with the benefit of concurrency
Comment: Your question said "How can I make sure, that even if the third method gets the repsonse sooner than the first or the second one, it won't add the data to the array before the previous methods did?". That means that operation SaveData3 has a dependency on SaveData1 and SaveData2 completing, correct?
Comment: It wasn't my question, but using dependencies on fetching the data is one way of achieving the required outcome, but so is managing how the data is put into the array once it is retrieved


Array Numpy Side Effect

Question: I found a strange effect when permuting array with numpy:
    def permute(yy, kmax) :
     kmax=5
     kk= np.random.uniform(1,kmax)
     nn= int(np.floor(len(yy)/kk))
     yy3= np.zeros_like(yy );
     np.copyto(yy3,yy)

     for ii in range(0, nn):
        ax= kk*ii-kk*nn
        aux= yy[ax]
        aux2= yy[kk*ii]
        yy3[ax] = aux
        yy3[kk*ii] = aux2

     return yy3

and
   yy= np.random.normal(0,1,50000)
   yy1= permute(yy,2)
   ( np.var(yy)- np.var(yy1) )

   ( np.mean(yy)- np.mean(yy1) )

Result is not zero !!!
Do you think this comes from reference assignment in the array ?
Comment: That's not a permutation. You're taking values from the wrong array when you swap.
Comment: Show us what it does for a small sample case.
Comment: yy=yy3 , both are same arrays.
If you execute this code, You will see that the result is not zero, whereas it should be zero.
Comment: What are the stats differences?
Answer: I ran your function with np.arange(10) and got
1752:~/mypy$ python stack35004877.py
0.0
0.0
[0 1 2 3 4 5 6 7 8 9]  # yy
[0 1 2 3 4 5 6 7 8 9]  # yy1

And repeated it with the large random array, with the same 0s for the statistics.
Note that your code did not permute the input
Maybe it will be clearer if I clean it up:
def permute(yy, kmax=5) :
     kk= np.random.randint(1,kmax)  # int rather than float
     nn= int(np.floor(len(yy)/kk))
     print(nn,kk)
     yy3= yy.copy()
     for ii in range(0, nn):
        ind1 = kk*ii
        ind2 = ind1-kk*nn
        yy3[ind2] = yy[ind2]
        yy3[ind1] = yy[ind1]
     return yy3

You aren't moving anything; and with kmax=2 you just copy every thing from yy to yy3 - something you already did outside the loop.  With kmax=5 you don't copy everything in the loop - but the initial copy hides that.
With random.uniform(), kk is a float, and the indexes are also floats. That's not desirable, but apparently not a problem.
But even if I switch the indices:
    yy3[ind2] = yy[ind1]
    yy3[ind1] = yy[ind2]

I don't permute anything, because ind2 a negative value, that maps on to the same element as ind1.  yy[-1] is the last item of yy.
[(0, -10), (1, -9), (2, -8),... (9, -1)]

I could work out the details, but I think you should do that yourself - with a small test case.  And skip that initial copyto, that just hides errors in the iteration.  Print the details, not just summary statistics from large random arrays.
And in the long run you don't want to use an iteration like this.  You want to do the permutation with one indexing call.  But first get this version working correctly.
Comment: Hi,  The index is not int, and it caused some side effects, when No int index is used for array.

Array Numpy Side Effect


Call of Duty Black Ops Perks

Question: I'm playing the Wii version of Call of Duty: Black Ops.  Of the perks available, I'm thinking of going for the stealth perks, but was wondering which perks combined together do you think is the ultimate combination?
Comment: You need to specify a purpose of the class if you want tips on perk selection. There is no one magic combination to go with.
Comment: Reopen to close again for needing more details and clarity. At this point this question needs to be closed anyway, because 'ultimate' in this context *is* opinion-based.
Answer: Tier 1: Ghost
Tier 2: Sleight of Hand or Warlord.  You need to attach a suppressor to your weapon
Tier 3: Ninja or Hacker.  For a true stealth class, Ninja would be the way to go but Hacker is a good choice to sniff out those pesky claymores.
For your lethal, I would use the Tomahawk for silent kills.  For your equipment, I would use the motion sensor to detect anyone that is near by.
Comment: If you have a headset or use earphones having ninja is god like. You never hear your own footsteps but hear reloads and foot steps of enemies and sadly all allies not wearing Ninja pro.
Answer: If you want stealth:
1) Ghost
2) Sleight of Hand (use supressor, its better to get used to the iron sight)
3) Ninja
I always use Semtex in every custom class, and for equipment I preffer Stun Grenades (you can throw them really fast) or Decoy.
Try using a SMG with:
1) Lightweight
2) Sleight of Hand
3) Maraton
Semtex
Answer: Stealth but requires a good aim because you cant afford to waste ammo: ghost pro, sleight of hand pro, and hacker pro
Offense: Scavenger pro, sleight of hand pro, and hacker pro
 So far this worked with me great, don't forget to use a suppressed weapon in stealth otherwise it beats the whole purpose, as for offense I suggest using assault rifles with sights like the commando or famas with red dot or an M60 if you want to go crazy and keep holding the trigger. Have fun.
Answer: you are definitely going to need scavenger pro and hacker pro i don't know but the last one is up to your preference. For scavenger pro it takes away the need to conserve bullets and Hacker pro could help if your team is loosing and the other team has advantages like care packages and other things
Comment: Can you expand on this? Why do you think those perks are useful in this context?
Comment: You are grave digging ;)
Comment: For scavenger pro it takes away the need to conserve bullets and Hacker pro could help if your team is loosing and the other team has advantages like care packages and other things.
Comment: @Dr_Bunsen There's no rule against that here...as long as the answer is good and the question is worth answering, at least.

Call of Duty Black Ops Perks


Two .css files in the same folder, but only one can be found by Django, Windows10

Question: As the title described. Please refer to image below:

The two css files is under the same folder and in the template file I copy the link line just changed the file name. Why the abc.css file can't be found as shown in the command line screen? I just can't understand.
Also anther image file is also not found either, also a mystery to me.

As another try, I moved the png to static root and changed the template code  to
src="{% static 'folder.png' %}

Comment: `CTRL + F5` or `CTRL + SHIFT + I` > Network > Disable cache checkbox.
Comment: I add a new picture. It seems to behave as the same.
Comment: First of all, the result you get is because the Django design. we can't add two CSS files directly. StackOverflow has similiar questions, see this https://stackoverflow.com/questions/49873194/django-use-multiple-css-file-in-one-html and this https://stackoverflow.com/questions/25386868/django-templates-use-different-css-for-pages and this
https://stackoverflow.com/questions/64474041/how-to-add-multiple-css-file-in-django3-in-a-single-html-file
Comment: Before I post this question I do read the first link you provided. But I thought the reply was telling me that I can use as many .css files as I wish. Contrarily maybe. I'm reading those posts again.
Comment: @yueyongdong I read again all these 3 posts. I don't think all are suitable for my case. The 49873194 and 64474041 just show me I can use css link side by side. The same as my first understanding. The 25386868 just saying one child css link replacing its parent.
Answer: STATIC_URL setting is no related to what folder you're storing the images in, it's related to the URL of the file located at the server. Let's say that we have an image foo.png that's shown somewhere on the website. When you right click on the image and open it in a new tab, the image URL will look something like that http://localhost:8000/static/foo.png.
What you want is to make Django look for static files directories so that Django will later collect them into another directory. Let's say you're storing the static files for the whole project in a folder called static located at the root of the project, then you have to define the following setting in settings.py:
# Make sure to import os first

import os

# ...

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

This means that Django will also look for static files in a folder called static in our root folder, not just in our apps.
Now we want Django to collect all the static files in one place. Let's add this setting in settings.py:
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

The folder staticfiles will hold all static files for the project. Finally, make sure to run the command:
$ python manage.py collectstatic

This command will make Django gather all the static files in staticfiles folder.
Comment: I tried what you said but not succeed yet. However I believe you may be correct to some extent and I'll check further in this direction.
Comment: The .css file missing resolved. I made a mistake for APP static folder and project static folder. You wrote python manage.py collectstatic remind me of that. I just the .css file to app/static and the collectstatic action will move them to the specific dedicated resource bin. I forgot this step. I'll read again the Django tutorial.


How long does the PSP remember's it's state when the battery is removed

Question: i have 2 Batteries for my PSP 2000, i only recently learned that the problem with the first battery may have actually been the PSP not charging up via the power cable
when i was fiddling with batteries between my 2 PSPs i found that if i switch the batteries quickly the PSP would not fully rest (By asking me to re-input the current time/date)
so i am wondering, if i was in the middle of a game and notice the battery is low, i put the PSP on standby and take the battery out, how long do i have to replace the battery before the PSP looses it's state and resets (thus quitting out of my game)
Answer: From my personal experience: swapping the batteries probably won't work, except you are extremely fast.
The PSP's date is kept because of an internal battery (pretty much like in every PC - BIOS battery). It takes some time till this one is fully depleted.
So: Once the power supply is cut (battery), the PSP does not hold enough charge, to keep the game running, even on standby.
What you could do - if you notice low battery, plug in the power supply and then swap the battery. Now, I don't know if the PSP can run with power supply only, so try it first.
Comment: it can, i was once playing my PSP 1000 without a battery because i had it in my PSP 2000 while i was waiting for Dissidia 012 to install to the memory stick (i was playing it on the TV before i got my new battery).....downside is that i think the DC-IN port on my PSP 2000 might be stuffed and that's why i was asking about battery switching, guess i have to think of a backup plan


For a topological space $X$ with a bijection $f: X \rightarrow \mathbb{R}$, prove there exists $x$ such that $X \setminus \{x\}$ isn't connected.

Question: The title is lacking because the whole question didn't fit:
For a topological space $X$ with at least two points $X$ such that there exists a continuous bijection $f: X \rightarrow \mathbb{R}$, prove there exists $x$ s.t. $X \setminus \{x\}$ isn't connected.
We know there are at least two points in $X$, labeled $x_1,x_2$. We can label $f(x_1) = y_1$,$f(x_2) = y_2$, and by continuity, for an open interval $B_r$, $f^{-1}(B_r(y_1), f^{-1}(B_r(y_2) $ are both open. I'm not sure how to continue from here.
I can't even convince myself that the question is indeed true, for example, taking $X = \mathbb{R}, f(x) = x$. I can't convince myself that $\mathbb{R} \setminus \{x_0\}$ isn't connected. Is it really the union of two disjoint closed sets?
Any help would be appreciated.
Comment: To answer the last question; yes. $(-\infty,x_0)$ is open *and* closed in the subspace topology (which is what you are interested in). Therefore $\Bbb R\setminus\{x_0\}$ is not connected.
Comment: If you are looking at it as a subset of $\Bbb R$, yes. But if we put $Y=(-\infty,x_0)\cup(x_0,\infty)$, then no.
Comment: Isn't $x_0$ a limit point? Shouldn't all limit points be part of a closed set?
Answer: $\Bbb R\setminus\{0\}=(-\infty,0)\cup(0,\infty)$.  The point here is that $(-\infty,0)$ and $(0,\infty)$ in the subspace topology of $\Bbb R\setminus\{0\}$.


Cycle to previous suggestions in VSCode

Question:
Hi, is there a way in Visual Studio Code to cycle to suggested keywords even when you already selected one of them (by clicking TAB multiple times)? This is possible in Sublime. In VSCode even with the keybindings of Sublime it does not work.
In the GIF above, in order to cycle through keywords, I pressed TAB several times, after typing 'hel' and 'he'
Answer: I think it is not possible to achieve this exact behavior out of the box. Even the Sublime Text Keymap does not support this. Maybe you want to open a new issue?
A possible workaround to achieve something similar could be to add custom keybindings. To enable toggling the suggestions via Tab and Shift + Tab you can add the following to your keybindings.json:
{
    "key": "tab",
    "command": "selectNextSuggestion",
    "when": "editorTextFocus && suggestWidgetMultipleSuggestions && suggestWidgetVisible"
},
{
    "key": "shift+tab",
    "command": "selectPrevSuggestion",
    "when": "editorTextFocus && suggestWidgetMultipleSuggestions && suggestWidgetVisible"
}

Update
Maybe macros can solve this. This enables you to chain multiple vscode commands into a single command. Then you can bind this new command to Tab.
Comment: I don't know, even with macros it seems impossible. Basically, because the suggestions are only available when you are typing but not when a suggestion is selected and wrote down.
Answer: For those still looking for this capability, it was implemented here. Set
"editor.tabCompletion": "on"
in your settings.json, or change the Editor: Tab Completions setting in the UI to enable it.
Answer: We can use user keybindings to navigate up and down in suggestions available.
There are two default key bindings selectPrevSuggestion and selectNextSuggestion in vscode which can be used to move up and down in the suggestions list.
First, we have to got to show default key bindings from settings and here, we can change selectPrevSuggestion and selectNextSuggestion easily as our wish.
In below screenshot we can see that

For selectPrevSuggestion it is upArrow by default which can be changed by clicking on it easily to our wish.
Similary, we can change for selectNextSuggestion.

Cycle to previous suggestions in VSCode


How to randomly choose an element from coredata swift

Question: import UIKit
import CoreData

class Period1Controller: UIViewController, UITextFieldDelegate {

@IBOutlet weak var enterName: UITextField!
@IBOutlet weak var presentName: UITextView!
@IBOutlet weak var independceStatue: UITextField!
@IBOutlet weak var driverSelection: UITextField!

var entitys = [NSManagedObject]()
var nameList : [String] = []
var period1 = ""
var period1NameList = ""

override func viewDidLoad() {
    super.viewDidLoad()

}

func setValues() {
    nameList = [enterName.text!]
}

//this button is for saving the element into the core data
@IBAction func setName(sender: UIButton) {
    setValues()
    for item in nameList{
        period1 += (item + "  ")
        period1NameList += item
    }
    let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    let entity = NSEntityDescription.entityForName("Entity", inManagedObjectContext: context)
    let otherEntity = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: context)
    otherEntity.setValue(period1NameList, forKey: "period1Core")
    do {
        try context.save()
        print("Item Saved")
    } catch {
        print("Saved Failed")
    }
    presentName.text = period1
    enterName.text = ""
}

// this button is for taking out element from core data and randomly pick a value from the element I took out from core data
@IBAction func start(sender: UIButton) {
    setValues()
    let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    let request = NSFetchRequest(entityName: "Entity")
    do {
        let results = try context.executeFetchRequest(request)
        entitys = results as! [NSManagedObject]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
    let otherEntity = entitys.last
    let randomIndex = Int(arc4random_uniform(UInt32(otherEntity.count)))
    driverSelection.text! = nameList[randomIndex]

}

}

What I am trying to do is to randomly pick an element from my core data and set it equal to the driverSelection textfield.
In my code I set the element at my coredata = to otherEntity. This made otherEntity a NSmanagedObject, but since the otherEntity is an NSmanagedObject, I am not able to use .count method. Is there a way that can make me able to randomly selected a element from NSmanagedObject???
Answer: Swift 5
I was looking for this answer and I figured out that you can get a row with fetchOffset and the array count with moc.count
like so...
func randomIconAK(_ moc: NSManagedObjectContext) -> Icon? {
  //
  //  RETURNS ONE ITEM AT RANDOM
  //
  let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Icon")

  if let fetchRequestCount = try? moc.count(for: fetchRequest) {
    fetchRequest.fetchOffset = Int.random(in: 0...fetchRequestCount)
  }

  fetchRequest.fetchLimit = 1

  var fetchResults: [Icon]?
  moc.performAndWait {
    fetchResults = try? fetchRequest.execute() as? [Icon]
  }

  if let wrapFetchResults = fetchResults {
    if wrapFetchResults.count > 0 {
      return wrapFetchResults.first
    } else {
      return nil
    }
  } else {
    return nil
  }
}//randomIconAK

Answer: If you are trying to pull a random index out of the current number of objects in the DB than you should use results.count not otherEntity.count like so:
    @IBAction func start(sender: UIButton) {
        setValues()
        let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
        let request = NSFetchRequest(entityName: "Entity")
        var results = [AnyObject]()

        do {
            results = try context.executeFetchRequest(request)

        } catch let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
        }
        let randomIndex = Int(arc4random_uniform(UInt32(results.count)))
        driverSelection.text! = nameList[randomIndex]

    }

Comment: please  accept the answer if this answered your question.
Comment: it does not work. It return me an error that says "cannot assign value of type "[AnyObject]" to type "[NSManagedObject]"
Comment: right sorry the result need to be of type  [AnyObject] instead of [NSManagedObject],  i fixed it.
Comment: Just one more question to ask. when I press the button "start" it return me that the index is out of range. Is it because it does not retrieve the element from my core data?
Comment: check your nameList is not empty. Even if the DB is empty randomIndex will be zero which is a valid index but if nameList is empty than you'll get out of bound exception.


Mumford's proof of theta function convergence

Question: On Dave Mumford's Tate Lectures on Theta I, he begins by proving that $\theta(z,\tau)$ converges. It begins something like:

Let $|Im(z)|<c$ and $Im(\tau)>\epsilon$, then:
$|e^{\pi i n^2 \tau + 2\pi inz}| < (e^{-\pi \epsilon })^{n^2} (e^{2\pi c})^{n}$

It is clear to me that $\displaystyle |e^{\pi i n^2 \tau + 2\pi inz}|=(e^{-\pi Im(\tau) })^{n^2} (e^{-2\pi Im(z)})^{n}$.
I understand the rest of the proof, assuming the inequality, but I don't get how he get's it in the first place. Thanks in advance for any help!
Comment: Are you missing an $i$ somewhere? Because $|e^{2\pi n z}|=e^{2\pi n \text{Re}\, z}$ (note the real part!), assuming $n$ real.
Comment: @mickep. I'm sorry, you are right. It's fixed now.
Answer: I'm not really sure what your issue is. Maybe this:
The function $R\ni x\mapsto e^{-x}$ is decreasing. Thus, since $\text{Im}\,\tau>\epsilon$ it holds that
$$
e^{-\pi\text{Im}\,\tau}<e^{-\pi\epsilon}.
$$
Also, since $\text{Im}\,z>-c$
$$
e^{-2\pi\text{Im}\,z}<e^{-2\pi(-c)}=e^{2\pi c}.
$$


Skipping acquire of configured file 'main/binary-i386/Packages' as repository 'xxx' doesn't support architecture 'i386'

Question: Getting below error message while issuing :
sudo apt-get update

Get:1 http://us.archive.ubuntu.com/ubuntu xenial InRelease [95.8 kB]
Ign:2 http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 InRelease
Ign:3 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:4 http://ppa.launchpad.net/canonical-x/vulkan/ubuntu xenial InRelease
Hit:5 http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.2 Release
Hit:6 http://us.archive.ubuntu.com/ubuntu xenial-security InRelease
Ign:7 http://dl.google.com/linux/talkplugin/deb stable InRelease
Hit:8 http://us.archive.ubuntu.com/ubuntu xenial-updates InRelease
Ign:9 http://linux.dropbox.com/ubuntu wily InRelease
Hit:10 http://ppa.launchpad.net/numix/ppa/ubuntu xenial InRelease
Get:12 http://dl.google.com/linux/chrome/deb stable Release [782 B]
Hit:13 http://dl.google.com/linux/talkplugin/deb stable Release
Ign:14 https://apt.dockerproject.org/repo ubuntu-wily InRelease
Hit:15 https://apt.dockerproject.org/repo ubuntu-wily Release
Get:16 http://dl.google.com/linux/chrome/deb stable Release.gpg [181 B]
Hit:17 http://linux.dropbox.com/ubuntu wily Release
Get:20 http://dl.google.com/linux/chrome/deb stable/main amd64 Packages [1,191 B]
Fetched 98.0 kB in 0s (118 kB/s)
Reading package lists... Done
N: Skipping acquire of configured file 'main/binary-i386/Packages' as repository 'http://dl.google.com/linux/chrome/deb stable InRelease' doesn't support architecture 'i386'

This cuts across various releases of ubuntu
Also seeing a similar glitch after enabling Ubuntu pro on my 22.04 ... now shows
sudo apt-get update
...
Reading package lists... Done
N: Skipping acquire of configured file 'main/binary-i386/Packages' as repository 'https://esm.ubuntu.com/realtime/ubuntu jammy InRelease' doesn't support architecture 'i386'

Comment: @Pilot6 (and others who voted for this question being off-topic): This is not specific to a particular Ubuntu version. It affects all users of Google Chrome on Ubuntu who have the Chrome repository enabled.
Comment: I can't see, why this should be a duplicate of the mentioned question. The source of the problem is the same, but the context is different (64 vs 32 bit).
Comment: @GunnarHjalmarsson what's the point of re-opening, since it's a dupe of http://askubuntu.com/questions/724093/no-more-updates-for-google-chrome-apt-get-update-error anyway?
Comment: Chrome repository?
Comment: @guntbert: I referred to Google's repository from where the updates are fetched.
Comment: @muru: Wasn't aware of that extensive answer to the other question. But then this is a duplicate, and not off-topic. OTOH, I guess it's useful to keep a question with the wording of the error message in the title, expecially since it shows up also on 64 bits installs.
Comment: @muru: Pasting the error message into Google just brought me here, and since I've already up-voted it, it's apparently not the first time. Whatever technicalities people may bring up about the validity of this question, it's obviously useful for many people… 194 and counting, at this point.
Comment: @MichaelScheper that is irrelevant, since you would have gotten redirected to the dupe otherwise.
Comment: Also see: https://stackoverflow.com/questions/61523447/skipping-acquire-of-configured-file-main-binary-i386-packages
Comment: For what it's worth this applies to more than just Chrome. I had the same issue with the repository for cloudflared.
Answer: I tracked down offending repo (any for Google chrome in this dir)
cd /etc/apt/sources.list.d
grep chrome * | grep -v amd64

or more generally
grep -r google  /etc/apt | grep -v amd64

Now do same as below for each repo file which matches above
cat /etc/apt/sources.list.d/google-chrome-unstable.list

### THIS FILE IS AUTOMATICALLY CONFIGURED ###
# You may comment out this entry, but any other modifications may be lost.
deb http://dl.google.com/linux/chrome/deb/ stable main

SOLUTION : limit to just 64 bit by introducing the [arch=amd64]
deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main

similar solution to fixing bug when upgrading to Ubuntu pro
cat /etc/apt/sources.list.d/ubuntu-realtime-kernel.list
#  original bad ... comment out next line
deb https://esm.ubuntu.com/realtime/ubuntu jammy main
#  fixed by adding [arch=amd64] to above line as per
deb [arch=amd64] https://esm.ubuntu.com/realtime/ubuntu jammy main

NOTE : If you are trying to apply this solution for another package which as a .list file containing a line similar to this :
deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared jammy main

The solution is to add the architecture flag inside the square brackets, separated from the other arguments with a space. Here is an example :
deb [arch=amd64 signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared jammy main

ROOT CAUSE : Google dropped support for 32-bit Chrome on Linux triggering an error when updating apt in 64-bit systems (with multi arch enabled) ...  details here : http://www.omgubuntu.co.uk/2016/03/fix-failed-to-fetch-google-chrome-apt-error-ubuntu
To confirm you are using 64 bit ubuntu with multiarch enabled issue
dpkg --print-foreign-architectures

if it says
i386

then you have added 32 bit support, this will list your native arch ... issue
dpkg --print-architecture

if you are native 64 you will see this output so do SOLUTION shown above
amd64

issue below to show packages using 32 bit
dpkg --get-selections | grep 386

Here is the command to remove multi architecture ( only if you have no 32 bit applications )
sudo dpkg --remove-architecture i386

Comment: This answer works very well (thank you!), however the file that needs to be edited (in your example /etc/apt/sources.list.d/google-chrome-unstable.list) is automatically configured on a regular basis, so the fix is written over and needs to be added over and over again. Any suggestions to overcome this?
Comment: I love the thoroughness of this answer. Good work. Thank you.
Comment: @EugenKonkov dpkg --get-selections | grep 386 might help
Comment: Cloudflared [https://pkg.cloudflare.com/index.html] introduces this issue on Ubuntu 22.04; love how well this was documented; thank you
Comment: This answer helped me fix what turned out to be the same issue for the Keybase package. I just made the same change in `/etc/apt/sources.list.d/keybase.list`, adding `[arch=amd64]` and that fixed the issue. _(I also applied the more permanent fix in Eric Mintz' solution - see my comment there.)_
Comment: How to list `i386` architectures?
Comment: I came here because I got the same error after installing brave-browser.  Your solution worked.
Comment: Still not working for me, great instructions, but ....
Comment: `/etc/apt/sources.list.d ❯❯❯ sudo dpkg --remove-architecture i386
Alias tip: _ dpkg --remove-architecture i386
dpkg: error: cannot remove architecture 'i386' currently in use by the database
`
Comment: I was getting this error w/ a different apt repo. This answer is particularly helpful because I wanted to know _why_ it happens as well as how to fix it. Now I know it's because of multi architecture, how to verify that, AND how to fix it.
Answer: (this solution is for Ubuntu Bionic Beaver)
First, shame on Google for letting this issue linger so long!!
Here's how to fix it:
As already mentioned above, editing files in /etc/apt/sources.list.d seems to work... but only temporarily. The next day, the problem is back.
Here's why:
The file /etc/cron.daily/google-earth-pro runs daily and overwrites what you have in /etc/apt/sources.list.d/google-earth-pro.list.
To fix it once and for all, edit /etc/cron.daily/google-earth-pro.
Find this line:
REPOCONFIG="deb http://dl.google.com/linux/earth/deb/ stable main"

...and change it to:
REPOCONFIG="deb [arch=amd64] http://dl.google.com/linux/earth/deb/ stable main"

Comment: For immediate change for Google Earth, it might be worth editing the files `google-earth-pro.list` and `google-earth-pro.list.save`.
Comment: Interesting, I did this AND the sources file still gets re-written.
Comment: `/etc/apt/sources.list.d/google.list` covers `google-chrome-stable`, `google-chrome-beta` and `google-chrome-unstable`. `cat /opt/google/chrome-beta/cron/google-chrome-beta | grep "REPOCONFIG="`. `cat /opt/google/chrome-unstable/cron/google-chrome-unstable | grep "REPOCONFIG="`. All three point to `stable`.
Comment: The line to change would be at LINE 24
Comment: Thank you. `[arch=amd64]` solved my problem with virtualbox 6.0
Comment: @AndorKiss Yes, that's what this cron job is doing. That's why this answer is here.
Comment: This answer helped me fix what turned out to be the same issue for the Keybase package. I edited `/etc/cron.daily/keybase` and edited the lines that include `REPOCONFIG` and `SSLREPOCONFIG` to include `[arch=amd64]`. _(Based on comments in that file, it looks like the Keybase team copied the Google Chrome package file that had this same issue and modified it.)_
Answer: Changing
deb http://dl.google.com/linux/chrome/deb/ stable main

to
deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main

in each of

/etc/apt/sources.list.d/google-musicmanager.list
/etc/apt/sources.list.d/google-musicmanager.list.save
/etc/apt/sources.list.d/google-musicmanager.list.distUpgrade

seems to fix the issue for Google Music Manager for Play Music too. Not sure if it will revert these changes at some point as the files are automatically configured.
Comment: for me file to change was `/etc/apt/sources.list.d/google.list`
Comment: ### THIS FILE IS AUTOMATICALLY CONFIGURED ###
# You may comment out this entry, but any other modifications may be lost.
Answer: Although Google has fixed this issue for Chrome, it still appears for e.g.  Google Earth.
Adding [arch=amd64] fixes the issue, but it needs to be added over and over again.
After making the file immutable as proposed by a webupd8 article and running into issues because of that, my current solution is to add a cronjob to apply the fix automatically once every hour:
~$ sudo crontab -e

0 * * * * sed -i 's/^deb http/deb [arch=amd64] http/' /etc/apt/sources.list.d/google-earth.list

(Replace google-earth.list if necessary).
Comment: [Sergio Rus](http://www.webupd8.org/2016/03/fix-failed-to-fetch-google-chrome_3.html#comment-2561557082) reckons that Google eventually fixed it for Chrome such that your one-time change would be preserved over updates.
Comment: Out of curiosity what keeps changing this file? In my experience, apt sources files don't get changed by themselves
Answer: Note that the above answers give accurate solutions for the ONE-LINE-STYLE format .list files; however, the verbose DEB822-STYLE FORMAT needs to use the full Architectures option instead of the abbreviated arch option to restrict the repo's packages to your desired architecture.
For example:
# /etc/apt/sources.list.d/apache-arrow.sources

Types: deb deb-src
URIs: https://apache.jfrog.io/artifactory/arrow/ubuntu/
Suites: focal
Components: main
Signed-By: /usr/share/keyrings/apache-arrow-apt-source.gpg
Architectures: amd64

Details on this option and others can be found with man sources.list
Answer: Though this question has been marked solved, I was unable to solve this issue with any of the above answers. I used an another method. Go to 'software & updates' > ubuntu software > download from > select best server. Now wait for some time for the system to find it out. Once this gets done, try your command again. This worked for me.
Comment: This worked for me as well! Nice!
Comment: Glad to know :)
Answer: I add my 2 cent. Sorry If I have a Debian 10 and not an Ubuntu, but my answer is in-topic.
I had the same problem due to mariadb repo. It was added to sources.list as
deb [arch=amd64,i386,ppc64el] http://ftp.nluug.nl/db/mariadb/repo/10.3/debian buster main

I simply removed i386 and ppc64el
deb [arch=amd64] http://ftp.nluug.nl/db/mariadb/repo/10.3/debian buster main

Answer: Even if this question is marked solved, for me, on Ubuntu 18.04, changed a line in /etc/apt/sources.list from    deb http://dl.google.com/linux/chrome/deb/ stable main
to deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main.
There was no file named /etc/apt/sources.list.d/google-chrome-unstable.list.
Making the same changes in /etc/apt/sources.list.d/google-chrome.list gave warnings saying that target package is configured multiple times. (in sources.list and google-chrome.list)
Answer: Change my source list
deb https://download.mono-project.com/repo/ubuntu stable-focal main

to
deb [arch=amd64] https://download.mono-project.com/repo/ubuntu stable-focal main


BIML Express applying one of the packages failed

Question: When you install Varigence BIML Express I get the error "applying one of the packages failed".
Answer: If you run the installation as administrator the problem goes away.


disable a button based on variable value

Question: I'm trying to figure out as why the button does not get disabled after the this.submitted changes to true. The this.submittedis False by default, once the user clicks on the submit button, it calls the onSubmit() component's method and this.submitted is changed to true as part of the data submitting procedure. And this is when the button should switch to disabled state, however it does not.
login.component.html

        <form class="form-signin" [formGroup]="loginForm" (keyup.enter)="onSubmit()" (ngSubmit)="onSubmit()">

            <input type="text" placeholder="Username" class="form-control" formControlName="username" name="username"
             maxlength="20" required="" autofocus="">

              {{ formErrors.username }}

            <input type="password" placeholder="Password" class="form-control" formControlName="password"
            name="password" maxlength="20" required="" autofocus="">

              {{ formErrors.password }}

          <button type="submit" class="btn btn-lg btn-primary btn-block"
              [disabled]="!loginForm.valid" > Sign in
          </button>

        </form>
        I can't access my account

            OR

                    <button [disabled]="submited" (click)="signup($event)" class="btn btn-lg btn-primary btn-block">Create New Account</button>

              News
              Updates
              Events

For the sake of simplicity I have removed the form validation from the below ts file.
login.component.ts
import { Component, OnInit }                    from '@angular/core';
import { Router }                               from '@angular/router';
import { LoginService }                         from '../services/login.service';
import { User }                                 from '../classes/interfaces/user.interface';

@Component({
  moduleId: module.id,
  selector: 'login-panel',
  templateUrl: '../templates/login.component.html',
  styleUrls: [ '../styles/login.component.css' ],
  providers: [ LoginService ]
})
export class LoginComponent implements OnInit {

  public submitted:boolean = false;
  public loginForm: FormGroup;

  constructor(
    private router: Router,
    private loginService: LoginService,
    private fb: FormBuilder
  ) {}

  ngOnInit(): void {
    this.buildForm();
  }

  public onSubmit(): void {
    if ( ! this.submitted ) {
      this.submitted = true;
      this.loginUser( this.loginForm.value );
    }
  }

  private loginUser( user: User ){
    if ( this.loginForm.valid ) {
      //console.log( user )
      this.loginService.login( user ).then( (token) => {
        localStorage.setItem('id_token', token.id);
        this.router.navigate(['home']);
      }).catch( (error) => this.onLoginFailed(error) );
    }
  }

  private onLoginFailed( error: any ): void {
    this.submitted = false; /// make form submitable again ///
  }

  public signup( event: any ): void {
    event.preventDefault();
    this.router.navigate(['signup']);
  }

}

Comment: Your variable is called `submitted` (2 t's) instead of `submited` (one t)
Comment: "facepalm" good spot :)
Answer: You have a typo, as pointed out by devqon:
<button [disabled]="submited" (click)="signup($event)" class="btn btn-lg btn-primary btn-block">Create New Account</button>

You need to change your code to:
<button [disabled]="submitted" (click)="signup($event)" class="btn btn-lg btn-primary btn-block">Create New Account</button>


display part of an image and hide the rest using CCScene

Question: ok so i have the following code :
CCScene * timerLayer = [CCScene node];
[timerLayer setContentSize:CGSizeMake(50, 36)];
timerLayer.position = ccp(100, 260);
if(![self getChildByTag:777]){
    [self addChild:timerLayer z:20 tag:777];
}

timerGraphic = [CCSprite spriteWithFile:@"timer_small.png"];
timerGraphic.position = ccp(0,0);
timerLayer.contentSize = CGSizeMake(50, 36);

if(![timerLayer getChildByTag:779]){
    [timerLayer addChild:timerGraphic z:19 tag:779];
}

as you can see, I am making a timerLayer Scene, and I have resized the the scene to 50x, 36y. and I also have timerGraphic, and I just want to show 50x 36y of this sprite so i tried resizing the scene, but its not working... its showing the entire image all together!
Answer: The CCScene node can not be used to clip images. You can either use a Clipping Node or in your case simply change the texture rect to only display that part of the image that's inside the rectangle:
[timerGraphic setTextureRect:CGRectMake(0, 0, 50, 36)];

Note: be sure that the rect is within the image's bounds!
Comment: you could overlay a "round corner" image
Comment: thanks alot, do you know how I can make the corners round? is that possible?


I can not find my.cnf on my windows computer

Question: My computer is Windows XP.
I need to find my.cnf to get all privileges back to the root user. I accidentally removed some privileges of the root user. I still have the password and there is no problem for me to log in to MySQL as the root user. But I can not alter a table.
Answer: Here is my answer:

Win+R (shortcut for 'run'), type services.msc, Enter
You should find an entry like 'MySQL56', right click on it, select properties
You should see something like "D:/Program Files/MySQL/MySQL Server 5.6/bin\mysqld" --defaults-file="D:\ProgramData\MySQL\MySQL Server 5.6\my.ini" MySQL56

Full answer here:
https://stackoverflow.com/a/20136523/1316649
Comment: what happens if mysql is not running as a service? where is the my.ini located? I can see my-default.ini on C:\Program Files\MySQL\MySQL Server 5.6 but I don't know if the server is using it.
Comment: @PabloPazos Same question, what happens if we run it *not as a service*, but rather from cmdline: `mysqld --console`?
Answer: To answer your question, on Windows, the my.cnf file may be called my.ini.  MySQL looks for it in the following locations (in this order):

%PROGRAMDATA%\MySQL\MySQL Server 5.7\my.ini, %PROGRAMDATA%\MySQL\MySQL Server 5.7\my.cnf
%WINDIR%\my.ini, %WINDIR%\my.cnf
C:\my.ini, C:\my.cnf
INSTALLDIR\my.ini, INSTALLDIR\my.cnf

See also http://dev.mysql.com/doc/refman/5.7/en/option-files.html
Then you can edit the config file and add an entry like this:
[mysqld]
skip-grant-tables

Then restart the MySQL Service and you can log in and do what you need to do.  Of course you want to disable that entry in the config file as soon as possible!
See also http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html
Comment: For me it was: `C:\ProgramData\MySQL\MySQL Server 5.5\my.ini`
Comment: I am using xampp and mine is found in C:\xampp\mysql\bin\my.ini
Answer: Windows 7 location is: C:\Users\All Users\MySQL\MySQL Server 5.5\my.ini
For XP may be: C:\Documents and Settings\All Users\MySQL\MySQL Server 5.5\my.ini
At the tops of these files are comments defining where my.cnf can be found.
Comment: good one, i check it in Win8 also: " C:\Users\All Users\MySQL\MySQL Server 5.6 "
Answer: You can find the basedir (and within maybe your my.cnf) if you do the following query in your mysql-Client (e.g. phpmyadmin)
SHOW VARIABLES

Answer: you can search this file : resetroot.bat
just double click it so that your root accout will be reset and all the privileges are turned into YES
Answer: Start->Search->For Files and Folders->All Files and Folders
type "my.cnf" and hit search.


App installation data (from google play and apple store)

Question: As part of a project in my workplace -
I'm searching the web for a way to get the daily installations per device
(note that the data from google analytics is irrelevant for us as they give back the
amount of installations and not installations per device -
in case a user installs, removes and installs the app again they regard it as 2 installations while google play developer console display this as 1 installation).
So far I found out that the google play developer console contains the data we need,
but the only way I could get that data is by manually downloading a csv file and parsing it.
This is not good enough for us as we MUST automate the download process and get that data without any human.
I'll note that we are using .net technology and from what I've red we can't get that data with the
beta API library which google supplies for the google play developer console.
P.S. we have to do the same with the apple app store
P.S. 2 we can't use a 3rd party code/service
Any help would be greatly appreciated.
Answer: I think it's too late now, but maybe it can help someone else.
Google Play Store:
First of all, you need GCP account
"Reports are available from Google Cloud Storage. Reports are generated daily and accumulated in monthly CSV files. They are stored in a private Google Cloud Storage bucket for your Google Play Developer account."
Second point, you need bucket ID
"Find your reporting bucket ID on one of your Download reports pages, near the bottom of the page.
Your bucket ID begins with: pubsite_prod_rev (Example: pubsite_prod_rev_01234567890987654321)."
and you can follow the steps below
Step 1: Create a service account
Sign in to the Google Developers Console (console.developers.google.com).
If you already have a project, use the drop-down to select a project. If you don't have a project listed or want to create a new one, click Create project.
Select the Menu icon Menu icon > Permissions > Service accounts > Create service account.
Follow the on-screen instructions and select Create.
Copy the email address listed.
Example: firstname.lastname@example.com
Step 2: Add the service account on your Play Console
Sign in to your Play Console.
Select Settings Settings > User accounts & rights > Invite new user.
Paste or type the email address associated with your service account.
Based on the types of reports needed, select permissions.
For example, if you need access to financial reports, select "View financial reports."
Click Add user. Your service account will be added to your account.
Step 3: Fetch reports using an API call
Install the API client library for your preferred code language.
Configure the code performing the API call to use OAuth2 server-to-server authentication and to request permission to the OAuth2 scope (https://www.googleapis.com/auth/devstorage.read_only).
Issue authenticated API calls to fetch reports.
To learn more, follow link: https://developers.google.com/api-client-library/
More information here: https://support.google.com/googleplay/android-developer/answer/6135870
Answer: Google Developer console provides two options. 1) number of downloads. 2) No of total devices currently using your app..
I hope 2nd option will help you in the case..
Or you can also ask user for one time registration
Comment: Thanks, but what I need is to automate the process of getting the 2nd option's data - I'm already getting it manually.
Comment: @GrizzlyMcBear, I have a similar requirement, will it be possible to share some details on how you are able to get the installation details via automated process - TIA


Add field to $map entry in MongoDB

Question: I have MongoDB collection items with following document:
{
    "values": [
        { "number1": 5, "number2": 6, "anotherProp": "...", "anotherProp2": "..." },
        { "number1": 8, "number2": 1, "anotherProp": "...", "anotherProp2": "..." }
    ]
}

Is there any way to add sum property to each item of values (sum = number1 + number2)? I would like to avoid naming all other properties (number1, number2, anotherProp, anotherProp2, ...), only add new one (sum). My current solution is:
db.items.aggregate([{
    $project: {
        values: {
            $map: {
                input: "$values",
                as: "v",
                in: {
                    sum: {$add: ["$$v.number1", "$$v.number2"]},
                    number1: "$$v.number1", // This and next 3 lines I would like to omit.
                    number2: "$$v.number2",
                    anotherProp: "$$v.anotherProp",
                    anotherProp2: "$$v.anotherProp2"
                }
            }
        }
    }
}])

Desired result is:
{
    "values": [
        { "number1": 5, "number2": 6, "anotherProp": "...", "anotherProp2": "...", "sum": 11 },
        { "number1": 8, "number2": 1, "anotherProp": "...", "anotherProp2": "...", "sum": 9 }
    ]
}

Is there any way to do this? I tried use $addFields instead of $project, however result is same.
Answer: Yes, you can use $mergeObjects
db.collection.aggregate([
  {
    $project: {
      values: {
        $map: {
          input: "$values",
          as: "v",
          in: {
            "$mergeObjects": [
              {
                sum: {
                  $add: [
                    "$$v.number1",
                    "$$v.number2"
                  ]
                }
              },
              "$$v"
            ]
          }
        }
      }
    }
  }
])

MongoPlayground

Add field to $map entry in MongoDB


How to add cursor and activate my editText?

Question: Actually I am creating a custom EditText in my android application.
What I have done is that I have created a class called CustomEditText, in which I am drawing my EditText. Its code as follows:
public class CustomEditText extends View {

String mText;
Context mContext;
Paint paint = new Paint();

public CustomEditText(Context context) {
    super(context);
    mContext = context;
    paint.setColor(Color.WHITE); // You could setup the background etc here
    paint.setStyle(Style.FILL);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    drawTextOnCanvas(canvas, mText);
}

private void drawTextOnCanvas(final Canvas canvas, String mText) {
    canvas.drawPaint(paint);

    final EditText editText = new EditText(mContext);
    editText.setTextColor(BLACK);
    editText.setEnabled(true);

    editText.setDrawingCacheEnabled(true);
    editText.measure(MeasureSpec.makeMeasureSpec(canvas.getWidth(), MeasureSpec.EXACTLY), 50);

    editText.layout(0, 0, editText.getMeasuredWidth(), editText.getMeasuredHeight());

    canvas.drawBitmap(editText.getDrawingCache(), 0, 0, paint);
    editText.setDrawingCacheEnabled(false);
}

and this class is being called in the MainActivity using the following code:
    CustomEditText editText = new CustomEditText(this);
    setContentView(editText);

What should I be doing next to add a cursor and make this CustomEditText act like normal editText( which means that it should be able to accept, select and clear input text ).
Comment: You mean to show the keyboard?
Comment: merely showing keyboard is easy, it can be done via manifest.
But what I want is to implement it like a normal edittext
Comment: I just checked your checked, what is the mText you are passing to `drawTextOnCanvas ` and where are you using it?
Comment: In your github code you are only adding `height`, not `width`
Answer: If your drawTextOnCanvas() is working properly, just making your CustomEditText extend EditText should work. (instead of view)
If I understand your comment correctly, you just have to do this :
public class CustomEditText extends EditText {

   Context mContext;
   Paint paint;
   EditText editText;

   @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
   public CustomEditText(Context context) {
      super(context);
      paint = new Paint();
      editText = new EditText(context);
      mContext = context;
      paint.setColor(Color.GREEN);
      paint.setStyle(Paint.Style.FILL);

  }

  @Override
  protected void onDraw(Canvas canvas) {
     canvas.drawPaint(paint);
     super.onDraw(canvas);
  }
}

Comment: I guess there is something wrong with your `drawTextOnCanvas()`, i just copied your code and commented  `drawTextOnCanvas(canvas, mText);` it works fine(because of `super.ondraw()`).
Comment: so what should I be doing .. remove the input parameters
Comment: So your class is customized only in terms `color` and `style` right? Other than that you want it to act it like a normal `Edittext` right?
Comment: Hey @karthik I removed `String mText` from it, and now its working but whatever I am typing is not being shown. Its just blank.....
Comment: Yes I saw that, what is the API version you are targeting?
Comment: My API version is 19 and above
Comment: Then check my answer, that will work. `paint.setStyle(Paint.Style.FILL);
` only works for after 17, that's why I was asking. Just use the class in my answer.
Comment: its working thanks for the help, but just one last thing ... how to adjust its size.... like for the width n height of editText
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/82773/discussion-between-karthik-and-aditya-prasun).
Comment: You can just use `editext.setWidth()` and `editext.setWidth()` (Set it in constructor if you don't have to change it again)
Comment: have already tried it at both locations but still of no help..... in the constructor and mainActivity when I am calling it
Comment: You must be doing something wrong, can you show your code?


Mdbg: unable to detach from process

Question: We are using MDBG to attach to IIS worker processes.
After performing stack snapshots, we detach with MDBgProcess.Detach().
While this call normally takes 10-80ms, occassionally it hangs for a very long time, also freezing the process in the meantime.
This is unacceptable since the process is a production program.
Here is our complete code:
try
{
    proc.AsyncStop();
}
finally
{
    // Make sure we are able to detach
    try
    {
        // delete all breakpoints
        proc.Breakpoints.DeleteAll();
    }
    catch (Exception e){}
    finally
    {
        // detach and wait
        var waitHandle = proc.Detach();
        if (proc.CanExecute())
        {
            waitHandle.WaitOne();
        }
    }
}

Any ideas why this may happen, and what we can do about it?
Best,
Mike
Answer: I don't know why it would hang up, but I think you potentially have a race condition - in my program, I block until the process is stopped using the WaitOne() on the Stop()...
proc.AsyncStop().WaitOne();
m_Debugger.Processes.Active.Breakpoints.DeleteAll();
proc.CorProcess.Detach(); // I don't wait here because this is where my prog ends

Mdbg: unable to detach from process


Does a Java Swing Window (in Fullscreen) affect the HDMI output of a Raspberry Pi 3?

Question: The simple Problem: i have a RaspPi3 hooked to a TV (via HDMI) and on that a java Swing application in fullscreen (remote client to show simple text as a slide show). The TV, however, goes into standby after ~60 seconds, but only if my app is running. If i simply display the desktop the TV just stays alive.
The Question is: does a fullscreen swing app mess with the HDMI signal, so that the TV thinks there is nothing more to show and shuts down? (Or is there something wrong with the way i approach the function of displaying text? See code below*)
Or is it a problem with the TV because the signal stays the same and doesnt change or isn't strong enough over ~60 seconds (too much "blank" space because the screen is mostly black)?
Note: My app does work as intended on a pure functionally basis. This standby behavior is a "bug" that i did not expect.
I don't have that deep insight of the HDMI spec, so if anyone could give me a hint on how to solve this problem, i would appreciate it.
This is my first question and i decided to ask it because i didnt found any similar problem to mine. I am not entirely sure if this question is to specific, so i apologize in advance if it is.
*Code:
<code>public GUIController()
    {
        Statics.GUIC = this;
        jf = new JFrame("SP-MultiMonitor@arm " + Statics.VERSION_INFOS);
        jf.setUndecorated((Statics.PROPERTIES.getProperty("p.undecorated").equals("true")));
        jf.setAlwaysOnTop(true);
        jf.setLocation(Integer.parseInt(Statics.PROPERTIES.getProperty("p.pos.x")), Integer.parseInt(Statics.PROPERTIES.getProperty("p.pos.y")));
        jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        Container cp = jf.getContentPane();
        MyCanvas tl = new MyCanvas();
        tl.setBackground(Color.BLACK);
        cp.add(tl);
        cp.setBackground(Color.BLACK);
        jf.setSize(Integer.parseInt(Statics.PROPERTIES.getProperty("p.width")), Integer.parseInt(Statics.PROPERTIES.getProperty("p.height")));
        jf.setVisible(true);
        t = 0;

        timer = new Timer(100, new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
                //check cmd
                switch (Statics.PRESENTATION_CMD)
                {

                    case Statics.REND_CMD_EMPTY:

                        Statics.PRESENTATION_CMD = Statics.REND_CMD_RUN;
                        break;

                    case Statics.REND_CMD_RUN:
                        break;

                    case Statics.REND_CMD_START:
                        tl.repaint();
                        Statics.PRESENTATION_CMD = Statics.REND_CMD_RUN;
                        break;

                    case Statics.REND_CMD_STOP:
                        Statics.PRESENTATION_CMD_ADD = null;
                        tl.repaint();
                        Statics.PRESENTATION_CMD = Statics.REND_CMD_EMPTY;
                        break;

                    case Statics.REND_CMD_NEXT:

                        Statics.PRESENTATION_CMD = Statics.REND_CMD_RUN;
                        break;

                    case Statics.REND_CMD_PREV:

                        Statics.PRESENTATION_CMD = Statics.REND_CMD_RUN;
                        break;

                    case Statics.REND_CMD_GOTO:

                        Statics.PRESENTATION_CMD = Statics.REND_CMD_RUN;
                        break;
                }
            }
        });

        jf.addWindowListener(new WindowListener()
        {
            @Override
            public void windowOpened(WindowEvent e)
            {
            }

            @Override
            public void windowClosing(WindowEvent e)
            {
                timer.stop();
            }

            @Override
            public void windowClosed(WindowEvent e)
            {
            }

            @Override
            public void windowIconified(WindowEvent e)
            {
            }

            @Override
            public void windowDeiconified(WindowEvent e)
            {
            }

            @Override
            public void windowActivated(WindowEvent e)
            {
            }

            @Override
            public void windowDeactivated(WindowEvent e)
            {
            }
        });
        timer.setInitialDelay(1000);
        timer.start();
    }

    public void toggleVisibility()
    {
        jf.setVisible(!jf.isVisible());
    }
}

class MyCanvas extends JComponent
{

    int fontSize = 50;
    Font font = new Font("Calibri", Font.PLAIN, fontSize);

    @Override
    public void paintComponent(Graphics g)
    {
        if (g instanceof Graphics2D)
        {
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            if (Statics.PRESENTATION_CMD_ADD == null && Connection.getInstance().hasConnected())
            {
                g2.setColor(Color.GREEN);
                g2.setFont(font);

                g2.drawString("connected", 50, 50);
                return;
            }
            else if (Statics.PRESENTATION_CMD_ADD == null)
            {

                g2.setColor(Color.GREEN);
                g2.setFont(font);

                g2.drawString("not connected", 50, 50);
                return;
            }

            String[] content = Statics.PRESENTATION_CMD_ADD.split(Statics.STRING_LIMITER_HASH);

            g2.setColor(Color.WHITE);
            g2.setFont(font);
            for (int i = 0; i < content.length; i++)
            {
                g2.drawString(content[i], 50, fontSize + fontSize * i + 10);
            }
        }
    }
}
</code>
Answer: I don't have enough reputation yet to comment, so will need to post as an answer.
I've not even looked at your code but i was having a similar issue when working on the Pi a while back, i was displaying video with image overlays(digital signage). When i went full screen i would get a flicker of the image before the screen would go black and eventually time out and the screen would go to standby.
It turned out to be an issue with the hdmi buffer or something. I never actually solved my issue, i think i just hit the limits of the raspberry pi.
What did work was turning down the resolution.  in config.txt on the sd card image i think i changed hdmi mode to 34, this gave me 1920x1280p at 30hz and opposed to 60hz, essentially doubling the buffer. There was a slight loss in quality but barely noticeable.
Sorry i can't be more help, just thought i'd add my 2cents in case it nudges you in the right direction.


Creating a callback handler to notify multiple listeners in Android

Question: I have an Android application that interfaces 3rd party hardware through a vendor-supplied library. When data from the hardware is ready to be processed, the library calls back to my application.
The 3rd party library, due to it's design, only makes one callback to the application. However, my app has a few different asynchronous tasks that it would like to do when the callback is called (for example, logging, update the UI display, call external programs). Trying to fan out the event, in a way, to different methods. So, I'm thinking about doing this in my Application class:
interface MyCallback {
    public void doSomething(ArrayList<DataClass>);
}

public class MyApp extends Application {
...
private MyCallback cb;
public void registerCallback (MyCallback callback) {
    cb = callback;
}

public methodCalledBy3rdPartyAPIOnData (ArrayList<DataClass> data){
    cb.doSomething(ArrayList<DataClass> data);
}

which would work for a single method to call, but I'm having an issue on how to do this for a series of callbacks...and making sure they get called asynchronously. Are there any examples or best practices for doing this sort of thing in an Android application, or in Java in general?
Answer: I would use a slightly adapted Observer Pattern (the adaptation is notifying each observer in a new thread):
Your callback handler is the subject (i.e., being observed):
public class Subject {
    private List<Observer> observers = new ArrayList<>();

    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    public void notifyObservers(final Object data) {
        for (final Observer observer : observers) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    observer.notify(data);
                }
            }).start();
        }
    }

    public methodCalledBy3rdPartyAPIOnData (ArrayList<DataClass> data){
        notifyObservers((Object)data);
    }
}

And each of the real handlers needs to implement the following interface
public interface Observer {
    public void notify(Object data);
}

And register itself by calling subject.registerObserver(this).
Comment: Observer is good, but you're missing an unregisterObserver. This might be desirable if the OP's notifying class "stays around" (say, is a singleton), and the multiple observers might be non-static members of instances of Activities, say. To avoid leaky-ness, such as keeping the entire view stack around in a singleton that exceeds the life of the activity, the activity would want to unregister listening onPause or similar.
Comment: @Tom You're right, but I wanted to show the bare minimal. Should've mentioned that, though.
Comment: I'm guessing for the unregisterObserver method, a simple `observers.remove(observer)` is all that's needed? There will be at max 5-6 items in the `ArrayList`, and hopefully not called often, either, so performance isn't a big issue.


Simplifying Roots and Trigonometric Identities

Question: I have a bunch of sympy expressions similar to
g = sp.sympify('2**(1/4) * 5**(1/2) * 3**(3/4) * 6**(-1)')

which I want to simplify. In this case, I would very much prefer this rewritten as (25/24)**(1/4), but I couldn't find settings for simplify or the other methods listed here that would let me do this.
So what I want is given a bunch of natural numbers a_i and rational exponents (p_i/q_i), I want the product
a1**(p1/q1) * a2**(p2/q2) * ... * ak**(pk/qk)

to be rewritten as
(r/s)**(1/lcm(q1,q2,...,qk))

or possibly
(r1**s1 * r2**s2 *... rm**sm)**(1/lcm(q1,q2,...,qk))

where the r_i are the prime factors and the s_i are integers. Do any of the built in functions allow me to do that?
Secondly, I noted that Sympy won't simplify certain trigonometric identities. For example it doesn't seem to know that
tan((1/2)*atan(x)) = (sqrt(x**2 + 1)-1)/x

How can I tell Sympy to use this identity, even if x is a much more complicated?
Answer: Try this:
def simplify_root(g):
    d = sp.degree(sp.minimal_polynomial(g))
    return sp.Pow(sp.simplify(g**d), sp.Rational(1, d), evaluate=False)


SQL values for min and max rows in one row

Question: I have a table with price changes and I need to get initial price and latest price.
In other words I want to display price values for min(StartDate) and max(StartDate) in one row for each product.
Table structure is simple:
ProductID, StartDate, Price

Desired result is
ProductId, StartDate, InitialPrice, LatestDate, LatestPrice

Comment: Does MS SQL Server have a GREATEST() function?  If so, use it, and the matching LEAST() which it would presumably also have.
Answer: WITH latestPrice AS
(
   SELECT ProductID, StartDate, Price,
          ROW_NUMBER() OVER (PArtition BY ProductID ORDER BY StartDate DESC) rn
   FROM TableName
)
, initalPrice AS
(
  SELECT ProductID, StartDate, Price,
         ROW_NUMBER() OVER (PArtition BY ProductID ORDER BY StartDate ASC) rn
  FROM TableName
)
SELECT  a.ProductID,
        b.StartDate,
        b.Price InitalPrice,
        c.StartDate LatestDate,
        c.Price LatestPrice
FROM    (SELECT DISTINCT ProductID FROM tableName) a
        INNER JOIN initalPrice b
          ON a.ProductID = b.ProductID AND b.rn = 1
        INNER JOIN latestprice c
          ON a.ProductID = c.ProductID AND c.rn = 1

SQLFiddle Demo
Comment: @MitchWheat thanks, actually this is my first trial, i've been browsing on sql server docs to find some built-in function to make the query shorter `:D`
Comment: @JW Thanks, it seems to be working but it's quite complex for me to digest. First time seeing WITH and PARTITION BY. However I also came up with this, what do you think? `SELECT id1, id2, MIN(date1), MAX(date2) FROM
(
  SELECT ProductID id1, MIN(StartDate) date1, Price p1
  FROM TableName
  GROUP BY ProductID, Price
) A
INNER JOIN
(
  SELECT ProductID id2, MAX(StartDate) date2, Price p2
  FROM TableName
  GROUP BY ProductID, Price
) B

ON B.id2 = A.id1
GROUP BY id1, id2`
Comment: the `WITH` you see is called `Common Table Expression`. `Partition By`, searched for `Window Function`. `:D`
Answer: (SELECT x.ProductId, x.MinStartDate, x.MinPrice, y.MaxStartDate, y.MaxPrice FROM (SELECT a.ProductId, a.MinStartDate, b.Price AS MinPrice FROM (SELECT ProductId, MIN(StartDate) AS MinStartDate FROM Products GROUP BY ProductId) a INNER JOIN Products b ON a.ProductId = b.ProductId AND a.MinStartDate = b.StartDate) x INNER JOIN (SELECT a.ProductId, a.MaxStartDate, b.Price AS MaxPrice FROM (SELECT ProductId, MAX(StartDate) AS MaxStartDate FROM Products GROUP BY ProductId) a INNER JOIN Products b ON a.ProductId = b.ProductId AND a.MaxStartDate = b.StartDate) y ON x.ProductId = y.ProductId

DISCLAIMER: This is from memory so I apologize if this is not entirely accurate. And it assumes that the StartDate is a datetime or is not repeated for each productId.
Hope this helps.


Where can I farm gadgets?

Question: I need simple gadgets to upgrade Pods B & C, and I believe I'll need complex and elaborate ones to further upgrade them.  I've gotten all the main endings, completed all quests except for three (9S's unit recon, and two others I haven't seen appear yet).  Is there a place / boss enemy I can fight that has a good chance of finding them?  Does the Item Drop chip help at all?
Answer: I, too, ended up needing simple gadgets to finish upgrading the Pods. I basically followed the farming route in this video:

Essentially, all you do is teleport to the access point near where you first started the game in the City Ruins. Run up the stairs to the 6th or 7th floor and there will be a harvest spot if you run out of the building wall and jump back in (circumvent the wall by going around it outside the building). If you have the chip that allows you to suck in nearby items, you can grab it through the wall. Simply rinse and repeat and you'll get 10 simple gadgets within an hour or so.
Comment: Awesome, I'll try this tonight.  Also, are we the only two on this site that play this game?
Comment: @Andy nah, there are others. But it's like, my favorite game ever, so I answer the questions as soon as I see them
Comment: I'm not on SE very often anymore, but I just logged in to upvote and confirm that this is still useful to someone!

Where can I farm gadgets?


Too many re-renders. React limits the number of renders to prevent an infinite loop when I trying to change the state

Question: I have a react component
import React, {useState} from 'react';

function App() {
  const [number, setNumber] = useState(12);

  return (
    <>

Number value is: {number}

 setNumber(number + 1)}>Add

Sub

    </>
  );
}

export default App;

When I change change number using onClick = {() => setNumber(number + 1)} everything is ok but when I use onClick = {setNumber(number - 1)} I've got an error

Error: Too many re-renders. React limits the number of renders to
prevent an infinite loop.

Explain to me please why I've got an error and what difference between these callings? Thanks in advance.
Answer: onClick = {() => setNumber(number + 1)} This creates a function, that will be called on click event.
onClick = {setNumber(number - 1)} Here you call function right now, in process of creation App object. That results to setState => reRender => calling again, so infinite loop.
Answer: Passing the setNumber function to onClick actually runs it causing a re-render everytime the div is rendered.
Passing it as a arrow function, passes the function object without executing it, until the onClick method is called.
https://reactjs.org/docs/handling-events.html
Answer: Just do what you did for your addition in your substraction.
With your current syntax in the substraction, your set state is gonna be called infinitely because you are calling the function directly, you need a function returning this function like you did for your addition.
Comment: I've got but I want to understand the difference between these two methods


What degree do I make bevel cut to form a 28ft ring with 2x4s

Question: I'm trying to make this circle for my pool to put 3" of sand in it
Comment: Hello, and welcome to Stack Exchange. How many boards will your (mostly) circle have?
Answer: You can't figure this out without knowing how many boards your circle will have; once you choose the number of boards, just divide 360 by the number of bevels (one for each end of each board) and that's how far from 90° each end should be.
So, if you have 4 boards (a square):

4 * 2 = 8 bevelled ends
360° / 8 = 45°
each end should have a 45° bevel on it:

If you have 20 boards:

20 * 2 = 40 bevelled ends
360° / 40 = 9°
each end should have a 9° bevel on it, so each end should be cut 9° from perpendicular:

A couple of possible optimizations:

When you're cutting a board to length with a (say) 9° bevel, you automatically create a second end with a 9° bevel in the opposite direction. So, flip the board over and then cut THAT board to length with the 9° bevel. Bingo: half as many cuts.
Another alternative would be to leave one end of each board square (what I'm calling a 0° bevel), and then cut the other ends at twice the angle calculated above. Depending on the situation, this may mean less work.

(Just to be clear: what I'm calling a 9° bevel will result in a board whose end is cut almost perpendicular to the sides, not a board with an extremely sharp point on the end. Here's a page with more math for your calculations.)
Comment: I could add to this good answer that the bevel for 20 boards will apply to any length boards. Just make certain that all the boards are the same length.
Comment: If you do decide to go with 20 boards to make the 28' diameter circle you will need to make each board about 4' 5 3/16" length on the outside (long side). If you want to make a more rounded circle of course more boards would be required. For example of you chose to go with 36 boards the bevel would be 360 / (2 * 36) = 0.5°. The outside length for 36 boards would be 2' 5 3/8". This latter choice would leave little waste if starting with 8' boards. The 20 sided design would require starting with 10' boards and there would be over a foot of waste from each board if cutting two per board.


Do the different colored rocks in the mines have different drop chances?

Question: Some rocks in the mines are grey, some are red, some are different shapes? Obviously they are there for the sake of variety, but are some more valuable than others? Are red rocks more likely to drop coal for example? (I am not referencing rocks that have minerals obviously sticking out of them.)
Comment: There's a grey one that always seems to drop stone. That's all I've noticed.
Comment: The different colours also take a different amount of hits before breaking them, so it is not just for variety.
Answer: The grey rocks only loot normal rock, atleast they do before the last patch, I didn't play enough to secure that in the actually patch do the same. On my mine time, which it is a lot, the different colours rock can give you: rocks, geodes, coal or "normal" ores like copper, gold or metal. Also, the different colours means what type of geodes can you get. On the first levels on the mines you can get "Geode" on the coloured rock and with the red rock on the finals levels can loot you the red geode. As far I played, all the coloured rocks have a chance to also loot Omni Geode. A coloured rocks never can loot minerals but monster or The Quarry, when you "repair" the bridge on the community center, can do. But on the mines, yes, different colours means different loot.
Comment: Sources? Proof? Just stating your feelings aren't considered reliable...
Comment: My proof is around 50 hours playing and I get the same result as I answer. On the wiki there is no such information but when you go around 20 days to the mines without stop to harvest the crop, you will know what rocks do you wanna detroy to farm geodes.
Answer: It is more based on the items. For example 1 in 500 could be a diamond. The colors matter not.
Comment: This is simply not true
Answer: No, the rocks doesn't have different drop chances.
Comment: The rocks do have different loot tables.


For loop that takes in inputs for different items sold, calculates a total based on various prices, and prints the quantity and total at the end

Question: So for my python class, we've been instructed to create a for loop that will ask the user to input a quantity of an item sold, where the string literal is supposed to be "Quantity of item 1: " and so on, for a total of 5 different items. Then it calculates the price of the item * the quantity and comes up with a total for each SEPERATE  item. The gimmick is that we can't use lists and it HAS to be a for loop. The professor also gave us a hint that we'll be using if/else/elif statements.
The code I've come up with so far is
for x in range(1,6):
    quantity = int(input("quantity of item " +str(x)+ " : "))
    if x == 1:
        total = quantity * 2.50
    elif x == 2:
        total = quantity * 1.98
    elif x == 3:
        total = quantity * 5.75
    elif x == 4:
        total = quantity * 3.45
    elif x == 5:
        total = quantity * 4
print(quantity)

The problem with this code is that it only prints the totals of the last elif statement. I'm trying to refrain from making too many variables as that would defeat the purpose of the loop.
Comment: why not just move the print statement inside the for loop?
Comment: all youre doing is printing the last int assigned to quantity
Comment: I moved it to the outside of the for loop because the program has to print out everything at the very end.
Comment: @JackDegennaro You should have specified the desired end result. I changed my answer accordingly.
Answer: Hi and welcome to Stack Overflow!
Probably what you're missing is that = operator override whatever was in that variable before, so everytime you do total = something, total gets overridden to something.
Probably what you want to use is +=, which will add to total what you want.
Answer: You want to use += rather than just = because = overwrites what was previously in the variable when you want to keep the total sum.
You also made a mistake with the print statement. Presumably you want the total, but the variable you have in the print is quantity.
See the working code below.
total = 0
for x in range(1,6):
    quantity = int(input("quantity of item " +str(x)+ " : "))
    if x == 1:
        total += quantity * 2.50
    elif x == 2:
        total += quantity * 1.98
    elif x == 3:
        total += quantity * 5.75
    elif x == 4:
        total += quantity * 3.45
    elif x == 5:
        total += quantity * 4
print(total)

Comment: OP said total for each separate item
Answer: for x in range(1,6):

    quantity = int(input("quantity of item " + str(x)+ " : "))
    if x == 1:
        total = quantity * 2.50
        Print("quantity: " + str(x) + " Total: " + str(total))
    elif x == 2:
        total = quantity * 1.98
        Print("quantity: " + str(x) + " Total: " + str(total))
    elif x == 3:
        total = quantity * 5.75
        Print("quantity: " + str(x) + " Total: " + str(total))
    elif x == 4:
        total = quantity * 3.45
        Print("quantity: " + str(x) + " Total: " + str(total))
    elif x == 5:
        total = quantity * 4
        Print("quantity: " + str(x) + " Total: " + str(total))

The reason why your code only prints the last item because you didn't save the previous values. When you assigned quantity equal to a variable that changes each loop, it replaces the previous value.
for example:
for i in range(3):
    num = i
print(num)

Because num will be replaced by the next value in this loop. We know the last value in range(3) is 2.
Since print statement is outside of for loop, it does not get affected by the loop and only print the last value which again is 2.
If you want all of them in one string, you can concatenate them into a string by first declaring a variable assign to an empty string where you can store the values. See below:
for x in range(1,6):

    FinalOutput = ""

    quantity = int(input("quantity of item " + str(x)+ " : "))
    if x == 1:
        total = quantity * 2.50
        FinalOutput += "Quantity: " + str(x) + " Total: " + str(total) + " , "

    elif x == 2:
        total = quantity * 1.98
        FinalOutput += "Quantity: " + str(x) + " Total: " + str(total) + " , "
    elif x == 3:
        total = quantity * 5.75
        FinalOutput += "Quantity: " + str(x) + " Total: " + str(total) + " , "

    elif x == 4:
        total = quantity * 3.45
        FinalOutput += "Quantity: " + str(x) + " Total: " + str(total) + " , "
    elif x == 5:
        total = quantity * 4
        FinalOutput += "Quantity: " + str(x) + " Total: " + str(total) + " , "

print(FinalOutPut)


Missing Editor, in Appearance Wordpress theme Activello

Question: I have a little problem with wordpress theme Activello.
https://i.stack.imgur.com/DP6US.jpg
I can't found in Appearance sumbmenu Editor. I need it for edit footer theme because for the moment it's looks like this https://i.stack.imgur.com/pHYQI.jpg
Thanks for your attention.
Wish you a good day!
Comment: you can see all menu items in "menus"
Comment: Yes I can see them. https://imgur.com/a/RELb9Hk
Comment: just drap and drop left to right the 2nd menu item
Comment: George I don't need to edit position of menu and submenu. I need to fix the problem with missing Editor in Wordpress Dashboard in Appearance.
Answer: Add this line in wp-config.php file
<code>define( 'DISALLOW_FILE_EDIT', false );
</code>
Answer: Probably, its due to some of your security plugins like - https://wordpress.org/plugins/better-wp-security/. Check settings of each and every security plugin you have installed.
Comment: Okay. I'll check them now! Thanks.
Comment: Outsource WordPress can you tell me please, what plugin can give me this trouble.
On my site I use this list of plugins:
a3 Lazy Load,
Akismet Anti-Spam,
Akismet Privacy Policies,
Autoptimize,
Child Theme Condifgurator,
COnditional Widgets,
Contact Form 7,
Contact Form 7 Widget for Elementor page builder,
Custom Fonts,
Easy Google Fonts,
Elementor,
Elementor Addon Elements,
Elementor Addons & Templates - Sizzify Lite,
Force Regenerate Thumbnails,
Hide Page and Post Title,
NavMenu Addon For Elementor,
PopBox for Elementor,
Really Simple CAPTCHA,
Comment: reGenerate Thumbnails - advanced, Shariff Wrapper, Smart Slider 3, Smush, TinyMCE Advanced, Webcraftic Clearfy, Widget Importer & Exporter, WP Meta and Date Remover, WP Super Cache
Comment: I didn't use wordpress for a long time and forgot how to use it right. Thanks for help
Comment: Can you just rename 'plugins' folder and check whether Editor menu showing? Sometimes theme settings may also disable the Editor menu access.
Answer: I have solution. This video will help you. You can change or delete footer credits: https://youtube.com/watch?v=fVm2eenrgkE. Or you can go to to customise > css and find div class of credits. Then in css box type this:
.{display:none;}
Comment: Mario, I've seen this video, but it didn't help. I don't want to delete my footer, I just need to edit it. Cause I can't edit .php files without editor.
Comment: But, you can change it. If you want, I can do it for you, but you will need to give me login credentials. You can also contact me by mail: firstname.lastname@example.com and I can like connect to you with TeamViewer, and fix it. (If you want.)