How do I verify that a set of vectors is a basis for the given plane

Question: I have a set of 2 vectors: $\{ (1,2,0), (0,2,-1) \}$. I have to show that this set is a basis for the plane with equation: $2x_1 - x_2 -2x_3 = 0$. I know that the normal vector of the plane is $\langle 2, -1, 2\rangle$. I also know that I have to check for linear dependence.
But do I check linear dependence only with the 2 vectors in the set? Because when I use Gauss-Jordan elimination to check for linear dependence for all 3 vectors (the 2 in the set and the normal vector of the plane), I get an inconsistent solution. What do I do?
Comment: You only have to check the first two vectors are independent, and that they satisfy the equation of the plane. By the way, the three vectors *are* independent. Check your computations.
Comment: Your normal vector is not normal to the second span vector. $n_3$ should be $-2$.
Comment: You could take the vector cross product and ask yourself if the result is a scalar multiple of the normal vector.
Answer: The equation of the plane directly gives a normal:
$$
0 = 2 x_1 - x_2 - 2 x_3 = (2,-1,-2)^T \cdot (x_1,x_2,x_3)^T = n \cdot x
$$
Now examining the scalar product for every vector in the span:
$$
n \cdot x = n \cdot \left( c_1 a_1 + c_2 a_2 \right)
= c_1 \left(n \cdot a_1 \right) + c_2 \left(n \cdot a_2\right) = 0
$$
as the $a_i$ are normal to $n$. Thus the span is part of the plane.
Can the plane have more vectors than the span? Its defining normal vector is base of a 1D orthogonal space, so it must be 2D, as expected from a plane.
The span might be of dimension less than 2. It is at least 1D as the generating $a_i$ are not null vectors. That would only leave linear dependence as cause for a 1D span, thus we test this:
$$
c_1 a_1 + c_2 a_2 = 0 \iff \\
\left[
\begin{array}{rr|r}
1 &  0 & 0 \\
2 &  2 & 0 \\
0 & -1 & 0
\end{array}
\right]
\iff
\left[
\begin{array}{rr|r}
1 &  0 & 0 \\
0 &  2 & 0 \\
0 & -1 & 0
\end{array}
\right]
\iff
\left[
\begin{array}{rr|r}
1 &  0 & 0 \\
0 &  1 & 0 \\
0 &  0 & 0
\end{array}
\right]
\iff \\
\left(
\begin{array}{r}
c_1 \\
c_2
\end{array}
\right)
=
\left(
\begin{array}{r}
0 \\
0
\end{array}
\right)
$$
There is only 0 as solution, so they are linear independent.
Thus the span is 2D and equal to the plane.
The $a_i$ form a basis for the plane.
Answer: both vectors $(1,2,0)$ and $(0,2,-1)$ are on the plane $2x_1-x_2-2x_3 = 0.$ you don't need the normal to the plane to show that these vectors are linearly independent. in fact, if you have only two nonzero vectors, then they are linearly dependent if one is not the  multiple of the other as the case her.


Very Basic query on logging in powershell

Question: I have no programming background and I'm working on doing some very basic tasks with Powershell. Moving files and logging which files moved
I've tried using out-file and write-output none of which are working
Move-Item -Path $sourceDir\*.* -destination $destinationDir -force  | Out-File -filepath $Mylogpath -Append

I'm trying to move files from one server to another which I have working however I'd like to log the files I'm moving into a text file and date/time stamp them.
Any pointer gratefully accepted
Comment: that cmdlet has no default output. [*grin*] if you want it to tell you what it did, you will need to add the `-Verbose` parameter. otherwise, you will likely want to add explicit logging with one of the logging modules from the PSGallery.
Comment: um ... you need to tell the item you want info about to give you verbose output. [*grin*] if you want to know what the `Move-Item` cmdlet is doing, add the parameter to THAT cmdlet. if you want such info on every thing, you can wrap it all in an advanced function and add the `[CmdeltBinding()]` option to it. that will pass a `-Verbose` call to everything in the function. ///// another two ideas - use the `*-Transcript` cmdlets OR enable script logging via GPO.
Comment: i added the -verbose and it them gave me the below but didnt actually tell me the files it moved, im going to go have a look at the logging modules in PS Gallery. 'code' VERBOSE: Performing the operation "Output to File" on target "C:\testlog_012019.txt".
VERBOSE: Performing the operation "Output to File" on target "C:\testlog_012019.txt" 'code'.
Comment: Thanks @Lee_Dailey i added the -verbose to the correct cmdlet and used the *-Transcript to output all to a log. Working perfectly. Many Thanks
Comment: you are most welcome! glad to have helped a tad ... [*grin*]
Answer: Move-Item by default does not output anything. To get an output of which files are moved, you can use the -PassThru parameter on Move-Item. This will then tell Move-Item to output the files it is moving:
Move-Item -Path $sourceDir\*.* -destination $destinationDir -force -PassThru | Out-File -filepath $Mylogpath -Append


Did I fudge up or is my paint just too light?

Question: I am needing to do touch-ups around the house and I grabbed a sample off the wall since our handyman fudged up some of the paint anyways, took it down to home depot and the lady made me a quart, she did the little dot on the top and it looks pretty damn identical, I took it home and started my touch ups but noticed it was a fair bit lighter than what she dabbed on the top, now it clicked about 20 mins later I forgot to stir it (durr moment, but I figured since I just had it made up it'd be fine).
If I gave it a nice drill mixing is it possible that it'll get darker?
Comment: The shaker in the paint mix machine should have given it a better stir than you'll ever manage manually. Those things are *fierce.*
Comment: is the paint dry? wet paint can look an entirely different colour once its dried
Comment: Answers are good. The solution is to paint corner to corner.
Comment: It's not just the color, it's the sheen.  I still hate Glidden for stopping the manufacture of their high hiding white.
Comment: @SteveWellens Hiding is the job of primer.  I buy $300/gal paint and I get print-through on 1 coat.  I don't get mad, I mix their white and gray primers to get a lightness which matches the final coat. Then I use 2 final coats.
Comment: @Harper-ReinstateMonica  "High Hiding" was the name of the paint.
Comment: @Steve yeah, the consumer-facing house paint space is chock full of bad ideas, like combination paint-primer.   But "high" is relative: if you're overpainting a chess board, that's going to take a lot of coats.  Paint and primer are translucent.
Comment: @Harper-ReinstateMonica   Why are you lecturing me?  I didn't name the paint.
Answer: You have two core problems.
A perfect paint match is functionally impossible.  The limiting factor is more the mixing than the scanning.  Mixing isn't precise enough.  Advice when doing a multi-gallon paint job is to mix all the gallons into a bucket, stir them together, then pour them back out into the gallon cans.  So buying another can, even with the same formula code, will probably not match well enough to get away with painting spots.
The second issue is texture or sheen.  Paints differ. When you brought in your sample, you didn't tell them whether it was a flat, matte, satin, gloss, etc. So you might not have gotten a match there. That will show.  Alternately, if you changed paint brands or grades, ones satin may not match the next's satin.
Answer: It may improve if you stir it up.   The colorant dispensing machines are not super-accurate, and so a quart is generally less consistent than a gallon or a 5 gallon bucket.
Different paints also have different compositions, sheens, and hiding levels, so even if the color is right, putting a second identical coat of paint over a an earlier coat tends to create perceptions of light and dark.  Same with thicker or thinner coats of paint, or even with brushed touch-ups vs the original roller or spray application.   Paint also fades and gets dirty, so new applications rarely match exactly.
In general, I've been most successful by identifying the original manufacturer, year, and color, and asking the paint store to duplicate the formula rather than bringing in swatches and asking them to duplicate the color.


Simplifying $ \sum_{m = -\infty}^{\infty} \frac{1 }{ (qm + a)^2} $

Question: For an integer $q \geq 2$ and $1 \leq a \leq q/2$, I am asked to simplifty
$$ \sum_{m = -\infty}^{\infty} \frac{1 }{ (qm + a)^2} $$
I know that the function involves $1 / \sin$, but I am unable to find the sum.
I am not looking for a direct answer, just a general method to compute series such as these. We know that when $q = 1, a = 0, m = 1, 2, 3, \ldots$ , the sum equals $\pi^2 / 6$, which can be proven using Taylor series expansions, but I was unable to do something similar here.
Comment: $\frac{\pi^2}{\sin^2(\pi z)} - \sum_{n=-\infty}^\infty \frac{1}{(z-n)^2}$  is $1$-periodic and analytic and bounded on $\Re(z) \in [0,2]$
Comment: $\displaystyle\frac{\pi^2}{\sin^2(\pi z)} = \sum_{n=-\infty}^\infty \frac{1}{(z-n)^2}$  (the LHS minus the RHS is a [bounded entire function](https://en.wikipedia.org/wiki/Liouville%27s_theorem_(complex_analysis)) which vanishes at $\infty$)
Comment: Why is it bounded?
Answer: Let us start with the Weierstrass product for the sine function:
$$ \frac{\sin(\pi z)}{\pi z}=\prod_{n\geq 1}\left(1-\frac{z^2}{n^2}\right) $$
and apply $\frac{d^2}{dz^2}\log(\cdot)$ to both sides:
$$\frac{\pi^2}{\sin^2(\pi z)}-\frac{1}{z^2} = \sum_{n\geq 1}\left[\frac{1}{(z-n)^2}+\frac{1}{(z+n)^2}\right] $$
then rearrange and multiply both sides by $\frac{1}{q^2}$:
$$\sum_{m\in\mathbb{Z}}\frac{1}{(mq-qz)^2} = \frac{\pi^2}{q^2\sin^2(\pi z)}. $$
If we set $z=-\frac{a}{q}$, we get:
$$\boxed{\sum_{m\in\mathbb{Z}}\frac{1}{(mq+a)^2} = \color{red}{\frac{\pi^2}{q^2\sin^2\left(\frac{\pi a}{q}\right)}}.}$$


Generic point and pull back

Question: Let's work over $\mathbb C$,
Consider a finite morphism between two integral curves $f: X\rightarrow Y$, let $\eta_Y$ (resp $\eta_X$) be the generic points
Questions:

What is $X_{\eta_Y}=f^{-1}(\eta_Y)$ ? is it just $\eta_X$?
If the answer is no, haw about the case where $f$ is an double cover?
How about the general case of two integral schemes (rather then curves)?

thanks.
Answer: Recall that finite morphisms are closed, so that closed points of $X$ map to closed maps of $Y$.
On the other hand the generic point of $X$ (the only non closed point) cannot be sent to a closed point $y\in Y$, else all points of $X$ would be sent to $y$ too, by continuity of $f$, and $f$ would be constant and thus certainly not finite.
All in all we have proved that $$f^{-1}(\{\eta_Y\})=\{\eta_X\}$$
Edit
Since you are interested in a generalization, here is one:
Given a morphism of completely general integral schemes $f:X\to Y$ we have the equivalence $$ f \operatorname {is dominant}\: (i.e.\operatorname {has dense image}) \iff f(\eta_X)=\eta_Y$$
If moreover $f$ is proper (for example projective or finite) its image is closed and we thus deduce:$$      f (X)=Y\iff f(\eta_X)=\eta_Y              $$
Be careful that this last equivalence does not say that $f^{-1}(\{\eta_Y\})=\{\eta_X\}$ as shown by the unique $k$-morphism $$f:X=\mathbb P^1_k\to Y=\operatorname {Spec}(k)$$ for which $f^{-1}(\{\eta_Y\})=\mathbb P^1_k$

Generic point and pull back


Python urllib.encode @ symbol?

Question: The Python documentation for httplib (http://docs.python.org/2/library/httplib.html) shows the
urllib.urlencode parameter keys preceded with an @ symbol. I don't see this in other examples. What is the @ symbol doing in this case?
>>> import httplib, urllib
>>> params = urllib.urlencode({'@number': 12524, '@type': 'issue'})
>>> headers = {"Content-type": "application/x-www-form-urlencoded",
...            "Accept": "text/plain"}
>>> conn = httplib.HTTPConnection("bugs.python.org")
>>> conn.request("POST", "", params, headers)

Comment: Because the bug trackers expects `@number` etc... as parameters and they need to be escaped...? It doesn't have any special meaning if that's what you mean?
Answer: as you can see, it has no meaning:
>>> import httplib, urllib
>>> params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
>>> print params
'%40action=show&%40number=12524&%40type=issue'
>>> params = urllib.urlencode({'number': 12524, 'type': 'issue', 'action': 'show'})
>>> print params
'action=show&type=issue&number=12524'

it just formats the special character @ into %40 that is being used by http://bugs.python.org as POST keys, and the reason why they use it is internal to that site's engine...

Python urllib.encode @ symbol?


Low basement ceiling, how high should cabinets be?

Question: I am creating basement suite. The ceiling is 6' 8". I plan to install a drop ceiling, so it  will be around 6' 6" when that is done.
How high should my upper kitchen cabinets be? I've read that they are supposed to start at 54". If the shortest cabinets are 30" and the ceiling is only 78" high, these won't fit.
Should I cut the cabinets? Or install them them lower?
Comment: Have fun getting an occupancy permit. https://buildingcodetrainer.com/residential-ceiling-heights-per-code/
Comment: actually it's only 6' 4" height requirement where I live.
Comment: 6'-4" is a magic number in IRC R305.1: "Beams, girders, ducts or other obstructions in basements containing habitable space shall be permitted to project to within 6 feet 4 inches (1931 mm) of the finished floor." You're not extrapolating this exception for @Ecnerwal's 7'-0" to the whole area, are you?
Comment: This is a decorating/design question. There is no "right" answer.
Comment: My standard kitchen cabinets come in ~18, 24, and 30 inches, so custom/semi custom should not be needed.
Answer: Standard counter height is 36". 54" - 36" = 18". So the usual distance between the counter and the bottom of the cabinets is 18". Keep in mind that upper cabinets are also usually not as deep as counters: 12" vs. 24".
All of that means that if you use 30" tall upper cabinets above 36" counters on a 78" wall that you will have 12" instead of 18" between the counter and the cabinets. If you use the under-cabinet space mainly for storage - e.g., slide the toaster and food processor, etc. out of the way when not in use, you will be fine. On the other hand, some things such as a dish drying rack may be a bit harder to fully use with only 12" of available space.
Custom, or semi-custom, cabinets may be a solution. Shorter cabinets are routinely used above cooktops and refrigerators, and anything can be special ordered for a price. You can also mix and match - use shorter cabinets where you really need the space and taller (standard 30") cabinets where you don't.
If you have lots of floor space than another option is an island, peninsula or simply a section with no cabinets above it. I have a 5' counter on a brick wall with standard base cabinets and no upper cabinets, and there are plenty of things I'll do there (especially anything involving rolling out dough) that I can't and/or just won't do on the other counter areas because the large open space is much easier to work with than the rest of the counters which have cabinets above them and are broken into small sections by cooktop and sinks.
Comment: Thanks very much for your response. That makes a lot of sense. I will try to mix and match depending on where they are in the kitchen. There will be a couple of spots 30" cabinets shouldn't be an issue... but aside from that may need to go with the shorter ones. Thanks again!
Answer: You are not obligated to install your cabinets at any "customary" height used when installing cabinets in new construction.
Comment: This is more of a comment than an answer, but I agree 100%
Answer: Standard upper cabinet elevation is 18" above the countertops.
In the US you typically need a ceiling height of no less than 7'-0" in "habitable spaces," where the definition of "habitable space" includes cooking areas like your kitchen. See IRC R305.1. Your 6'-6" drop ceiling will fail inspection in any jurisdiction using the International Residential Code, which is very, very common in the US. There is an exception for girders and ducts hanging from the ceiling, so don't worry about those as long as they're at or above 6'-4".
The 7'-0" ceiling height requirement explains the unavailability of upper cabinets with heights less than 30". With standard counter height of 36" and standard space between counters and upper cabinets of 18", 36"+18"+30" = 84" = 7'-0".


Can Ruby's Sass gem be manually installed?

Question: I work inside a corporate firewall. I am using Windows 10 and have the Ruby 2.4 x64 install.
I need to get the sass gem. I cannot do it through the command line because all external calls such as this are blocked and will not be unblocked for my situation. Is there a place I can manually download the sass gem, and then issue the command to install the gem from a local file?
Comment: you can download it from rubygems ([link](https://rubygems.org/gems/sass))
Comment: you can always run your own gem server. http://guides.rubygems.org/run-your-own-gem-server/ — there are other solutions as well.
Answer: I'm in the same position and use two techniques

through the firewall
See my answer at installing-gems-from-behind-a-corporate-firewall
from a local file

You download the gem from https://rubygems.org/downloads/sass-3.5.4.gem
You can put the file in your ruby\bin folder and delete it later.
Then you cd to your bin folder and install it in the console with the command
<code>gem install sass-3.5.4.gem --local
</code>
the 3.5.4 is the current version.
If there are dependencies (other gems) you need to first download them as wel.
Can't see what these are because on this machine I'm still using Ruby MRI 1.9.3 and the current version of sass requires Ruby 2.0.0
See also my answer here
deploy-a-ruby-gem-local-without-using-git-or-internet-access
Comment: I did this and got this: ERROR: Could not find a valid gem 'sass-listen' (~> 4.0.0) in any repository.
Comment: see wat I wrote about dependencies, sass-listen is one of them, you need to download them as well and put them in the same folder, the easiest thing to do is first install the gem on a normal to the internet connected pc, copy the list of gems that are installed as well and copy these gems to your server behind the firewall
Comment: This is a great answer and got me close. However, it still did not work for me due to corporate restrictions on my computer. My end goal is SASS, so I might explore another way to compile it. Thanks!


Issue with action link and areas in asp mvc project

Question: I have one area Area1 with controller Home and it's Index method.
I also have created another area Area2 with controller Home and it's Index method.
In Area1 I have action link that should open Index page in Area2.
@Html.ActionLink("Link to another area index", "Index", "Home", new { area = "Area2" }, null)

But when I click on this link it first go to Area1/Home/Index!
Why is this happening. Is this has to be like this or it can go directly to Area2/Home/Index?

This makes me problem because in Area1/Home/Index I need some parameters and when this happens this valuer are null or wrong and make me problem. I must doing something wrong.
Update
Area1 routing
public override void RegisterArea(AreaRegistrationContext context)
        {
            context.Routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

            context.MapRoute(
                "Area1_home",
                "{country}/{city}",
                new { controller = "Home", action = "Index", country = UrlParameter.Optional, city = UrlParameter.Optional }
            );

            context.MapRoute(
                "Area1_default",
                "Area1/{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

Area2 routing:
public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Area2_default",
                "Area2/{controller}/{action}/{id}",
                new { controller="Home", action = "Index", id = UrlParameter.Optional }
            );
        }

Answer: Try:
Html.ActionLink("Link to another area index", "Index", "Home", new { Area = "Area2" }, new{});

Comment: Still goes to Area1/Home/Index first :(
Comment: Hmm, that's strange, I found some more links saying pretty much the same thing: http://www.f15ijp.com/2011/04/30/specifying-what-area-an-actionlink-should-use/ and also here http://stackoverflow.com/questions/2036305/how-to-specify-an-area-name-in-an-action-link. If you got your areas set up right and no special routing configured I don't know then why it would not work. You did try with the word `Area` spelled with a capital `A` yes ?
Comment: Yes I have tried 'A'. I have updated question with routing because maybe routing is making my trouble.
Comment: When I created project I removed all routings from global.asax. I return default routing now and it worked. I don't understand why this works... routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { area = "Area1", controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
Comment: At least you got your action link to work to work and can focus on the routing now. Routing can get very confusing. Remember that a route is always tried to be matched top down. So, which ever rout configuration is added first will the first one tried to be matched firsted. If MVC finds a match it will not continue to search and return that route configuration. When adding routes always add them with most important to match fist and with least important last.


Moonstone Ore turns into invalid item when mined

Question: I have my custom mod pack installed on Minecraft 1.6.4 server and client. THe proble is - when I mine Moonstone Ore from ARS Magica 2 I get Invalid Item (Destroy) from Thermal Expansion instead of Moonstone:

What can be the reason and how to fix that?
Comment: This is an ID conflict. You'll have to modify one of the config files to change the ID of one of these items to some new unused ID. I don't have time now to make a full answer though.
Comment: @Arperum, I have tried what you suggested and it helped. If you find some time and post your comment as an answer I will mark it as accepted one.
Answer: This is a clear case of an ID conflict.
The Ars Magica moonstone item uses the ID 20256, but this same ID is also used by Thermal Expansion for that "Destroy" item (that is probably used for something hidden in Thermal expansion). The Thermal expansion item is used because these are loaded later in the boot order (loading order is alphabetic over the jar/zip files as far as I've seen)and thus overwrite the previous Ars Magica item.
The solution to this is to modify the Ars Magica or the Thermal expansion config file so it uses a different ID for this specific item. Keep in mind that some mods require their itemID's to be sequential, so modifying one requires you to modify the other ID's in the sequence too(I don't know if this goes for Ars Magica and/or Thermal expansion though)
Answer: After some thinking I solved the problem: I opened the config file from Ars Magica and changed the value of "I:ItemIDRangeStart" on the section "items" for some other value, (I used 19744) and then deleted the list of IDs on the same section.
By testing, I confirmed that I was able to craft the moonstone as it should be, I even placed the block on the world and broke just to make sure. After it I just trowed the "invalid" items on the lava and spawned the right ones to make it even. The last step is to turn the config "B:RetroactiveWorldGen" to true so you can get the blocks affected by the ID change on the already loaded chunks. Don't forget to backup all the process and good luck :)


Java: Why can't I insert parameter instead of %s?

Question: I have a structure as this:
String xml = "<tag><another_tag>%s</another_tag></tag>"

and I pass a parameter to method and try to replace %s:
String str = String.format(xml, parameter);

But I have got previous xml file wrapped as a tag on the place of '%s'. If I set a simple String:
String str = String.format(xml, "parameter");

all works well.
Why does it happen?
Comment: What's the value of `parameter`?
Comment: Could you post code that reproduce problem because it seams to works fine (at least for me).
Comment: what is `String.formate()`?  do you mean `String.format()`?
Comment: Yes, I can. Sorry, I have  code on my workplace and will get access to it only toworrow
Answer: As Pshemo says, this works fine:
String xml = "<tag><another_tag>%s</another_tag></tag>";
String parameter = "abc";
String str = String.format(xml, parameter);
System.out.println(str); // <tag><another_tag>abc</another_tag></tag>

Comment: @RomanC OP said in comment that he is using `String parameter = "parameter"` so does it matter if we use `"abc"` instead of `"parameter"`?


Boot Stuck After Update to 18.04 from 14.04

Question: I recently tried to upgrade a machine from Ubuntu 14 to 18 via dist-upgrade. The update appeared to proceed without problems. However, after rebooting and choosing 'ubuntu' from grub the splash screen loads with the dots underneath but gets stuck (no progress or keyboard / mouse input) after each dot has flashed once.
I have tried pressing ESC to display the text interface while booting. This works sometimes if I press it quick enough but the text is often a little jumbled, although sometimes not. I have also tried turning off the splash from grub by pressing e and editing the options. This however just gave a blank screen. I also tried selecting the 14.04 option which is still in grub. This boots fine. Re-running dist-upgrade from 14.04 didn't work. I also tried boot-repair from 14.04 to see it if would help but it just renamed and reordered the grub entries to make the 14.04 option 'Ubuntu' and the Ubuntu 18 option 'Ubuntu 18.04'.
When the text interface does work it appears to get stuck either at the part where it is waiting for entropy or just after these lines:
[ OK ] Started Network Manager Script Dispatcher Service.
NetworkManager-dispatcher.service
[ OK ] Started GNOME Display Manager.
gdm.service
_

Any ideas how to sort out this mess and get the 18.04 upgrade to boot?
Comment: Ubuntu 14.04 LTS should be upgraded to 16.04 LTS (via `do-release-upgrade`  which ensures packages are upgraded in the correct order), then a reboot  to get 16.04 LTS running, then a second upgrade to go to 18.04 LTS via a second `do-release-upgrade`.  This is the tested path.  If you skipped 16.04 LTS, and used debian's `dist-upgrade` after manually adjusting your sources - I'd recommend a re-install (without format, use something else & don't format your partitions. the last part of the install will try and restore you packages so your programs are installed).  Otherwise it's manual checks..
Comment: I didn't do any manual adjustment of sources. Just `dist-upgrade` which went straight to 18.04 all on by itself. I'd be happy to remove the failed 18.04 and try the other method but I do not know how to do this. Do I just remove a partition?
Comment: `sudo apt-get dist-upgrade` (or `sudo apt full-upgrade`) will not move you from one release (14.04 LTS) to another, it will just do an upgrade of more packages than `sudo apt-get upgrade` allows.  The only way dist-upgrade can change from one release (14.04 LTS) to any other releases is via a sources change (performed via `do-release-upgrade`).  Something doesn't add up in my books (or I don't understand anyway).  No you don't remove a partition; nor would I re-install, as if you only `sudo apt dist-upgrade` you'll be on 14.04 LTS.  Boot with a '1 nomodeset` (removing quiet splash) and lsb_r..
Comment: It appears as if it it has upgraded packages and added a grub entry in /userdata replacing the home directory. Hmm maybe I'll just have to wipe the machine and fresh install.
Comment: Ok. Just managed to find all of the old home directory files. The paths have just been messed up so no data lost. Will back up everything again just to make sure and clean install.
Comment: `sudo apt upgrade` has a lot of limitations (for stability, to avoid need for reboot etc) where as dist-upgrade allows minor program version bumps, can require a reboot etc..  If you had a kernel upgrade installed (which occurs with dist-upgrade), it will perform a `update-grub` which scans your system for other OS, then writes a new `/boot/grub/grub.cfg` file - this maybe all that happened. Either way it cannot change your version unless you did something to make it.  Do you have a dual boot, with 18.04 or another GNU/Linux or your system?  Maybe the grub.cfg or /etc/fstab mounts wrong parts
Comment: No dual boot but I had the OS (mountpoint /) on one drive and /home on another. It would be nice to fix it but ultimately I think a clean install will be less of a headache.
Comment: I agree that a clean install will be less of a headache. Good luck :-)
Answer: I am answering my own question in case others searching for a similar answer find this helpful.
I accidentally used the Debian dist-upgrade command instead of Ubuntu's do-release-upgrade. This upgraded packages beyond what apt-get upgrade allows and also moved my home folder from where it was on a separate drive to the drive with the OS. It also replaced the old home directory with grub boot files. No data was lost. If anyone else makes this mistake, your files may have just moved. You may be able to boot using a different grub entry and recover them or use a live CD.
My solution was ultimately to ensure I have a backup of everything and perform a clean install.
TLDR: Don't use dist-upgrade, use do-release-upgrade.


Substitution in finding limits

Question: I'm really obsessed with using substitution in order to finding limits . When we can use that ? (What's the conditions for using substitution ?)
What's the rigorous proof which enables us to do that ? For example is that true if we say : $\lim_{x \to \infty } x - \lfloor x \rfloor $ doesn't exist so we conclude $\lim_{x \to 0 } 1/x - \lfloor 1/x \rfloor $ also doesn't exist ?
Comment: Similar: https://math.stackexchange.com/questions/167926/formal-basis-for-variable-substitution-in-limits, https://math.stackexchange.com/questions/1069642/finding-a-limit-using-change-of-variable-how-come-it-works
Comment: "is that true if we say : $\lim_{x \to \infty } x - \lfloor x \rfloor $ doesn't exist so we conclude $\lim_{x \to 0 } 1/x - \lfloor 1/x \rfloor $ also doesn't exist ?" Let's be careful. You don't want $x\to 0,$ you want $x\to 0^+$ The general result you want in this setting is: Assume $f$ is defined in some interval $(a,\infty).$ Then $\lim_{x\to \infty} f(x) = L$ iff $\lim_{x\to 0^+} f(1/x) = L.$
Answer: A standard theorem about limits, which you can probably find a proof of in a standard calculus text is: If $\lim_{x\to a}f(x)=b$ and $\lim_{x\to b}g(x)=c$ then
$\lim_{x\to a}g(f(x))=c$.
Proof: Let $\epsilon>0$. Since $\lim_{x\to a}f(x)=b$ and $\lim_{x\to b}g(x)=c$, there are $\delta_1,\delta_2>0$ such that $|x-a|<\delta_1$ implies $|f(x)-g|<\delta_2$, and $|x-b|<\delta_2$ implies $|g(x)-c|<\epsilon$.
So, if $|x-a|<\delta_1$, the fact that $|f(x)-b|<\delta_2|$ implies $|g(f(x)-c|<\epsilon$.  Therefore,
$$\lim_{x\to a}g(f(x))=c.$$
Comment: The above answer is correct, and can be complemented with those provided in the posts indicated by *H. Lundmark*. To help you visualize that, consider to graph $g(x)$ on a rubber sheet. Then imagine the sheet subject to a deformation along the $x$ axis, given by $f(x)$. If the deformation does not cause a tear in the sheet ... can you see what's going on ?
Comment: This answer is not quite right. For example, suppose $f(x) = x\sin (1/x)$ and $g(x) = 1$ for all $x\ne 0,$ $g(0)=0.$ We have $\lim_{x\to 0} f(x) = 0,$ and $\lim_{x\to 0} g(x)=1.$ But $\lim_{x\to 0}g\circ (x)$ fails to exist, oscillating  between $0$ and $1$ in every neighborhood of $0.$
Comment: That's right but in many problems it can't be applied .
Comment: It should apply if the first two limits exist.
Comment: I mean in many substitutions we can't use that theorem . Undoubtedly , if the conditions of the theorem is fulfilled we can use that .
Comment: Yes, I guess I'm missing the point of your comment.  Are you looking for some other answer?
Comment: In fact yes but anyway thanks for the answer .
Comment: OK, I'm not sure there is one. This is the principle that allows substitution in limits.  Perhaps someone more knowledgeable may have deeper insights. :)
Comment: It's very challenging to me that use substitution without any proof . I appreciate your help , thanks a lot . :)
Comment: Have you seen the proof of the theorem I mentioned. If not , I can provide one.
Comment: Yes I do , it's really hard to grasp it !
Comment: OK, I'll edit my answer
Comment: @zhw. is correct. $g$ must be continuous at $b$ in order for this to work.
Answer: Let's discuss the case you mention: Suppose $f:(a,\infty)\to \mathbb R$ for some $a>0.$ Here is a basic substitution result for this case:
$$\tag 1\lim_{x\to \infty}f(x) = L\, \iff\, \lim_{x\to 0^+}f(1/x) = L.$$
Your question was: "is that true if we say : $\lim\limits_{x \to \infty } x - \lfloor x \rfloor $ doesn't exist so we conclude $\lim\limits_{x \to 0^+ } 1/x - \lfloor 1/x \rfloor $ also doesn't exist?" The answer is yes, by the result $(1).$ Let's go through the logic: Define $f(x) = 1/x - \lfloor 1/x \rfloor.$ Suppose $\lim\limits_{x\to \infty}f(x)$ fails to exist. Could $\lim\limits_{x\to 0^+}f(1/x)$ exist? No! If it did, then then $(1)$ would imply $\lim\limits_{x\to \infty}f(x)$ exists, contradiction. That's what the $\iff$ is all about.
So in fact $(1)$ tells us that $\lim\limits_{x\to \infty}f(x)$ fails to exist $\iff \lim\limits_{x\to 0^+}f(1/x)$ fails to exist.
Added later: General result on limits and substitution The following result covers many, but not all, cases of interest. (Missing is the case of one-sided limits.)
Thm: Let $I,J$ be open intervals. Let $s: I \to J$ be a a continuous bijection. Let $a\in I$ and set $b=s(a).$ Suppose $f: J\setminus\{b\} \to \mathbb R.$ Then $\lim_{y\to b} f(y) = L$ iff $\lim_{x\to a} f(s(x))=L.$
Notes: 1. $y=s(x)$ of course is our substitution. 2. The hypotheses imply $s^{-1}: J \to I$ is a continuous bijection. We need this for both directions, i.e., the "iff". 3. We have taken care to not assume $f$ is defined at $b.$ Hence also $f(s(x))$ is not defined at $a.$ This is important for limits in general, for example in the famous case of $\lim_{x\to 0} (\sin x)/x.$
Proof of Thm: $\implies:$  Let $\epsilon>0.$ Then there exists $\delta > 0$ such that $(b-\delta, b+ \delta)\subset J$ and $y\in (b-\delta, b+ \delta)\setminus \{b\}$ implies $f(y) \in (L-\epsilon,L+\epsilon).$
Since $s$ is continuous, there exists $\gamma > 0$ such that $(a-\gamma, a+ \gamma)\subset I$ and $x\in (a-\gamma, a+ \gamma)\setminus \{a\}$ implies $s(x) \in (b-\delta, b+ \delta)\setminus \{b\}.$ For such $x$ we have $f(s(x)) \in (L-\epsilon,L+\epsilon).$ Thus $\lim_{x\to a} f(s(x))=L$ as desired.
$\impliedby$ Briefly: This time we assume $f\circ s,$ which is defined on $I\setminus \{a\},$ has limit $L$ at $a.$ From our work above, this implies $(f\circ s)\circ s^{-1} \to L$ at $b.$ Since $(f\circ s)\circ s^{-1}=f,$ we have $f\to L$ at $b$ as desired.
Comment: Yes , please write the proof but this is an example of substitution . How we can prove it in the general case ? My mean is changing variable in all situation works ? (i.e $\lim_{x \to a} f(g(x)) \iff \lim_{x \to b} f(x) $ if $\lim_{x \to a} g(x) = b$ )
Comment: @S.H.W The "all situations" result is not correct in the way you stated it. We need to be more careful. Did you read my comment to the other answer?
Comment: Oh , I see . That's a nice example . Can you mention the conditions where we can use that without any problem ?
Comment: @S.H.W I've added a proof for a general result.

Substitution in finding limits


How are fragment activity layouts affected by main activity layout?

Question: After having been introduced to Android development and creating a few basic applications, I have begun splitting activities into fragments for reusability. However one thing that I'm still slightly confused about is how the layout of the main activity(which holds the fragments), is affected by the layouts defined for fragment activities and vice versa.
While I believe that the layouts would affect each other based on definitions of height and width for each fragment, the number of fragments in an activity, etc. However Im not sure if there are other rules I am unaware of and I want to know if the layouts specified for the fragments directly affect the way the way the layout of the main activity displays.
For example, the main activity has a RelativeLayout and contains two fragments which have LinearLayout defined in their own separate layout xml files. Do the LinearLayouts affect the way in which the RelativeLayout would normally display and vice versa?
Answer: Fragments are basically similar to other view like RelativeLayout or LinearLayout in some ways. For Example they can also have width and height; Fragments can expand on the basis of size of its children. Rest is up on you, how you design layouts (fragments). Fragment is also similar to Activity in a sense that it has its own xml layout and corresponding java class. Primarily, we use fragments in two ways:
i) One or more fragments capturing separate parts (space) of activity at a time.
ii) A particular fragment in activity which is replaced (add,remove,replace) by many other fragments programmatically
Answer: You can use fragments statically in the layout files of your activities and dynamically by adding them in containers which you also define in the layout files of your activities.
The fragment view, will be inflated and be displayed in its container. It all depends on how you define your container. If you make it so it match the width of its parent, the layout of the fragment can have a width as much as the parent of the container. It is like putting views into that container.


SQL music playlist database queries from design

Question: Im trying to implement this database design. I am new to mysql and do not really understand how to connect everything so i am trying to break every query down to pieces..
Database looks like
Songs:
id title length artist_id

Artists:
id name

Playlists:
id title user_id

Playlists_Songs:
playlist_id song_id

Users:
id name email

Query -
get the users playlistname and the playlist id
SELECT users.id,users.name,playlists.playlistname,playlists.id
FROM users, playlists
WHERE users.user_id = playlists.users_id

outputs :
user_id | user_username | playlistname | id

How do i use the id from the output to continue query "deeper" to get the playlist_songs ?
Sorry for confusion question, correct me if i am wrong.
Comment: Please use the more useful explicit joins rather than implicit(comma) joins. And do google how to join 3 tables = there's lots out there.
Comment: Possible duplicate of [Mysql query to join three tables](https://stackoverflow.com/questions/10257433/mysql-query-to-join-three-tables)
Answer: To connect tables, you can use Joins. If you want to get data from playlist_songs, you can use query like
SELECT users.id,users.name,playlists.playlistname,playlists.id, playlist_songs.song_id FROM users
        inner join playlists on users.user_id = playlists.users_id
        inner join playlist_songs on playlist_songs.playlist_id = playlists.id
WHERE users.user_id = <user_id_of_user>

You can join songs table with playlist_songs and then artists table with songs.
Comment: Thank you!! Do i do the joins for the songs with playlist_songs in the same query ?
Comment: Yes you can join in same query and include the columns that you need from that tables in select statement.
Comment: Thank you again, i have now accomplished what i wanted!


How can I improve the following grammar?

Question: I am trying to find out where I went wrong in the below code.
Flex input:
%{
        #include "jq.tab.h"
        void yyerror(char *);
%}
method          add|map|.. and other methods go here

%%

"/*"            { return CS; }

"*/"            { return CE; }

"jQuery"        {
                printf("%s is yytext\n", yytext);
                return *yytext;
                }

"args"          { return ARGUMENT; }

{method}        { return METHOD; }

[().\n]         { return *yytext; }

[ \t]+          { return WS; }

.               { return IGNORE; }

%%

int yywrap(void) {
        return 1;
}

Bison input:
%{
        #include <stdio.h>
        int yylex(void);
        void yyerror(char *);
%}

%token ARGUMENT METHOD IGNORE WS CS CE
%error-verbose

%%

stmts:
        stmt '\n'               { printf("A single stmt\n"); }
        | stmt '\n' stmts       { printf("Multi stmts\n"); }
        ;

stmt:
        jQuerycall                      { printf("A complete call ends here\n"); }
        | ignorechars                   { printf("Ignoring\n"); }
        | ignorechars WS jQuerycall     { printf("ignore+js\n"); }
        | jQuerycall WS ignorechars     { printf("js+ignore\n"); }
        | optionalws stmt optionalws
        | CS stmt CE                    { printf("comment\n"); }
        ;

jQuerycall:
        'jQuery' '(' ARGUMENT ')' '.' methodchain       { printf("args n methodchain\n"); }
        | 'jQuery' '(' ')' '.' methodchain              { printf("methodchain\n"); }
        | 'jQuery' '(' ARGUMENT ')'                     { printf("args\n"); }
        | 'jQuery' '(' ')'                              { printf("empty call\n"); }
        ;

methodchain:
        methodchain '.' methodcall
        | methodcall
        ;

methodcall:
        METHOD '(' ')'
        ;

ignorechars:
        IGNORE
        | IGNORE optionalws ignorechars
        ;

optionalws:
        | WS
        ;

%%

void yyerror(char *s) {
        fprintf(stderr, "%s\n", s);
}

int main(void) {
        yyparse();
        return 0;
}

My aim is to recognize any jQuery call with all its elements, and ignore any other statement / string. Also ignore comments. Right now, this code makes many assumptions - like 'args' to be the only selector element inside jQuery().
Edit
I am using the following input-output cases. Cases like 10 and 12 are the ones I'm trying to figure out:
> 1.input: statement\n output: Ignoring
>
> 2.input: statement statement\n output: Ignoring
>
> 3.input: statement statement statement\n output: Ignoring
>
> 4.input: jQuery()\n output: jQuery is yytext empty call A complete call ends here
>
> 5.input: jQuery(args)\n output: jQuery is yytext args A complete call ends here
>
> 6.input: jQuery().add()\n output: jQuery is yytext methodchain A complete call ends here
>
> 7.input: jQuery(args).add().map()\n output: jQuery is yytext args n methodchain A complete call ends here
>
> 8.input: /*comment*/\n output: Ignoring comment
>
> 9.input: /*jQuery()*/\n output: jQuery is yytext empty call A complete call ends here comment
>
> 10.input: /* comment */\n output: syntax error, unexpected CE, expecting IGNORE
>
> 11.input: var a = b\n output: Ignoring
>
> 12.input: var a = jQuery(args)\n output: jQuery is yytext syntax error, unexpected 'jQuery', expecting IGNORE

Comment: If you want help, it would be useful for you to tell us what the symptoms of your problem are, and why you are having a hard time diagnosing the root cause.  Few of us are going to bother to read your code to try to guess what your symptom is.  If you're lazy, so are we.
Comment: @IraBaxter, 've edited the description to include the cases i'm concerned about.. Thank u:)
Answer: In your lex file, the rule:
"jQuery"        {
                printf("%s is yytext\n", yytext);
                return *yytext;
                }

returns the token 'j' when it sees an input string of jQuery. Since your bison file never does anything with the token 'j' this will generally give you a syntax error.
You need to add JQUERY to your %token declaration and have this lex rule return that.
edit
Usually a comment can appear anywhere in the program (between any two other tokens) and are completely ignored.  So the easiest way to deal with them is in the lexer:
%x comment
%%
"/*"           { BEGIN comment; }
<comment>.     ;
<comment>"*/"  { BEGIN 0; }

this will skip over comments (returning no tokens at all), so the grammar doesn't need to worry about them.  If you don't want to use a lexer start state, you could instead use the complex regex:
"/*"([^*]|\*+[^*/])*\*+"/"          ;

Comment: Okay, i fixed that. Also the rule ignorechars: IGNORE | IGNORE optionalws ignorechars had a right recursion. Fixed that too.. Yet to fix case 10
Answer: I think I can give you a fix that will solve case 10, but there is a deeper problem.
Since case 8 gives you the results you expect, I infer that the input
/*comment*/

is recognized by the prouduction
stmt: CS stmt CE

Which is to say that the string "comment" is recognized as a stmt.  But when you add whitespace between CS and stmt the parse fails, which is your case 10.  You can patch this by rewriting your production as
stmt: CS optionalws stmt optionalws CE

But the deeper issue is that your parser can't recognize other comments, like
/* This is a remarkable remark, isn't it? */

and
/**
 * This is a multi-line comment.
 */


Native debugging error

Question: If I try to deploy and debug my windows 10 mobile app, the debugging stopped with error:

It only happens when I set Native debugging. Managed debugging doesn't cause such error.
Comment: This error seems more related to your environment. Have you tested in other devices? Besides, here is [a similar case](https://social.msdn.microsoft.com/Forums/en-US/2f539ccf-17ae-465a-9784-cda21e40a1a7/error-when-deploying-windows-10-uwp-app-to-phone?forum=wpdevelop) might be helpful.
Comment: Yes, I tried. Its not working. I think, it causes msvsmon.exe. Its remote debugger on phone.
Answer: It is stated here that .NET Native debug engine has some capability differences from normal .NET debugging. Furthermore, it is recommended to debug a non-optimized code:

These optimizations will have a significant impact on the debugging experience including unpredictable stepping and breakpoint behavior (due to code inlining) and the inability to inspect most variables due to memory optimizations.

Although this was not your presented case, it still pushes further to the following practical solution:

This means you will want to debug a non-optimized .NET Native build. This fastest way to do this is simply to disable optimizations.

Source

Native debugging error


Viewing friends' uploads on Xbox One

Question: Is there a way to view my friends' uploads in the 'Upload' app on the Xbox One? I thought this was a feature already, but when using the app tonight, all I saw were 'featured' uploaders, games, and featured uploads.
Why doesn't my account show this anymore?
edit: This video shows what I am talking about (around 1:21), and I don't seem to see my friends in this app anymore -

further research: I tried a few other things. For example, using my wife's account, she can see her friends videos. Also, I deleted my profile and then logged in again, and this did not help either. So it appears the app is fine and this is there - but my question now is - why doesn't this show for my account?
Comment: Can you verify that you can browse your friend's videos from their profile please? Go to view their profile and you should be able to see their videos when scrolling right (I can't remember what tab exactly). If not than it might have to do with your friend's privacy settings as you can set it to never share videos to anyone. Of course, if your wife's and your friend list overlap...
Comment: Yes, I could see all their videos in their actual profiles the whole time.
Answer: While rather confusing and somewhat embarrassing of a fix - its mainly because I have not enough friends. Well, not enough friends with a One who are also actively uploading things.
I went through so much debugging with Xbox Twitter support, checking my profile, etc. Well, then to try something I followed Major Nelson, and it started working! But only for him. I then found a friend who had last updated a video, but that had been a few weeks ago.
This feature is very time dependent. So, instead of being my friends uploads, its more so their 'recent' uploads, and by recent does not mean their last, but recent in time, like a week or so.
Now that Titanfall is out a friend has been uploading some videos and it works as it should.
Comment: Good catch on the feed being time sensitive! Hadn't thought of that!

Viewing friends' uploads on Xbox One


Map function on object containing mutliple arrays

Question: I have a props object, with a user comment array, and the userId array inside. Originally i only had the user comment array, and so i used the map function to style each comment individually. Now that i have two arrays inside my props object, is there a way to use the map function to style both the users comment and his id at the same time? Here is my attempt at it but it doesnt work:
import React from 'react'
import faker from 'faker'

const UserComment = (props)=> {
    var commentData = props.map(props=> {
        return(


How do I ensure that all the images are aligned correctly in differing browser windows/resolutions?

Question: Firstly, there are 3 separate images. A chick, the word 'delivery' and 'foodstant' I wanted to align them in such a way--> 3 images
Are there any methods to achieve such positioning which enables an unchanged position despite the resizing of the browser window and perhaps resolution ?
Both Absolute and relative positioning works, but resizing the browser screws up everything.
Margins can't seem to do the trick.. Or I am just less-skilled.
HTML code as follows:
<!doctype html>

    <meta charset="UTF-8"/>
    <title> Foodstant Delivery </title>
    <link rel="stylesheet" type="text/css" media="screen" href="stylo.css" />
    <link rel="shortcut icon" href="favicon.ico" />

Home

Menu

Contact Us

About Us

Terms & Conditions

Jobs

Your Order

CSS code as follows
/* Foodstant Delivery */

* {
margin: 0;
padding:0;
  }
 body { font-family: 'Comic Sans MS',Verdana,Helvetica,Courier New,sans-serif;
background:url("images/bg.jpg");
   }
   /* home page */
  #hnavbar{
font-size:2em;
margin-top:-13em;
}
  #hnavbar ul li {
    list-style-type:none;
    width:325px;
    display:inline;
    padding:0 13px 0 13px;
    }
  #chi {
position:relative;
top:-30em;
left:10em;
       }
  #foo {
position:relative;
top:1em;
left:-11em;
   }
  #del {
position:relative;
top:10.5em;
left:26em;
}
 /* home page */

Many thanks in advance.
Answer: I recently had to do something very similar to this and after some time I decided I had to use absolute positioning to every link. The problem with your code is that it seems that you don't quite understand how relative and absolute positioning works. Absolute objects are always relative to it's nearer parent set to "relative position". So you should try this:
#hnavbar { position: relative; } //all "absolute" children will be relative to this hnavbar
#home, #menu, ... { position: absolute; }

And after that, you should set the position of every absolute positioned menu link with top/left or bottom/right properties.
For the image, if you don't have links for "Foodstant" and "Delivery", I would really use one single image.
Hope it helps!
Answer: Specify the values for top and left in percents as opposed to 'em'. These percentages would be relative to the parent element containing these image.  OR simply use one single image instead of 3 and use a image map. Here s a coupla online tools to do this:
http://www.mobilefish.com/services/image_map/image_map.php
http://www.image-maps.com/
Comment: The parent element for the images in this case is  ?
Comment: It's a HTML5 element for marking up images, illustrations etc.


XElement with colon in the name doesn't work

Question: i'm trying to make something like :
new XElement("media:thumbnail", new XAttribute("width", ""))

but i doesn't work, and i got a error because of the colon ':'.
does anyone know how can I solve the problem ?
Answer: That's not how you create an XName with a namespace.
You should create an XNamespace with the right URI, and then you can create the right XName easily - personally I use the + operator. So:
XNamespace media = "... some URI here ...";
XElement element = new XElement(media + "thumbnail", new XAttribute("width", "");

To use a specific namespace alias, you need to include an attribute with the xmlns namespace, which can be in a parent element.
Here's a complete example:
using System;
using System.Xml.Linq;

public class Test
{
    static void Main()
    {
        XNamespace ns = "http://someuri";
        var root = new XElement("root",
                                new XAttribute(XNamespace.Xmlns + "media", ns),
                                new XElement(ns + "thumbnail", "content"));
        Console.WriteLine(root);
    }
}

Output:
<root xmlns:media="http://someuri">
  <media:thumbnail>content</media:thumbnail>
</root>

Obviously you need to use the right namespace URI though...
Comment: @AdamB: That suggests you're using `media` as your namespace *URI*, which is almost certainly incorrect. Read my answer carefully, including the example.
Comment: Hi @jon , I did it but my input is


How to add space to Exec path in a Thumbnailer description?

Question: I wish to use mplayer to generate thumbnails for nautilus, so I wrote a perl script as the thumbnailer named "gnome_thumbnailer_with_mplayer", and wrote a description in /usr/share/thumbnailers to tell the system to find the thumbnailer.
At the beginning, the description is:
[Thumbnailer Entry]
TryExec=/home/allfox/programs/gnome_thumbnailer_with_mplayer
Exec=/home/allfox/programs/gnome_thumbnailer_with_mplayer %u %o %s
MimeType=application/vnd.rn-realmedia;application/mxf;application/ogg;application/ram;application/sdp;application/vnd.ms-wpl;application/x-extension-m4a;application/x-extension-mp4;application/x-flash-video;application/x-matroska;application/x-netshow-channel;application/x-ogg;application/x-quicktimeplayer;application/x-shorten;image/vnd.rn-realpix;image/x-pict;misc/ultravox;text/x-google-video-pointer;video/3gpp;video/dv;video/fli;video/flv;video/mp2t;video/mp4;video/mp4v-es;video/mpeg;video/msvideo;video/ogg;video/quicktime;video/vivo;video/vnd.divx;video/vnd.rn-realvideo;video/vnd.vivo;video/webm;video/x-anim;video/x-avi;video/x-flc;video/x-fli;video/x-flic;video/x-flv;video/x-m4v;video/x-matroska;video/x-mpeg;video/x-ms-asf;video/x-ms-asx;video/x-msvideo;video/x-ms-wm;video/x-ms-wmv;video/x-ms-wmx;video/x-ms-wvx;video/x-nsv;video/x-ogm+ogg;video/x-theora+ogg;video/x-totem-stream;audio/x-pn-realaudio;audio/3gpp;audio/ac3;audio/AMR;audio/AMR-WB;audio/basic;audio/midi;audio/mp2;audio/mp4;audio/mpeg;audio/ogg;audio/prs.sid;audio/vnd.rn-realaudio;audio/x-aiff;audio/x-ape;audio/x-flac;audio/x-gsm;audio/x-it;audio/x-m4a;audio/x-matroska;audio/x-mod;audio/x-mp3;audio/x-mpeg;audio/x-ms-asf;audio/x-ms-asx;audio/x-ms-wax;audio/x-ms-wma;audio/x-musepack;audio/x-pn-aiff;audio/x-pn-au;audio/x-pn-wav;audio/x-pn-windows-acm;audio/x-realaudio;audio/x-real-audio;audio/x-sbc;audio/x-speex;audio/x-tta;audio/x-wav;audio/x-wavpack;audio/x-vorbis;audio/x-vorbis+ogg;audio/x-xm;application/x-flac;

Everything works. But later I realized that I can sync this kind of little script to Ubuntu One, so I moved the thumbnailer(named "gnome_thumbnailer_with_mplayer", not the description) to ~/Ubuntu One. Then I changed the description to:
[Thumbnailer Entry]
TryExec=/home/allfox/Ubuntu\ One/fun_goods/thumbnailer/gnome_thumbnailer_with_mplayer
Exec=/home/allfox/Ubuntu\ One/fun_goods/thumbnailer/gnome_thumbnailer_with_mplayer %u %o %s
MimeType=application/vnd.rn-realmedia;application/mxf;application/ogg;application/ram;application/sdp;application/vnd.ms-wpl;application/x-extension-m4a;application/x-extension-mp4;application/x-flash-video;application/x-matroska;application/x-netshow-channel;application/x-ogg;application/x-quicktimeplayer;application/x-shorten;image/vnd.rn-realpix;image/x-pict;misc/ultravox;text/x-google-video-pointer;video/3gpp;video/dv;video/fli;video/flv;video/mp2t;video/mp4;video/mp4v-es;video/mpeg;video/msvideo;video/ogg;video/quicktime;video/vivo;video/vnd.divx;video/vnd.rn-realvideo;video/vnd.vivo;video/webm;video/x-anim;video/x-avi;video/x-flc;video/x-fli;video/x-flic;video/x-flv;video/x-m4v;video/x-matroska;video/x-mpeg;video/x-ms-asf;video/x-ms-asx;video/x-msvideo;video/x-ms-wm;video/x-ms-wmv;video/x-ms-wmx;video/x-ms-wvx;video/x-nsv;video/x-ogm+ogg;video/x-theora+ogg;video/x-totem-stream;audio/x-pn-realaudio;audio/3gpp;audio/ac3;audio/AMR;audio/AMR-WB;audio/basic;audio/midi;audio/mp2;audio/mp4;audio/mpeg;audio/ogg;audio/prs.sid;audio/vnd.rn-realaudio;audio/x-aiff;audio/x-ape;audio/x-flac;audio/x-gsm;audio/x-it;audio/x-m4a;audio/x-matroska;audio/x-mod;audio/x-mp3;audio/x-mpeg;audio/x-ms-asf;audio/x-ms-asx;audio/x-ms-wax;audio/x-ms-wma;audio/x-musepack;audio/x-pn-aiff;audio/x-pn-au;audio/x-pn-wav;audio/x-pn-windows-acm;audio/x-realaudio;audio/x-real-audio;audio/x-sbc;audio/x-speex;audio/x-tta;audio/x-wav;audio/x-wavpack;audio/x-vorbis;audio/x-vorbis+ogg;audio/x-xm;application/x-flac;

But it not works. I just can't get any thumbnail in nautilus. I thought the only change I made is the TryExec and Exec path, and the new path contains a space, this maybe the problem, how can I fix it?
I'm using 12.04 LTS.
Answer: For the record, you can also synchronize other folders in your home directory with Ubuntu One, rather than simply copying all the files you want synchronized into ~/Ubuntu One.
Also, you can use quotes in the Exec line (not sure about TryExec). So Exec="/home/allfox/Ubuntu One/fun_goods/thumbnailer/gnome_thumbnailer_with_mplayer" %u %o %s should work. You can try using the quotes in TryExec as well. If the quotes don't work there, you can also probably just remove the TryExec line, and it should work.
Also of note, is that Ubuntu One does not preserve permissions bits, so the executable bit on the script may have been lost, and thus the script would fail to execute as a result.
Comment: @allfox_五月 to get around Ubuntu One not synchronizing permission bits, you can explicitly call perl in the Exec line, giving it your script as an argument.
Comment: Thanks for your answer! I followed your direction and got the solution, I wish to post it via comment, but just why I can't start a newline in comment? So I started a new answer.
Answer: Thanks for dobey's direction! It is a quoting problem.
I read a document here: https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html
There are two rules: 1-We should use \s to represent space in normal lines; 2-The Exec line is special, if there is space in any part of it, we have to quote that part.
For the TryExec line, it is a normal line, so I should write TryExec=/home/allfox/Ubuntu\sOne/fun_goods/thumbnailer/gnome_thumbnailer_with_mplayer.
For the Exec line, I should write Exec="/home/allfox/Ubuntu One/fun_goods/thumbnailer/gnome_thumbnailer_with_mplayer" %u %o %s.
Now, it is working ;)
Why those specifications do not use the same rule on all lines? It took me so much time to find out the problem >_< .
For anyone need, I also post my thumbnailer here:
#!/usr/bin/env perl
use strict;
use 5.010;

# allfox's GNOME thumbnailer using MPlayer

use File::Temp qw(tempdir);
use List::Util qw(min);
use File::Spec qw();
use URI::Escape qw(uri_unescape);

&thumbnailer(@ARGV);
sub thumbnailer
{
    my($mplayer) = `which mplayer`;
    chomp $mplayer;
    my($input, $output, $size) = @_;
    $input = uri_unescape($input);
    $output = uri_unescape($output);
    if($input =~ /\.part$/i)
    {
        return;
    }
    my $common_arguments = '-nosound -noautosub -really-quiet -noar -noconsolecontrols -nojoystick -nolirc -nomouseinput -nosub';
    my $video_information = `$mplayer -identify -frames 0 $common_arguments '$input'`;
    $video_information =~ /^ID_VIDEO_WIDTH=(?<width>[0-9.]+)
                .*
                ^ID_VIDEO_HEIGHT=(?<height>[0-9.]+)
                .*
                ^ID_LENGTH=(?<length>[0-9.]+)
                /msix;
    my $width = $+{'width'} / 1;
    my $height = $+{'height'} / 1;
    my $length = $+{'length'} / 1;
    if(defined $size)
    {
        if($width > $height)
        {
            my $scale_to = min $width, $size;
            $width = $scale_to;
            $height = $height * ($scale_to / $width);
        }
        else
        {
            my $scale_to = min $height, $size;
            $width = $width * ($scale_to / $height);
            $height = $scale_to;
        }
    }
    my($temp_frames) = tempdir('gnome_thumbnailer_with_mplayer-XXXXXXXXXXXX', TMPDIR => 1, CLEANUP => 1);
    for(1..3)
    {
        $length /= 3;
        if(0 == system "$mplayer -vo jpeg:quality=100:outdir='$temp_frames' -ss $length -frames 1 $common_arguments '$input'")
        {
            last;
        }
    }
    my $convert = `which convert`;
    chomp $convert;
    opendir TEMP_FRAMES, $temp_frames;
    for(readdir TEMP_FRAMES)
    {
        if(/^\d+/)
        {
            my $jpeg_result = File::Spec->catfile($temp_frames, $_);
            system "$convert '$jpeg_result' -thumbnail ${width}x$height png:'$output'";
            last;
        }
    }
    closedir TEMP_FRAMES;
}


Custom Stripe checkout button not working without duplicate script

Question: I have a Stripe Checkout button in a Rails application (Part 1 below) that works well. I wanted to customize the button style, so I followed the guide here and added a custom Javascript and button (Part 2).
When both of these parts are included, the second button (Part 2) works well. When I delete Part 1, the second button doesn't pop up the Checkout dialog - instead, it just submits the form without a stripeToken and stripeEmail, causing an error.
Can someone shed some light on what's happening and how to fix this?

<button class="btn btn-primary btn-large" id="subscription-button">Subscribe Now</button>

Answer: I ran into a same problem while following a similar tutorial.
Including the javascript include tag in the view's layouts file solved the issue.
The view charges/new.html.erb is like :

<%=form_tag charges_path do %>

    <% if flash[:error].present? %>

<%=flash[:error] %>

    <% end %>

    <%=label_tag(:amount, 'Donation Amount:') %>
    <%=text_field_tag(:amount) %>

    <%=hidden_field_tag(:stripeToken) %>

  <button id='donateButton'>Donate</button>
<% end %>

every time our custom button was pressed, the checkout.js script failed to load and the further code started executing.
To solve the problem, just include
<%= javascript_include_tag "https://checkout.stripe.com/checkout/", "application" %>

in your supporting layout file(i.e., layouts/charges.html.erb in this case) inside the  tag.


Is the series uniform convergent in $(0,\infty)$?

Question: For  $$f(x)=\sum_{n=1}^{\infty}\frac{1}{1+n^2x}$$
And is it bounded in $(0,\infty)$?
Comment: $\displaystyle\sum_{n=-\infty}^{\infty}\frac{1}{1+n^2x^2}=\frac\pi x\coth\frac\pi x$
Comment: @Lucian how lead to this conclusion?
Answer: not uniformly convergent, since by picking $x = 1/n^2$ you can get the $n$-th term to be $1/2$ and since $n$ was arbitrary and your series has positive terms this contradicts uniform convergence. it's also not bounded since the terms are decreasing for a fixed $x$. what we've done before shows that you can get a sum bigger than $n/2$ for any $n$.
Comment: why $\frac{n}{2}$??
Comment: we've shown that the $n$-th term is equal to $1/2$ with this choice of $x$. therefore all the first $n$ terms are $\geq 1/2$ and hence the result (we neglect all the terms apart from the first $n$)
Answer: Note that
$$\sup_{x}\sum_{k=n+1}^{\infty}\frac{1}{1+k^2x}\geq\sup_{x}\sum_{k=n+1}^{2n}\frac{1}{1+k^2x}\geq \sup_{x}\frac{n}{1+4n^2x}=n$$
which does not converge to $0$.  So the convergence is not uniform.
Comment: I have difficulty understanding the second $\ge$..
Comment: There are $n$ terms each larger than the last term.
Comment: and why does it equal to $n$?
Comment: As $x$ goes to $0$ it increases to $n$, becoming arbitrarily close. Hence the sup is n and the sequence of partial sums does not uniformly satisfy the Cauchy criterion for $x >0$.


Removing all punctuation from string in dataframe

Question: This is officially doing my head in. I am web scraping a collection of tweets for text analysis. The tweets have been scraped and put into a dataframe, where each row is a string containing the entire tweet. I can't for the life of me remove quotation marks or apostrophes, but removing all other punctuation is OK.
What I am trying to do is extract just the verbs, nouns and adjectives from each of the scraped tweets, which I have done, but anything in quotation marks is excluded.
The code that I have been using so far is below, but I can't for the life of me add quotation marks or apostrophes. I have also tried every other method I can find on this site , but it either does nothing, or produces errors.
tweets['Text_processed'] = tweets['Text'].map(lambda x: re.sub('[,\@#.!?]', "", x))

The entire code base up until this point is:
import GetOldTweets3 as got
import pandas as pd
import re
from wordcloud import WordCloud# Join the different processed titles together.
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.simplefilter("ignore", DeprecationWarning)# Load the LDA model from sk-learn
from sklearn.decomposition import LatentDirichletAllocation as LDA
import os
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly as py
import plotly.graph_objs as go
import gensim
from gensim import corpora, models, similarities
import logging
import tempfile
from nltk.corpus import stopwords
from string import punctuation
from collections import OrderedDict
import pyLDAvis.gensim
import tempfile

%matplotlib inline

init_notebook_mode(connected=True) #do not miss this line
warnings.filterwarnings("ignore")

# Function that pulls tweets based on a general search query and turns to csv file
# Parameters: (text query you want to search), (max number of most recent tweets to pull from)

def text_query_to_csv(text_query, count):
    # Creation of query object
    tweetCriteria = got.manager.TweetCriteria().setQuerySearch(text_query)\
                                                .setMaxTweets(count)
    # Creation of list that contains all tweets
    tweets = got.manager.TweetManager.getTweets(tweetCriteria)
    # Creating list of chosen tweet data
    text_tweets = [[tweet.date, tweet.text] for tweet in tweets]
    # Creation of dataframe from tweets
    tweets_df = pd.DataFrame(text_tweets, columns = ['Datetime', 'Text'])
    # Converting tweets dataframe to csv file
    tweets_df.to_csv('{}-{}-tweets.csv'.format(text_query, int(count)), sep=',')

############################################
# Search word and number of tweets to scrape
############################################

text_query = '#barackobama'

count = 5

# Calling function to query X amount of relevant tweets and create a CSV file
text_query_to_csv(text_query, count)

filename = '#barackobama-5-tweets.csv'

tweets = pd.read_csv(filename)

# Convert tweets to strings and lower case
tweets['Text'] = tweets['Text'].astype(str)
tweets['Text'] = tweets['Text'].map(lambda x: x.lower())

tweets

This is the offending bit of code below...
# remove punctuation
tweets['Text_processed'] = tweets['Text'].map(lambda x: re.sub('[,\@#.!?]', "", x))
tweets['Text_processed'].head()

#####################################
# Extract nouns, verbs and adjectives
#####################################

import nltk
from nltk import word_tokenize, pos_tag
from nltk.corpus import wordnet

from IPython.display import display
lemmatizer = nltk.WordNetLemmatizer()

def leaves(tree):
    """Finds NP (nounphrase) leaf nodes of a chunk tree."""
    for subtree in tree.subtrees(filter = lambda t: t.label() =='NP'):
        yield subtree.leaves()

def get_word_postag(word):
    if pos_tag([word])[0][1].startswith('J'):
        return wordnet.ADJ
    if pos_tag([word])[0][1].startswith('V'):
        return wordnet.VERB
    if pos_tag([word])[0][1].startswith('N'):
        return wordnet.NOUN
    else:
        return wordnet.NOUN

def normalise(word):
    """Normalises words to lowercase and stems and lemmatizes it."""
    word = word.lower()
    postag = get_word_postag(word)
    word = lemmatizer.lemmatize(word,postag)
    return word

def get_terms(tree):
    for leaf in leaves(tree):
        terms = [normalise(w) for w,t in leaf]
        yield terms

tidied_tweets = []

for t in tweets['Text']:
    #word tokenizeing and part-of-speech tagger
    document = t
    tokens = [nltk.word_tokenize(sent) for sent in [document]]
    postag = [nltk.pos_tag(sent) for sent in tokens][0]

    # Rule for NP chunk and VB Chunk
    grammar = r"""
        NBAR:
            {<NN.*|JJ>*<NN.*>}  # Nouns and Adjectives, terminated with Nouns
            {<RB.?>*<VB.?>*<JJ>*<VB.?>+<VB>?} # Verbs and Verb Phrases

        NP:
            {<NBAR>}
            {<NBAR><IN><NBAR>}  # Above, connected with in/of/etc...

    """
    #Chunking
    cp = nltk.RegexpParser(grammar)

    # the result is a tree
    tree = cp.parse(postag)

    terms = get_terms(tree)

    features = []
    for term in terms:
        _term = ''
        for word in term:
            _term += ' ' + word
        features.append(_term.strip())

    tidied_tweets.append(features)

tidied_tweets

The code base I have after this works OK, but the inability to remove quoted text or anything with an apostrophe is causing real problems.
EDITED TO ADD
I've managed to solve the problem, but in doing so, created another. The latest bit of code to extract the words sans the punctuation is:
tweet_list = []
ind_tweet = []

for tweets in tidied_tweets:
    for words in tweets:
        a = re.findall(r"[\w']+", words)
        ind_tweet.append(a)
    tweet_list.append(ind_tweet)

re.findall(r"[\w']+", words) does the job of extracting the word, but I can't create the same structured list I started with. What I wanted is 'tweet_list' to act as the parent list, and 'ind_tweet' to act as a sucession of child lists (nested). When I print out the result of the code above, I'm not able to create the nested list I am looking for. ind_tweet produces the output but in a single list with no nesting, and tweet_list duplicates ind_tweet. It probably isn't helping that it's 2:30am on a Saturday, but this should be much easier than I am making it...
Answer: And the answer is...
tweet_list = [[] for i in range(len(tidied_tweets))]

for tweets, t in zip(tidied_tweets, range(len(tidied_tweets))):
    for words in tweets:
        a = re.findall(r"[\w']+", words)
        tweet_list[t].append(a)


Input type = "submit" not working in custom-control

Question: for some reason my input type= "submit" is not working (it's only working for the 1st time). I wrote the input in a custom-control. Will that be a problem?  Help is much appreciated. Thanks. Here is my code.

page.zoom = 4;

page.btn_Click = function() {

  if (page.MobileNo) {
    $http.get(serviceBasePath + '/api/Map/GetDeviceLocation?MobileNo=' + page.MobileNo).then(function(response) {

      var deviceindex = page.DeviceData.findIndex(x => x.DeviceId== response.data.DeviceId);
      if (deviceindex == -1) {
        page.DeviceData.push(response.data);
        page.zoom = 14;
        page.center = response.data.Location.position;
      } else {
        page.zoom = 14;
        page.center = response.data.Location.position;
      }

    }, function(error) {})
  }
}
<custom-control style="padding-left:10px; padding-top:10px" position="TOP_LEFT" index="2" on-click="page.btn_Click()">

  <input type="submit" class="form-control" value="GO">

</custom-control>
Comment: what is page in js?
Comment: it's a razor page ( .cshtml ) sir.
Comment: why you want to submit you can simply give button?
Comment: The same happening with button too sir. When i press enter or go button, it seems to be working fine ( as it is supposed to), but after the 1st trail, the button becomes irresponsive or rather numb.
Answer: I think you are missing form tag. try this..
HTML::
<custom-control style="padding-left:10px; padding-top:10px" position="TOP_LEFT" index="2" on-click="page.btn_Click()">
  <form name="formName" onsubmit="submitForm()">
    <input type="text" name="firstName" placeholder="Enter Your Name">
    <input type="submit" class="form-control" value="GO">
  </form>
</custom-control>

Script::
function submitForm(){
  //... do something..
};

if you want some action on ENTER key then you must have some text fields, else on click it will work.


Home HVAC condenser fan not spinning

Question: The Bryant condenser outside the house was making a noise like it wants the fan to spin but the fan wasn't spinning. I pushed the fan with a stick and it started spinning, but reluctantly, like 4 revolutions per second.
What is this symptomatic of? What is the potential solution? Can a DIYer do it?
My research shows that I have a "bad fan motor and/or bad start capacitor". Does that sound right?
Thanks!
Answer: The capacitor is the most likely culprit . They are easy to change out (with the power off). They are usually silver cans with several connections on 1 end. You need to find the size it will be something like 15mfd then the voltage. It may be a dual element then there will be 2 numbers like 15 - 28 mfd.
Make sure to write down the terminals the diferent wires go to so you get them correct on the new one. The caps can be found on line for the best price.
Comment: Will try it out tonight.
Comment: Indeed, it was the blown start-run capacitor. A ten minute repair. I wonder how much an HVAC company would've charged.

Home HVAC condenser fan not spinning


Can my DLL check conditions in the calling app at compile time?

Question: Short version:
I'm making a DLL that I intend to pass around the department, and it requires certain values to be present in the web.config of the app that references it. Is there any way to make my DLL check for these values before run time?
Long version, with background info:
We're using website-level web.config files to configure environment information for multiple websites/WCF services on the same server. When developing these apps, I have the debug versions of the web.config insert test values, and all is well. However, I'd like to reduce the hidden requirement as much as possible for future users [me, in a year, when I forget all this] and make missing config settings as obvious as possible. If a reference or build time solution is impossible or unfeasible, what's the earliest run-time opportunity my DLL can hook into to check its configuration?
Also- we're using the built-in application configuration classes to decrypt settings automatically at run time, as well as taking advantage of the configuration hierarchy, so we're locked into using app/web.config files. If anyone knows a more solid way of designing the system with regards to referenced assemblies requiring configuration entries, I would appreciate suggestions.
Answer: There is no real Main equivalent for a DLL.  The best option is to guard all of your DLL entry points with the method that will validate the configuration (and presumably cache the result).
Unfortunately depending on the contents of your DLL this can be quite time consuming.  The best way to start is looking at all of the public types and static methods.  These are your most obvious entry points to the code base.
This may also be a good time to review your entry points and limit them to a managable level :)
Comment: Given that nobody else is coming forward, I guess "you can't do that" is the right answer, albeit a depressing one. Thanks anyway!


selenium 3.4 with Safari 11 compatibility issues

Question: We are having lot of tests failing with the combination of selenium 3.4 with Safari 11 browser on Mac OS Sierra, where almost all other browsers are working more or less reasonably OK.
Is there any special wiki, forum or location which explains what are the compatibility issues between them and how to resolve them ?
Answer: It might be an issue related with Selenium Browser compatibility. Try to upgrade Selenium version to 3.9.1 or even higher 3.11.0 (which is compliance with the w3c standard)


vscode can't find buildifier on remote instance

Question: I'm bumping into a weird vscode issue. I use vscode to ssh into my EC2 instance. I primarily use bazel as the dependency management and build system for development. I installed buildifier, and included in my path variable however vscode still doesn't detect it. If I type buildifier <some bazel build file> in the terminal in vscode, it works perfectly, but if I try to use the formatting shortcut on the file using vscode, it doesn't. I went to the extension settings, and in the remote settings I explicitly put buildifier as the executable command. Still not working. Any help would be appreciated.
Thanks!
Answer: It's likely that the path you've set is set somewhere that the vscode remote server isn't looking. So it might be in your shell path but not the vscode remote servers path when it starts up.
As a workaround find the full path of buildifier e.g.
whereis buildifier

Then simply copy past the full path of buildifier into your settings under the Bazel: Buildifier Executable section.


Ww2 call of duty, can hear sound but no picture

Question: I just downloaded this game and it shows the beginning of the maker and stuff. Now after that the screen is black but I can hear the music in the background. Is it still downloading?
Comment: Where'd you get it from? Do you meet the system requirements?
Comment: I bought it at target brand new. Yes I checked the requirements and everything seems good. Like right now it's on the main menu of the ps4 where it says "start" I can see where it looks like it's still loading  but it's just weird that I can hear the music of the game just the picture I cannot see
Comment: Can I delete it from the ps4 and re install it?
Comment: You can certainly try that (whether you bought it digitally or on disc).  I would also check all of your cabling to your display and make sure they are connected fully.
Answer: That happened to me too. The game was working ok for a few days then a black screen appears after the Activision/Sledgehammer intro.  I can hear music but no picture. I did a hard reset on the PS4 and it's seems to work. I hope this helps.


How to optimize query which count last rows up to a certain condition?

Question: I have table test:
create table test
(
    id         serial
        primary key,
    status_id  integer,
    created_at timestamp with time zone default now() not null,
    client_id  integer
);

and I need to count all last rows with status_id != 3 sorted by created_at desc.
Such table:
id, status_id, created_at, client_id
(1, 3, '2023-04-23 19:34:08.454000 +00:00', 2),
(2, 3, '2023-04-23 19:34:07.493000 +00:00', 2),
(3, 3, '2023-04-23 19:34:06.459000 +00:00', 2),
(4, 2, '2023-04-23 19:34:05.838000 +00:00', 2),
(5, 3, '2023-04-23 19:34:04.782000 +00:00', 2),
(6, 3, '2023-04-23 19:34:03.768000 +00:00', 2),
(7, 2, '2023-04-23 19:34:02.768000 +00:00', 2),
(8, 3, '2023-03-23 19:34:02.768000 +00:00', 1),
(9, 2, '2023-02-23 19:34:02.768000 +00:00', 1),
(10, 3, '2022-04-23 19:34:02.768000 +00:00', 1);

result for client with id 1 must be 3 and for client with id 2 will be 1:
client_id, count
    2,3
    1,1

I have this query:
select count(*), i.client_id
from public.test i
where i.created_at > (select x.created_at
                      from public.test x
                      where x.status_id != 3
                        and x.client_id = i.client_id
                      order by x.created_at desc
                      limit 1)
group by i.client_id;

its works but very slow.
tried this index:
create index test_status_id_client_id_created_at_index
on public.test (status_id, client_id, created_at);

but index does not help.
Is there a way to optimize and speed up this query, or will it be necessary to make some kind of application that will export this data in a ready-made form in small time intervals?
explain:
GroupAggregate  (cost=12.80..12.85 rows=3 width=12) (actual time=0.149..0.152 rows=2 loops=1)
  Group Key: i.client_id
  ->  Sort  (cost=12.80..12.81 rows=3 width=4) (actual time=0.144..0.145 rows=4 loops=1)
        Sort Key: i.client_id
        Sort Method: quicksort  Memory: 25kB
        ->  Seq Scan on test i  (cost=0.00..12.77 rows=3 width=4) (actual time=0.054..0.091 rows=4 loops=1)
              Filter: (created_at > (SubPlan 1))
              Rows Removed by Filter: 6
              SubPlan 1
                ->  Limit  (cost=1.16..1.16 rows=1 width=8) (actual time=0.007..0.007 rows=1 loops=10)
                      ->  Sort  (cost=1.16..1.16 rows=1 width=8) (actual time=0.007..0.007 rows=1 loops=10)
                            Sort Key: x.created_at DESC
                            Sort Method: quicksort  Memory: 25kB
                            ->  Seq Scan on test x  (cost=0.00..1.15 rows=1 width=8) (actual time=0.001..0.002 rows=2 loops=10)
                                  Filter: ((status_id <> 3) AND (client_id = i.client_id))
                                  Rows Removed by Filter: 8
Planning Time: 0.826 ms
Execution Time: 0.314 ms

I use postgresql 14 version.
sqlfiddle
Comment: Hi - can you explain what you mean by "count all last rows" , what's a "last row"? Also, I think you have your results the wrong way round - the sqlfiddle shows the count for client 1 is 1, not 3
Comment: "Very slow" and then just 1.1 milliseconds for this query, don't match.
Comment: Why are you using a sub-query? I don't understand the output you are trying to get?
Comment: The created at values in your question are in the opposite order to your fiddle. Attention to detail matters.
Comment: @FrankHeikens i cannot execute query in production database during thirty mins
Comment: @BenKoshy https://i.imgur.com/lT4E7KF.jpeg
Comment: @wisicoc this is very confusing for me. are we filtering with status_id = 3 or not?
Answer: I'd replace the correlated sub-query with a regular sub-query, and join on it.
SELECT
  last.client_id,
  COUNT(*)
FROM
(
  SELECT
    client_id,
    MAX(created_at)   created_at
  FROM
    public.test
  WHERE
    status_id <> 3
  GROUP BY
    client_id
)
  AS last
INNER JOIN
  public.test
    ON  test.client_id  = last.client_id
    AND test.created_at > last.created_at
GROUP BY
  last.client_id;

Then ensure an index on (client_id, created_at) and a partial index on (client_id, created_at) WHERE status_id <> 3


convert index format date

Question: I have a data Series in which the index is a list of dates
IN: [318]: weightedflows
Out[318]:

2015-01-31 00:00:00                0
2015-02-28 00:00:00                0
2015-02-28 00:00:00.1              0
2015-02-28 00:00:00.2              0
2015-03-31 00:00:00                0
2015-03-31 00:00:00.1              0
2015-03-31 00:00:00.2    1.77419e+07
2015-03-31 00:00:00.3     1.6129e+07
2015-03-31 00:00:00.4              0

What i'd like to do is reformat the values in the index of this Series so that it reads as 2/28/2015 or 3/31/2015.  How do I reformat the index of this Series?  Not sure how datetime can be applied here?
I tried weightedflows.index.strftime("%m/%d/%Y") but get 'Index' object has no attribute 'strftime'.  If it helps, my data type is pandas.core.indexes.base.Index
Comment: Possible duplicate of [Format pandas dataframe index date](https://stackoverflow.com/questions/42185328/format-pandas-dataframe-index-date)
Answer: If index consists of datetime objects, then: series.index = series.index.strftime('%m/%d/%Y')
If not, you may have to go out of your way to convert them to datetime objects, so you can revert back to strings: series.index = pd.to_datetime(series.index).strftime('%m/%d/%Y')

convert index format date


How do I hang a 500lb slab of limestone as a new mantel?

Question: We are adding a fireplace outside on our porch, and my wife fell in love with the thought of a limestone mantel.  So, we have a beautiful 90.5"x14"x4" slab of limestone sitting here (just a hair under 500lbs).  There's a 5" ledge built into the framing, and we have 2 limestone corbels already mounted.
So far, the plan is to put custom-made iron angles bolted to the framing at the top of the slab to hold the wall side down, and let the rest of it sit on the ledge/corbels.  Is this enough (the weight supported by the ledge and corbels, the "twist" held down by the L brackets)?
I should also mention that the brick façade is only 1.5-2" thick, restricting the bottom of the L brackets to being that long so they are hidden.  And the corbels are probably 6" on a side at least, so MAYBE enough?
<code>ELEVATION (SIDE) VIEW

|
||
||____ <-- iron angle
|------------------------
|    stone slab
|________________________
|___________       /
  framing   |   __/ <-- corbel
   ledge    |  /
            |_/
            |
</code>
Comment: The answer lies in the integrity of the corbels, I think, and how they're mounted.
Comment: Your profile says Illinois. Anywhere near the Wabash Valley seismic zone? How will the limestone slab be retained if earthquake movement wants to shake it past the lip of the iron angles?
Comment: I don't know how to do the calculations but the thing that stands out to me is the possibility of the stone cracking/breaking where it is unsupported  beyond the ledge and between and outside the corbels.     I think your ledge/corbels can easily be made strong enough to support 500 pounds if the weight was made from imaginary unbreakable material. It's the stone itself I'd look at.  Imagine it cantilevered with all the upward force provided only by the tiny front edges of the corbels.
Comment: I think I follow your plan, but a sketch would help. I'll add one, and you can revise.
Comment: What's custom about the iron angles?
Comment: So, it's about 66 pounds per linear foot, then.
Comment: bolt through the slab into the framing ledge,
Answer: Solved (installed)!  Thanks Isherwood for your sketch, that's exactly what I was trying to describe.  Turns out, however, that the corbels were also held down with "L" brackets, then mortar used to level where those were, and the slab then put on top of it all with angle iron on top (but short enough projection out that it is covered by the brick façade applied last above it).  My contractor seemed more confident than I was originally, but his final solution seems very sturdy and permanent.  (and to answer the other question, no, we're quite a ways off of the Wabash earthquake zone.  Probably a little more worried about New Madrid, but not close to that, either.)  Again, thanks to you all for your help!


fetching Facebook friend list?

Question: This is giving empty array.Here is my code please help me out
Am I missing something here???
<code> -(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user
        {
         [FBRequestConnection startWithGraphPath:@"/me/friends"
                                             parameters:nil
                                             HTTPMethod:@"GET"
                                      completionHandler:^(
                                                          FBRequestConnection *connection,
                                                          id result,
                                                          NSError *error
                                                          ) {
                                          NSLog(@"me/friends result=%@",result);

                                          NSLog(@"me/friends error = %@", error.description);

                                          NSArray *friendList = [result objectForKey:@"data"];
                                          //[m_allFriends addObjectsFromArray: friendList];
                                      }];
        }
</code>
Comment: Then why it is returning empty array???
Comment: You have to put Facebook App in review..
Comment: https://developers.facebook.com/docs/apps/review#instructions
Answer: You can no longer get the entire list of friends.
Now the list will be limited to only those friends who also happen to use your app.
To quote Facebook Graph API 2.0 doc:

Permissions
A user access token with user_friends permission is required to view
  the current person's friends. This will only return any friends who
  have used (via Facebook Login) the app making the request.

So <code>/me/friends</code> will only return your friends that have logged in and given permission to the same app.(you and your friends need to have permitted your app to use facebook via login)
Answer: Only those friends who have authorized access to your app will be returned in this array. So if none of your apps have authorized your app it will return empty array.
If you want to test this you can authorize your app from one of your friends account and than when you test is using your account , you will receive 1 object in array
This has changed since Graph API 2.0
Please read following block of information fetched from facebook Graph API docs

A user access token with user_friends permission is required to view    the current person's friends.
This will only return any friends who have used (via Facebook Login) the app making the request.
If a friend of the person declines the user_friends permission, that friend will not show up in the friend list for this person.

You can find this here

fetching Facebook friend list?


How to repair a Shark nv352 vacuum cleaner motor gasket?

Question: Here is a Shark nv352 vacuum cleaner motor with a broken gasket:

A closeup:

It seems to be 3 3/4" in diameter.  I'm not sure of the material.  It is not currently pliable.
The motor works perfectly well, but the vacuum cleaner started making a huge whining noise.  I think this gasket probably dampens vibration?
Anyway, is it possible to buy a replacement gasket? Is it standard?  What is it made of?
It seems to be somewhat stuck on.  I imagine I can pry the rest of it off with a screwdriver, but I don't know if I can get a replacement.
I can get a replacement motor on ebay.  Do I have to?  The motor itself works perfectly well.
EDIT: Is this a gasket, or an o-ring, or something else?  It seems to have some depth and shape to it, and I'm noticing youtube videos about cork gaskets seem to indicate they are flat.
Comment: The material looks like cork.  Not sure where to buy one, but auto parts store should have cork sheets to make one.
Comment: Oh, thanks. How does someone make one? .. Oh, I'll look on youtube.
Comment: Do you think it's a standard size? I measured 3 3/4", which seems odd. (I'm wondering if I can buy a pre-made one.)
Comment: Also, should I prefer cork, or cork-rubber?
Comment: It is not made from cork, it is custom made to fit the grove
Comment: Thanks. Custom made from what material? And, do I need to use that, or could I use cork?
Comment: I do not know the material, but you could use plumber putty and form it to fill the notch
Comment: It looks like the other half of that piece is still stuck inside the housing...
Comment: To whoever closed this: it wasn't a product or service recommendation question. It was a question about how to repair something. Fortunately, I got some good comments that led me to a good solution (scrape the gasket away, deposit silicon, which is heat resistant), which I then posted. The question and solution will not become obsolete quickly, it will work with many things in the future that have a gasket. I just happened to mention the brand.
Answer: After scraping the old gasket away with a razor, I ended up using 100% silicone 2 to form a new gasket by depositing the silicone in a layer where the old gasket was.  It did not have to be precise, just absorb vibration.
I also put the silicone on two other plastic pieces that looked to be holding foam wedges to dampen vibration.  One of those pieces was missing.

Thanks to the comments who suggested I make a new one.


Site scraping drop down lists using Mechanize and python

Question: I am trying to get the available flights data from a website using mechanize and python, http://www.jet4you.com but the drop down list control shows "none" for the available items. Is there anyway to get the <options> using mechanize, urllib, or beautifulsoup?
When I submit a form using fiddler I see the values of the dropdown list but I cannot select them using mechanize.
br = mechanize.Browser()
br.possible_items("AvailabilityCompactSearchInputViewType$DropDownListMarketOrigin1")
["none"]

Comment: If the dropdown values are loaded from an AJAX call you'll need to either sniff the AJAX requests to the server and emulate them or use something more powerful, that can handle JavaScript and has a full DOM implementation.
Comment: I think @emaster70 is right. You'll find more help in the answers to this [question](http://stackoverflow.com/q/8323728/183066).
Answer: Give up on Mechanize for javascript.  Use a javascript-able browser emulator, such as selenium.  I've tried mechanize for this also, but it just fails.
Comment: [Splinter](http://splinter.cobrateam.info/) can be really helpful and considerably easier than pure Selenium.


Why doesn't Guice from TestNG delivery recognize @javax.inject.Inject while Guice from com.google.inject package does?

Question: I'm trying Guice. I made a simple example which is very similar to the example in the Guice Getting Started manual.
But it didn't work for some time and said:

Could not find a suitable constructor
  in mypack.ServiceUser. Classes must
  have either one (and only one)
  constructor annotated with @Inject or
  a zero-argument constructor that is
  not private.   at
  mypack.ServiceUser.class(ServiceUser.java:14)
  while locating mypack.ServiceUser

The problem was in imports. I attached both Google Guice and TestNG to the project. And I imported classes from org.testng.guice package. But annotation Inject was imported from the javax.inject package. After I changed that import to org.testng.guice.Inject my program began working.
But after that I played with imports a little more. And I changed all org.testng imports to com.google.inject. The program still worked. After that I went back to the @Inject annotation and changed its import to javax.inject.Inject (as it was in my very first broken version). And the program worked even after that.
I checked ones again: Guice from TestNG packages doesn't work with javax.inject.Inject while Guice from google packages (com.google.inject) works normally with it.
Why is it so weird?
p.s. I use last versions of both Guice and TestNG (guice-3.0-rc1 and testng-5.14.5).
Answer: The short answer is: @Guice is still a work in progress and being designed on the mailing-list as we speak, so it's still experimental.
Also, you are using undocumented packages that are reserved for TestNG's internal use (org.testng.guice).
I pushed a new version just today, you can download it at http://testng.org/beta
Note that this new version no longer has org.testng.guice, so make sure that whenever you need Guice symbols, you import them from com.google.inject.
Please post on the testng-users mailing-list if you have any more questions/concerns.
Thanks.
Comment: Thanks for the explanation and for the new version.
Comment: I'm getting the same error while using only com.google.inject and java.inject.Inject.