Android layouts for custom views

Question: I'm trying to create a window with a custom view at the top, and three buttons at the bottom. I would like the view to take up the real estate which is left over after the buttons have been created. My layout XML is as follows
<code><LinearLayout   xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff" >
  <FrameLayout
    android:id="@+id/CustomFrame"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />
  <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:background="#ffffff" >
    <Button
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ok"
        android:layout_marginBottom="10dip"
        android:layout_marginTop="10dip"  />
    <Button
        android:id="@+id/Button02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cancel"
        android:layout_marginBottom="10dip"
        android:layout_marginTop="10dip"  />
    <Button
        android:id="@+id/Button03"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/clear"
        android:layout_marginBottom="10dip"
        android:layout_marginTop="10dip"  />
  </LinearLayout>
</LinearLayout>
</code>
I then add my custom view to the window with the code
<code>  setContentView(R.layout.drawitwindow);
  FrameLayout layout = (FrameLayout)findViewById(R.id.CustomFrame);
  mView = new MyCustomView(this);
  layout.addView(mView);
</code>
in the onCreate method.
However, the custom view takes up the whole screen! If I remove the code which adds the custom view to the frame, the button bar appears at the top of the window (as I would expect).
I've tried overriding the onMeasure method, adding
<code>     super.onMeasure(widthMeasureSpec, heightMeasureSpec);

     int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
     int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
     this.setMeasuredDimension(parentWidth,parentHeight);
</code>
but this doesn't make any difference.
I've tried various combinations of layout width and height, and again that doesn't seem to make any difference.
All help will be very gratefully received...
Answer: Change the FrameLayout android:layout_height to wrap_content.
Also add to the FrameLayout and to the Buttons' Linear Layout android:layout_weight="1.0".
I hope this helps.
Comment: Rui, thanks for the tip. That made things better, but didn't unfortunately solve the problem completely - the buttons now appear, but they have an incorrect (small) height and so the text doesn't show.

I browsed around a few more appends and found a solution which does work. Unfortunately, I can't post the new XML as I'm out of space! Basically, I use a relative layout at the top level, as specified in the question "how to put custom view above built in views in android"

I don't know why I didn't find this topic before; I spent several hours looking for a solution before I asked my question.
Comment: Yes, a relative layout is easier to use. If you played a bit with the layout_weight on each layout, it would work.
Comment: Thanks, Rui - I'll go back to the linear layout and play with the layout_weight as well; it all helps with understanding.

Android layouts for custom views


Constructing a confidence interval question

Question: I'm trying to solve this question but I'm having trouble figuring how to solve it or even start

I know that the final answer is (739.8028 ml, 746.1972 ml) but I'd really appreciate any help on how to get there? Thank you!
Answer: The calculation of the confidence interval of $ 95 \gamma $ percent is generally based on the pivotal quantity, which is a function (in this case) that depends on the random sample and the parameter of interest, that is $ \mu $ .
So the pivotal quantity for this case is $$ Q(x_{1},x_{2},...,x_{n},\mu)=\frac{\bar{x} -\mu} {\sigma/\sqrt n}\sim N(0,1).$$ Thus, Q is the pivotal quantity whose standard normal distribution does not depend on $\mu $, then there are $q_{1},q_{2} $ such that $P(q_{1}<Q <q_{2}) = \gamma $, for $ \gamma $ given in the interval $ (0,1). $
From the above, clearing the parameter of interest, that is $ \ mu $, we have that \ $ P (\bar {x} - \dfrac {\sigma} {\sqrt {n}} q_ {2} <\mu <\bar {x} + \dfrac {\sigma} {\sqrt {n}}q_ {2}) =\gamma $
For the symmetry of the distribution we can take $q_{1} = - q_{2} $
Since it is $ 95 $ percent, for the complement there is 0.05 percent that must be divided by 2, that is, 0.025, then looking in a standard normal table for 0.975 we have that $ q_ {2} = 1.96.$
$  \bar {x} = 743, \sigma = 6, n = 16.$ You plug in and find the 95 percent confidence interval.
Comment: Just a question, could you explain why the Q function gives us that Normal distribution? I didn't quite get that part, thank you :)
Comment: Q is the pivotal quantity, by definition it must depend on the random sample of the population and the parameter of interest (µ), furthermore that pivotal quantity must have a distribution that does not depend on the parameter of interest (µ).  Therefore, the standard normal distribution is taken, which does not depend on the mean (\mu).
Comment: Tobar Castro Okay one last question, do you know of a way to get q1 and q2 with probability applets? I'm trying to use the Matt Bognar applets (you can find them on Google) but I'm not sure how to find these values from the Normal distribution applet?
Comment: No, normally I just use the tables


How can I unlock new components?

Question: I'm playing factory idle, and I wonder when I'll open the next components. I can hardly earn money with this components.
When/how do I unlock new components?
Answer:
On the achievements list, you can see that you'll unlock researches (which allow you to research new components) when your average income gets over $1.4.

How can I unlock new components?


Increasing Arrow Speed

Question: I'm playing Minecraft and I want to create a sort of "gun". Nothing special, just a bow with some slight twists.
Decreasing the draw speed is no problem, I already have that figured out.
The one thing I'm struggling with is finding a command to make the arrows travel faster.
Is there a command for that, and if there is, can anyone tell me how to use it?
Comment: The problem is that motion tags in Minecraft are not easy to manipulate. And even with hundreds of command blocks it wouldn't work, because to match the motion tag in the NBT data, you would have to check for every possible value of it, because you can't use > or < for it. So you would have to calculate the velocity yourself by getting the location in two ticks into scoreboards and subtracting them, that takes a few hundred commands per tick already, ... This quickly becomes a giant project and very lag-producing, so I don't think it's worth it. IThink punch ench.makes it fly faster, not sure.
Comment: Mikul Gamour gave an answer that would probably work for this question while trying to answer my question at https://gaming.stackexchange.com/questions/264925/shoot-bows-faster
Comment: On servers with minigames such as Quakecraft, players use guns to shoot at each other. The technique for doing this is called raycasting, or something similar. I myself haven't looked into this much,  but it could be the solution.
Answer: You can modify the Motion data tag which specifies in how many blocks per second an entity is moving an each axis.
Use this command for 1.14.4:
/data merge entity (arrow's UUID){Motion:[xmovement, ymovement, zmovement]}
Replace (arrow's UUID) with appropiate selector for your Arrow and xmovement, ymovement and zmovement with the desired movement values. This will change the Arrow's speed as well as its damage.
Answer: You can actually use /effect for arrows. I already tried it and it makes a change.
You can try /effect @e[type=arrow] 2 2 in a repeating command block to see the difference.
Comment: this doesnt worka s of 1.13

Increasing Arrow Speed


Can anyone explain how this wiring could work? (UK)

Question: This is how a bathroom lightswitch is currently wired... it works. But how?? (There's also a fan isolator switch supposedly connected to an extractor fan in the bathroom, but it apparently does nothing -- the fan never ran, even after it was replaced with a new unit.)
Thanks for any explanation!

Here's a photo, showing this wiring in action. And yes, it works fine. We can't understand how, or what the electrician who installed it was attempting to do.

Update
Due to interest, here's the extractor fan's wiring:

And the fan isolator switch's wiring:

And as a photo:

It remains a mystery how they're all connected.
Comment: It's odd for a switch to have "Live" and "Neutral" markings.   Usually the poles of the switch are symmetrical, they are "live" and "switched live" but only after you connect wires to them.   Until then there is no distinction.  (Your blue-with-black wires are probably switched live).   Perhaps this is not a simple switch.  Do you have the documentation?  The model number?  Is this two switches?
Comment: Ok .... when I blow up the photo I can see the markings clearly.
Comment: it begins to make sense if you think of the switch as two separate switches ... L side is one ... N side is the other
Comment: Does seem odd if using standard markings it does not trip breaker and the light works.  Imagine you are not seeing it right or someone made a mess.
Comment: @jay613 Did the photo not load for you?
Comment: The black tape on the blue wires and blue paint( on purpose or sloppy) on one of the browns might mean something.  Knowing where they come from and go to would help also.
Comment: @crip659 There's an electrician booked for next week. Hopefully they can start to decipher this confusing situation!
Comment: It's always best to edit additional pics into your original post. They can get lost in comments. You can make a comment to let someone know you've added the pics.
Comment: @FreeMan Added some context. Thanks
Comment: @jsotola Interesting. Thanks. But why not just us L-N / L-N? And why make the neutral cables live (if that is what happened). I still can't wrap my head around it :)
Comment: Are you sure this is a double-pole switch, and not a double switch (2 switches in 1 frame)?  If you don't know what a double-pole switch is, this will be really confusing.
Comment: @Harper-ReinstateMonica Yes, you can zoom in on the photo and see the words "Double Pole" clearly marked for yourself. This is what we *expected* to see when we opened it: https://images.socketsandswitches.com/images/content-images/double-pole-switch-wiring.jpg Thanks for any help!
Answer: This is marked as a "double pole" switch, and the terminals are marked "supply L&N" and "load L&N".
I think, with a little guessing, the switch is designed to isolate both the live and neutral sides of a device from power.  What kind of device, and why, is not clear to me.  If you know any local experienced electricians you could ask them how they've seen this kind of switch used in practice.
But the way it appears to be used in your house is to switch two different lighting circuits.   You have two switch loops there, operated together by one switch.   I can only guess why this would be done, rather than using a more typical pair of switches:

Maybe the two circuits are on different breakers so cannot share a live wire.
Maybe one switch loop controls the bathroom light, and the other the fan.  They are on two loops because that's how they were installed.  They were combined onto a double pole switch because that helps prevent users from using the bathroom without the fan, and from leaving the fan running after leaving.
maybe the installer only had one of these switches in his van.  That's often the answer to many mysteries, but this would be an odd thing to have bouncing around in your van.

You could disconnect each blue wire, one at a time, to see what the two loops each control and whether they are on the same breaker circuit.
Comment: Wild guess:  There are two switch loops to this switch, meant to be controlled by two switches but some previous user decided to put in a double pole switch for "convenience".   Nothing really wrong with that.    You could disconnect each blue wire in turn, to determine what is controlled by it.    Perhaps one is the fan, and the fan is broken.
Comment: I've seen the installation manual for this fan and I'm pretty sure that label that says "permanent" is just misleading.  It's for switched power and the manual clearly described that it's for switched power.  Their other models require both permanent and switched power.  I think for this model they just got the sticker wrong.
Comment: The fan was connected to a transformer. That's why the cables didn't match and why the fan didn't work: It was the wrong type.
Comment: Thanks for attempting to understand this. It's very confusing! It's just the bathroom light switch. As I say there's also an isolation switch (with six wires, indicating a permanent live -- but I've no idea where that goes or what it's connected to). There's an extractor fan, but it only have two wires: Blue and Brown. (No permanent live.) And the it doesn't work.
Comment: @jay613  That is about the only thing that makes sense.  Would not be surprise if that is the answer.  Should have seen the black tape on neutrals as a clue.
Comment: @jay613 A new fan was just installed, so its not that... but it does appear to be two loops
Comment: @jay613  Would add your wild guess to the answer.
Comment: I added some info to the answer.   If the fan is new, maybe it was installed incorrectly.  If it was connected to the two sides of a switch loop as if one side was "neutral" by somebody who did not know it was a switch loop, that would cause it to not work.   However this explanation would require the installer to not even attempt to turn it on after.  Seems unlikely.  If the new fan WAS working and then STOPPED working ... I think that would need some local diagnostics with a meter.
Comment: @jay613 The fan has never worked as long as I've been here. I simply followed the wiring of the previous installation (Live + Neutral), thinking the fan was broken. Now I wonder if the polarity is backwards
Comment: @jay613 You can see the fan wiring here: https://i.stack.imgur.com/fUK4R.jpg
Comment: And the isolation switch here: https://i.stack.imgur.com/k5i1c.jpg
Comment: Are there more wires behind the fan?   The fan's terminal is labelled "permanent live"?  Is that right?  So how is it meant to be switched on and off?  Is there voltage between the fan's two wires?  I'm not familiar with what the "isolation switch" is for or how it works or is wired.
Comment: Think the brown and blue wires on the fan are probably the same ones on the odd switch.  If they are, you a need power cable for the fan to work, if those wires are the only ones to the fan.
Comment: @jay613 Yes! You are right. I found a photo of the fan before I installed it (literally the same model that had been there previously -- although never worked for me). It does say "Permanent Live" on it. Although that in itself is baffling because there's nothing else to this fan: No pullcord. No timer. No humidstat. It's the cheapest model you can buy: MANROSE NVF100S
Comment: @crip659 I'm beginning to think they are, too. But there's no other cables available near the fan. Ugh
Comment: @jay613 Yep, I think you're correct about that


How to check current time is 12 noon in c#?

Question: i need to check current time is 12 noon using c# and timer tick event is used to execute the code
            int secs = System.DateTime.Now.Second;
            int hours = System.DateTime.Now.Hour;
            int minutes = System.DateTime.Now.Minute;
            string AmPm = DateTime.Now.ToString("tt");
            if (Convert.ToInt32("12") == hours && Convert.ToInt32("0") == minutes && Convert.ToInt32("0") == secs && AmPm.ToUpper().Trim() == "PM")
   {

}
else
{}

Comment: 1) Hour is in 24-hour format, so midnight=0, noon=12; 2) why `Convert.ToInt32("12")` instead of plain `12`?
Comment: Next problem: are you sure there is exactly one timer (not 0, not 2) tick inside that one second (12:00:00 - 12:00:01)?
Answer: You should just be able to do:
var is_noon = (
    DateTime.Now.Hour == 12 &&
    DateTime.Now.Minute == 0 &&
    DateTime.Now.Second == 0
);

No need to convert strings to ints, you're using literal values anyhow.
However as Hans Kesting pointed out, depending on the Timer you're using there is a chance for inaccuracy so you'd want some leniency, personally, I'd drop checking for seconds.


Pure geometry proof related to $(2+i)^2$

Question: Line segment $\overline{AB}$ is perpendicular to line segment $OAC$, with $O$ and $C$ at different sides of the meeting point at $A$.  The lengths of $\overline{AC} = \overline{AB}$ and  $\overline{OA} = 2\overline{AB}$.
Line segment $\overline{CD}$ is also perpendicular to line segment $OAC$; the two line segments meet at $C$ and point $D$ is on the same side of line $OC$ as point $B$.  The length of $\overline{CD} = 4\overline{AB}$.
(Sorry I have not provided a diagram; imagine on a 2-D grid a pair of right triangles one nested inside the other, with vertices at $(0,0),(3,0),(3,4)$ and $(0,0), (2,0), (2,1)$.)

Prove, using only classical plane geometry, that $\angle BOD = \angle AOB$.

It would be easy enough to show (using trigonometry) that the two angles are equal by calculating
$$\tan (2 \angle AOB) = \frac{\frac12 + \frac12}{1- \frac12 \frac12} = \frac43 = \tan (\angle COD)
$$
but that does not meet the requirement of "only classical plane geometry." One could of course prove the tangent of the sum of two angles formula using classical geometry, and then use that as a lemma in the proof of the desired statement, but I'm looking for a simpler and more direct proof.
Another cute proof using math outside of Euclid would be to consider point $O$ to be the origin of the complex plane, and take point $B = 2+i$.  Then
$$(2+i)^2 = 3+4i = C$$
and the result follows from de'Moivres theorem. Again, this is nice but it is not the pure geometry proof I am looking for.
Comment: Do you know the classical plane geometry result that if $D \in \overline{BC}$, then $\overline{AD}$ bisects the angle $CAB$ if and only if $\frac{BD}{AB} = \frac{CD}{AC}$?
Answer: Triangle $CDO$ is right with sides $3x,4x$ and $5x$, so inradius is $$ r={3x+4x-5x\over 2} = x$$
Since $B$ is at equal distance from $OC$ and $CD$ we see that $B$ is on angle bisector for $\angle OCD$ and since this distance is $x=r$ we see that $B$ is an incenter and thus a conclusion.
Comment: The use of the incenter is the clever idea I was looking for.
Comment: Interesting, I get a down vote! Why?
Comment: Now this is depresive. For a completly correct solution, you even get a downvote.


Will 2x10 joists span 10 feet between rims for a cabin?

Question: I intend to build on Weiss Lake in AL. If I use 8x8 posts, can I span 10 ft with 2x10 or should it be 2x12 for the floor joists?
Comment: Do you have any plans or diagrams you can share?
Answer: How far you can span with a given joist size depends on the load, the spacing between joists, the type / grade of wood, etc. - but not on the size of the supporting posts.  There are lots of tables you can find online such as http://www.southernpine.com/span-tables/
I'd see what's done locally but I'd bet you're way better off with piers made of concrete poured into sonotubes rather than sinking wood posts below grade.  But if you do, you do need a footer under the post.
Comment: I've seen cases where the concrete in sonotubes idea is used to come up above grade some and then wood posts are set on top. Metal post retainers can be set in the concrete when it is poured.
Comment: @MichaelKaras - thanks for the clarification that's what I meant - just coming above grade with the concrete, then setting the posts on the concrete.
Answer: I live where the ground is mush. We use two kinds of foundations: 1) piles (tree logs) driven into the ground to refusal (usually 100' - 120' down), or 2) piles driven until acceptable for friction.
1) Piles driven to refusal are designed to bear on bedrock.
2) Friction piles are designed to resist a load based on the ground "grabbing" onto the side of the pile.
Because it's so expensive to drive piles, they're designed to be spaced 20' - 25' apart. Then large grade beams (concrete beams) sit on the piles.
Wood piles will rot due to bugs. Bugs can only live with oxygen, which is in the top 10' (due to tidal action), so we only treat the top 15'. The remaining pile is a "green" tree trunk.
Caissons (concrete piers) are also used, but they are so heavy they often sink under their own weight.
I'd recommend treated wood piles, but you need to know the characteristics of your soil. I'd hire a geotechnical engineer to take soil samples and let you know the best foundation to use.


Better UX to avoid Multiple Dialog Box or Multiple Pop-ups

Question: So, recently I have encounter a UX challenge. There was a screen I was designing where I need to show some options in a dialog box. When we were handing over the screens to the developers they raised a question -
Q. How to handle a situation where they need to show errors-popups which are generated independent of the application? These independent error are shown in few scenarios where hardware got disconnected, machine jams, sensor error, dust blocking lense etc. etc.
Showing a popup on top of another modal window doesn't seem to me a correct UX and I kind of confirmed it after reading some material over internet.
Although, new Angular framework has an option to show multiple dialogbox/popups overlaying each other but it looks really ugly and I have found only one example in Angular.
My question - Is there a better way to resolve such situation where I don't have a control over system generated popup but at the same time I need to show dialogbox/popups for our app (ex - confirmation dialogbox)
Comment: Does your dialog box cover the whole screen? Are these errors urgent - will they affect the choices in your dialog?
Comment: Yes both cases are urgent.
Answer: To answer your question let us think like a USER. Do we like popups.... maybe but not more than one or two? Now if we are talking about more than say 3 popups that we have to close that's annoying/bugging and definitely not a great user experience.
So what to do. I would say there are two problems that we are solving here

Do we even need a popup as a way of showing a notification
Can we reduce the number of clicks to close all pop-ups

And assuming the intent is:

User should read all popups or be informed
Have a great user experience

To solve the first and second problems I would say we can

Have a permanent notification placeholder/icon where we can display a notification with the number written on some corner of the icon. to make the user know that there are notifications, we can have a popup when the user logs in on that screen saying you have 5 notifications waiting for your immediate attention, and then the popup goes in say 3-5 sec

Another way could be to have a one-liner notification, one below another with one closing icon on the top right, with an option of that disappearing in sometime
Comment: I don't think your first proposal would work with the case described here. If the hardware got disconnected and the user needs to fix it right now before proceeding with her work, you cannot display it somewhere in the background.
Comment: @Nash You exactly understood the point of my questions. I also disagree with giving a dedicated section for errors and warning when you have limited space on the screen and also when they occur infrequently but they are critical.
Comment: One liner notification are great when you have errors and warning that are somewhat familiar to the users. My fault, I didn't mention that the software that we are designing is a kiosk based interface for a niche industry.
Comment: some further question @ BLACK. So are you saying that the user will be getting these all popups in a kiosk. Why should he/she get popups in a kiosk. Dont you think it should have one popup telling all the errors or aggregation of errors. See we need to understand if the errors we are showing is an actionable item by the user or just an information?
Comment: @RiteshGupta As I have mentioned  in one of my comment that it is a very niche industry where those scenarios I have explained are happening in real life. Those actions require user intervention in order to proceed, as Nash has guessed already. Those kiosk are attached to a very critical operation, hence "most" of the errors are critical.
Answer: Show the popup on top of the other modal
From your question I got that the errors

Are urgent: The user needs to resolve them before continuing to work with the software.
Happen anytime: You cannot predict when they will happen.

I also hope that these errors happen rarely, otherwise the UX will suffer a lot. Therefore, I don't see any other option then to show it obtrusively with a modal or a toast in the face of the user.
Similar case: I had a similar case in the past where we would have to show an error message on a website if the backend got disconnected. In this case the user had to stop working otherwise changes could not be saved. We also opted for a red error toast.
Comment: No, I don't think it is good UX, but the best you can do in this situation. Can the user proceed without acting on the error? Yes -> Show a toast message that fades away. No -> Show a dialog over the dialog box.
Comment: Totally! you understood the problem but I would like to that my problem was when user is trying to select something from a dialog box within the app and hardware got disconnected that would render an error popup on top of the dialog box. Should I show popup on top of dialogbox? Is it a good UX ?


Unable to install software-properties-common on brand new Ubuntu 21.04 instance

Question: When I roll a brand new LXC CT with Ubuntu 21.04, I can't install software-properties-common which is required for apt-add-repository.
On a brand new instance I login as root and run apt update and apt upgrade, then apt install software-properties-common but get this output:
root@kubernetes:~# apt install software-properties-common
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 software-properties-common : Depends: packagekit but it is not installable
E: Unable to correct problems, you have held broken packages.

root@kubernetes:~# apt install packagekit
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 libglib2.0-bin : Depends: libglib2.0-0 (= 2.68.1-1~ubuntu21.04.1) but 2.68.0-1 is to be installed
E: Unable to correct problems, you have held broken packages.

Any idea why I can't install this on a brand new instance? Seems kind of messed up.
Comment: -1: The OP seems to be using the -proposed pocket. That error message is expected behavior when using -proposed. It's for testing, not for normal use. This un-reproducible question (and it's answer below) seem more likely to mislead folks into trying -proposed rather than help them avoid it.
Comment: On fresh 20.04 LTS running `sudo lxc-create -t download -n ubuntu -- --dist ubuntu --release hirsute --arch amd64` with `sudo lxc-start -n ubuntu -d; sudo lxc-attach -n ubuntu -- sh -c "apt-get update && apt-get install software-properties-common && add-apt-repository -h"` does not lead to any issues. Please edit your question to make it reproducible.
Comment: Does this answer your question? [How do I restore the default repositories?](https://askubuntu.com/questions/124017/how-do-i-restore-the-default-repositories)
Comment: Does this answer your question? [Unable to correct problems, you have held broken packages](https://askubuntu.com/questions/223237/unable-to-correct-problems-you-have-held-broken-packages)
Answer: Well for anyone else having this problem the solution was to edit /etc/apt/sources.list and the following into it as the only item (comment out everything else):
deb http://archive.ubuntu.com/ubuntu/ hirsute-proposed main

Then run apt update and apt upgrade again to fix libglib2.0-0 package, then restore sources.list back to before (but leave the proposed line) and it will work when trying to install software-properties-common again.
Why you have to do this for a stock installation is really confusing and a terrible user experience.
Comment: Very strange idea. You have to understand the current list of repositories. Using proposed is not recommended for end users. Check https://pastebin.com/x6YPa21B for understanding. Such Dockerfile works out the box.


Is jumping in snow piles the same as throwing snowballs?

Question: I got the recent update for Snoopy's Street Fair, and the goal that used to be "jump in 50 leaf piles" changed to "jump in 50 snow piles".
I figured it would work like the leaf piles - tap them, Snoopy runs over, and hops in. Simple enough. However, when I tap the snow piles, Snoopy runs over, steps on the pile, and throws a snowball at someone.
I have noticed that the progress meter hasn't moved for the 50 snow piles goal since the update - is this related to the fact that Snoopy is throwing snow instead of jumping in it? Or is my game just bugged somehow?
Comment: +1 for having a title that made me click through to see what the hell this was about.
Answer: No, they're different things.  I believe you'll have to change Snoopy's outfit if you want him to stop throwing snowballs.  Apparently he throws a snowball instead of jumping in the pile if he's wearing the Santa suit.


How to get custom shaders and texture packs on Minecraft Bedrock Edition?

Question: I want to be able to get texture packs and shaders on Minecract Bedrock Edition without having to buy them on the marketplace. Is there A way I can do that?
Answer: Any <code>.mcpack</code> will do.

For iOS, I recommend Addons For Minecraft

For Windows 10/Android, I recommend using MCPEDL.

Note that the two places I mentioned have a lot of the same content, with MCPEDL having a bit more.
For a version not mentioned (i.e. PS4) the marketplace is your only option.


Best way to add the same information to more items on a list

Question: Imagine we have a list of people. They are to do a task. I have the option of giving them
extra time. I could give Peter an extra 5 minutes for example.

What is a good way to give all people an extra 5 minutes?
"Extra time" could be a drop-down of sorts that controls the extra time of all the people in the list.
Any other ideas or known standards/conventions in this area?
Comment: How many 'extra time' amounts are there, or could it be any amount of time? (Meaning - can you only give people 5 extra minutes, or can you give John 5 minutes, Peter 15 minutes, Ida 12 minutes and Sarah 100 minutes?)
Comment: You can give all people a different amount of extra time. Lets say the options are 5 minutes, 10 minutes and 15 minutes. Now you want to give everyone 15 minutes of extra time and then change Ida's amount to 5 minutes.
Answer: What comes to mind here is a selection box for each list item, and then apply the change for all selected items (people).

download bmml source – Wireframes created with Balsamiq Mockups
You display the members of the list, together with their extra/remaining time. You provide selection boxes for each item (maybe with a SELECT ALL-box above), when selection is triggered the action panel above the list is enabled (which could provide more features than "Add extra time). The user choose which action to perform on the selection, this triggers a input field to appear (not on top of the list hiding the table, but adjacent to it) where the user can specify the update. The user can now perform directed action on multiple items in one flow.
Comment: Of the two answers, I agree with this one more because it allows more flexibility. I'm designing something exactly like this for a very similar purpose, and doing it exactly as AndroidHustle pointed out.
Answer: You could use preset control, which contains both extra time settings, and reset option, see the image:

This is one-click solution and doesn't require any chechboxes. Of course, it's less flexible.


How do I recursively create a Textures directory in every existing directory in Bash and then delete them?

Question: Lets say that I have the following structure:
./
├── Dir1
├── Dir2
│   ├── SubDir1
│   │   └── SubSubDir1
│   └── SubDir2
└── Dir3
    └── SubDir1

Use this to make the test structure:
mkdir -p Dir1 Dir2/SubDir1/SubSubDir1 Dir2/SubDir2 Dir3/SubDir1

I would like to create a Texture folder in every directory to include the current location so it would look like this (All new Texture directories are marked with *):
./
├── Dir1
│   └── Textures*
├── Dir2
│   ├── SubDir1
│   │   ├── SubSubDir1
│   │   │   └── Textures*
│   │   └── Textures*
│   ├── SubDir2
│   │   └── Textures*
│   └── Textures*
├── Dir3
│   ├── SubDir1
│   │   └── Textures*
│   └── Textures*
└── Textures*

Then I would also be able to delete these same folders after I work with them. You can assume that there are no other directories named Textures that need to be saved.

So I would like to create a Textures directory in the current directory and all of its subdirectories. And I would like to be able to delete every directory named Textures when I am done moving files around.
Answer: You can use a loop...
shopt -s globstar                   # turn on recursive globbing
for d in **/; do                    # for every directory
    echo mkdir -p "$d"Textures      # make a new directory inside named Textures
done

Remove echo after testing to actually create the directories.
You can turn off globstar with shopt -u globstar, but it is off by default, and will be off with you start a new shell.
Do your things...
Then to remove the directories, first find them
find -type d -name "Textures"

Then if the output looks OK, add -delete
find -type d -name "Textures" -delete

Comment: Just a minute faster than me... Good job ;-)
Comment: Could you shorten the loop to `mkdir -p **/Textures`? I would test it myself, but I'm not at home.
Comment: @wjandrea that just created a directory named "**" with a child directory of Textures.
Comment: @kingcobra1986 Ah, whoops. I forgot how globs work. :|
Comment: Thats alright I tried something earlier and it was trying to recursively create a Texture directories inside of themselves making it look like `./Textures/Textures/Textures/Textures/....` and it kept on going.


Python - How to move output text to the left / up?

Question: #!/usr/bin/python

from __future__ import print_function
import textwrap
import requests
from bs4 import BeautifulSoup

def bbb_spider(max_pages):
    bus_cat = raw_input('Enter a business category: ')
    pages = 1
    while pages <= max_pages:
        url = 'http://www.bbb.org/search/?type=category&input=' +     str(bus_cat) + '&page=' + str(pages)
        sauce_code = requests.get(url)
        plain_text = sauce_code.text
        soup = BeautifulSoup(plain_text, "html.parser")
        for link in soup.select("table.search-results-table tr h4 a"):
            href = link.get('href')
            bbb_profiles(href)
        pages += 1

def bbb_profiles(profile_urls):
    sauce_code = requests.get(profile_urls)
    plain_text = sauce_code.text
    soup = BeautifulSoup(plain_text, "html.parser")
    for business_name in soup.findAll("h1", {"class": "business-title"}):
        print(business_name.string)
    for business_phone in soup.findAll("span", {"class": "business-phone"}):
        print(business_phone.string)
    for business_address in soup.select("div.business-detail-text p span.nobr"):
        print(business_address.string, end=" ")

sort_pages = input('How many pages to sort through?: ')
bbb_spider(sort_pages)

So I have some output that looks like this:
Phone
                    Address      Name of Business

What I would like to have is:
 Name of Business
 Phone
 Address

Basically what's happening here is that throughout my foreach loop, for the next block of items arranged how i'd like (name, phone, address), the name is on the same line as the previous address's block. So what I'm trying to do is bring the name down and to the left, then address to the left, and then the phone will be fine as is.
Comment: check the raw strings. they may contain the spaces you're seeing, then you need to `trim` them.
Comment: @ivan_pozdeev Ahh. strip() function yes?
Comment: @n0de Yes. Before throwing it in, _first check if this is the issue._
Comment: @ivan_pozdeev  hmm. .get_text(strip=True) seemed to work. Thank you for your help guys :)
Answer: Use .get_text(strip=True) instead of .string:
print(business_name.get_text(strip=True))


How to call a method javaservlet in function javascript?

Question: function ShowMessage() {
    var url = '/primes/PrimesServlet';
    var result = CQ.HTTP.eval(url);
    var i = Number(document.getElementById("input").value);
    var str = document.getElementById("test");
    // if(result.checkPrimes(i)) // Want to call here
    str.innerHTML = i + " là số nguyên tố";
    // else str.innerHTML = i + " là hợp số";
    document.getElementById("output").style.display="block";
}

public class PrimesServlet extends HttpServlet {
    public boolean checkPrimes(long n) {
        boolean _return;
        MillerRabin obj = new MillerRabin();
        _return = obj.checkPrimes(n);
        return _return;
    }
 }

I want to call the method checkPrimes(long n) from my function ShowMessage(), but I can't.
Comment: You may want to read up on http://en.wikipedia.org/wiki/Ajax_(programming)
Comment: You'll need to call it via an AJAX request, since your java code is running on your server, and your JavaScript is executed client-side. Expose the Java method as a web service, make an [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from your JS, and make the return type of your Java method something which you can serialize, and parse on the front-end.
Answer:
I want to call method checkPrimes(long n) from function javascript "ShowMessage()" but I can't.

Yes you cannot.
Java plays on server side and javascript plays on client side.
Java needs compiled code and Javascript is just a scripting language interpreted by the browser.
What you need is just make a request to server.
That request may be

form submission
Ajax

Besides all with javascript you can check Prime like.
function isPrime1(n) {
    if (isNaN(n) || !isFinite(n) || n%1 || n<2) return false;
    var m=Math.sqrt(n);
    for (var i=2;i<=m;i++) if (n%i==0) return false;
    return true;
}

Just found here.
If you want to make a request with JavaScript, Ajax is your friend.
A great example :How to use Servlets and Ajax?
Comment: I don't need that.CheckPrime only is exampe. I want to use sevlet in javascript.
Comment: So Ajax is your friend.See here.http://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax
Answer: you can not call  methods using javascript because javascript runs in client side and javacodes lies in server side.
to call a method checkPrimes you can use ajax.
Answer: You could ether use AJAX-Calls or write a controller and call it via a request from the JavaScript.
The proble is (as the others said), that javascript runs in the browser of the client and your businesslogic runs on the webserver.
With AJAX you can trigger the server to execute code.
Answer: You can't call like that. You should do operation on doGet or doPost methods than write the result on PrintWriter.write method.
public class PrimesServlet extends HttpServlet {

 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                           throws ServletException, IOException{
 boolean _return;
 MillerRabin obj = new MillerRabin();
 _return = obj.checkPrimes(n);
 resp.getWriter().write(_return);

 }
}

Comment: If I use "resp.getWriter().write(_return);", browser will open new website. I want to keep my old website.
p.s: My English is bad.


How to unmerge same-key array elements?

Question: How can I unmerge same-key elements into separate elements?
array (size=1)
  'City' =>
    array
      'S' =>
        array
          'Red' =>
            array
              'SKU-1' => string 'Description 1'
          'Red' =>
            array
              'SKU-2' => string 'Description 2'

Desired output:
array (size=2)
  'City' =>
    array
      'S' =>
        array
          'Red' =>
            array
              'SKU-1' => string 'Description 1'
  'City' =>
    array
      'S' =>
        array
          'Red' =>
            array
              'SKU-2' => string 'Description 2'

So, instead of just having 1 element, the array has 2 elements even though the keys are the same.
Comment: Arrays in PHP always have unique keys. It's not possible for 2 elements to have the exact same key. Ever. Just think about it: how would you reference the element?? $array['Red']  would be... what? the first? or the 2nd element? Or am I misunderstanding your question ?
Comment: Thank you. The reason why I asked this is because when iterating the array, I need to get a unique combination iteration counting number (int) for each SKU (i.e 0000 or 0111 representing $city.$size.$color.$sku) even though the key-names are the same.
Answer: You cannot have duplicated keys, they will always overwrite.
You can do it like this.
array (size=2)
  'City' =>
    array=>
         0 => array
            'S' =>
                array
                'Red' =>
                 array
                   'SKU-1' => string 'Description 1'
         1 => array
           'S' =>
              array
               'Red' =>
                  array
                   'SKU-2' => string 'Description 2'

Comment: Thank you. But how I can convert that key-name/value pair multi-dimensional array elements into index-based elements?

How to unmerge same-key array elements?


How do I change the wallpaper in GNOME 3 via a script?

Question: The former way to change wallpaper in Gnome2 consists in use gconftool-2, but this tool has no effect in Gnome3.
gconftool-2 --type=string --set /desktop/gnome/background/picture_filename /home/user/background.jpg

Answer: Gnome3 uses dconf instead of gconf to background and wallpaper issues. The tool to modify dconf is gsettings and it can be done by the following way:
gsettings set org.gnome.desktop.background picture-uri "file:///home/user/background.jpg"


How can I attach the frame of a bed to legs using carriage bolts?

Question: I have a bed that I have been building - it has 4x4's for the legs, and I want to attach the frame of the bed (the part of the bed that runs from front legs to back legs, structural support) to the front and back legs.
I dont really want to just screw it to the 4x4's, but would prefer to have a carriage bolt that provide more modularity to the bed. Are there any kinds of deep nuts I could insert into the legs that I can screw a carriage bolt into? Basically so I can easily screw it in and unscrew it for dis-assembly. I have seen shelves and dressers we have bought that have these kinds of recessed nuts that you can screw a bolt into when assembling.
Just wondering if anything exists for home use?
Here is an image of what I am doing:

The brown pieces are what I want to attach to the posts/legs. I will then have supports along the 88 1/2 piece of wood that will span the width with 2x4's to provide a base for the box spring. Since it is a load bearing piece, I would like for it to be strong.
Comment: It was ludicrous to close this question. The question was "how to attach the side rails". How much more DIY could this be?
Comment: Since your very good question got closed I have been left with no choice but to respond to you here in the comments section. First off you will not be using "carriage bolts" to fasten the side rails. Carriage bolts have round top heads and a square part under the head. These are meant to be pounded into a hole and have a washer and nut be used on the other end of the bolt where it protrudes through the wood. Second big issue is the use of the 2x4 side rail. There just plain won't be enough support from bolting a narrow 2x4 so near the end of the (continued)
Comment: (continued from above) 4x4 posts. I recommend that you use at least a 2x10 side rail so that you can spread out the attachment points across the wider area to reduce the lever arm length of the posts. This will go a long way to keep the frame from getting rickety as pressure is applied laterally to the tops of the head and foot posts. The conventional wisdom would be to accommodate the wide side rails by having them come up along side the mattress stack. The support for the stackup is attached to the inside bottom edge of the 2x10 side rail. Last thing to consider (continued)
Comment: (continued from above) is that the that the wood inserts should be larger than the ones that you found at Amazon. I would suggest that you use something at least an inch long (~25mm) and a bolt size of 5/16" or greater. Suitable inserts could be found here: http://www.catalogds.com/db/service?domain=ezlok&command=locate&category=hex_flush_zinc_unc or here: http://www.fastenright.com/insert-nuts-for-wood-type-d
Comment: @tester101 There's actually a special bolt called a bed bolt (appropriately enough) designed specially for this exact application. They have been used since...people stated sleeping in beds. When it comes to furniture making things don't change often or quickly.
Answer: I found what I needed! I happened to stumble upon it after posting this.
What I need are "Wood Insert Interface Screws". This will allow me to screw these into the wood, while using a carriage bolt to screw into this. Hope this helps someone.
Comment: I hope that you find longer ones closer to 2.5 inches (63.5mm) rather than using those short ones (15mm). And that you use more than one bolt per end of the side rails.


Which maps are different in the console version of the game?

Question: I'm primarily a console gamer, so I don't tend to follow the PC versions of games I plan to play on consoles.  I know that there is a much lower limit to the number of players that can be in the same game on the console versions of BF3 versus the PC version.
However, I've also been informed that some of the maps have been scaled down in size (or perhaps changed completely?) from the PC version on account of the lower number of players possible.
Which maps were changed, and how are they different in the PC version?  Do Console players just have "invisible walls" on a much larger map?  Are they completely different maps of different size with the same name?  Or did console players get a completely different set of maps to replace the 64x64 maps on PC?
Answer: All the maps have been slightly compacted but nothing has changed. You will recognise areas on both PC and consoles as the same. DICE Executive Producer Patrick Bach says:

On the construction of more "compact" maps:
  "Maps will be smaller than their PC counterparts, though it's not that
  we have cut them in half, but rather compacted them slightly to keep
  the action up."

I think they have mainly cut away a lot of the empty land between places. There are also no "invisible walls" and the map borders works in the same way as Bad Company 2 - giving you 10 seconds to get back into the battle zone.


Why my Tensorflow FCN failed

Question: I implemented "Fully Convolutional Networks for Semantic Segmentation" on tensorflow. However my implementation can't learn anything meaningful and always resulted all 0 prediction or Nan value crash.
I tried all trick I have learned, weed out all difference between Caffe and Tensorflow. I am pretty much out of idea where it could be wrong now.
link to code
Answer: @24hours
I find it hard to dive into your code.
One thing that might help you is the following:
I use this code snippet in many projects to monitor all my trainable parameters and their gradients. An example is this
The code extracts all trainable variables, loops over them and requests a histogram
tvars = tf.trainable_variables()
grads = tf.gradients(cost, tvars)
gradients = zip(grads, tvars)
# The following block plots for every trainable variable
#  - Histogram of the entries of the Tensor
#  - Histogram of the gradient over the Tensor
#  - Histogram of the grradient-norm over the Tensor
for gradient, variable in gradients:
  if isinstance(gradient, ops.IndexedSlices):
    grad_values = gradient.values
  else:
    grad_values = gradient

  h1 = tf.histogram_summary(variable.name, variable)
  h2 = tf.histogram_summary(variable.name + "/gradients", grad_values)
  h3 = tf.histogram_summary(variable.name + "/gradient_norm",

Comment: Hi, my codes are indeed a mess. I refactored them abit and hope it help readability.
Answer: One more thing :
In your transpose convolution function call you are missing the argument of padding. I wonder how it would work without padding.
In any case you will have to set padding =VALID or padding = SAME while calling tf.nn.conv2d_transpose.
Hope this helps!
Comment: the default value for `padding` in `conv2d_transpose` is `same`. Since Tensorflow do not have `CROP` layer as in Caffe, I opt for same to maintain dimension. At the end, fcn worked on Tensorflow with the contraint on fixed sized image.

Why my Tensorflow FCN failed


Query Execution Request Exception

Question: I'm trying to update a record in a document table with the help of foreign key of the file table, but it gives the error of QueryExecutionRequestException. What should I do to update the record in document through foreign key?
@ DAO code
public void forwardTo(File ob, Person selectedP, long pid)
    {
        log.debug("Document forwarding ");
        try {
            System.out.println("in dao");
            System.out.println(ob.getFileRefNo());
            String queryString = "update Document d set d.onDeskOfPerson=:onDeskOfPerson, d.person=:person where d.file=:file";
            System.out.println("after update query");
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter("onDeskOfPerson", selectedP.getLogin());
            queryObject.setParameter("person", selectedP);
            queryObject.setParameter("file", ob);
            Document doc = (Document)queryObject.list().get(0);
            getSession().merge(doc);
            System.out.println("after merge");
            int result=queryObject.executeUpdate();
            System.out.println("Rows affected="+result);
            log.debug("save successful");

        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }
}

@error log
Dec 11, 2014 1:29:48 PM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: org.hibernate.hql.QueryExecutionRequestException: Not supported for DML operations [update com.model.filling.Document d set d.onDeskOfPerson=:onDeskOfPerson, d.person=:person where d.file=:file]
javax.el.ELException: org.hibernate.hql.QueryExecutionRequestException: Not supported for DML operations [update com.model.filling.Document d set d.onDeskOfPerson=:onDeskOfPerson, d.person=:person where d.file=:file]
    at org.apache.el.parser.AstValue.invoke(AstValue.java:291)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.hql.QueryExecutionRequestException: Not supported for DML operations [update com.model.filling.Document d set d.onDeskOfPerson=:onDeskOfPerson, d.person=:person where d.file=:file]
    at org.hibernate.hql.ast.QueryTranslatorImpl.errorIfDML(QueryTranslatorImpl.java:297)
    at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:346)
    at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1149)
    at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
    at com.dao.filling.DocumentDAO.forwardTo(DocumentDAO.java:259)
    at com.service.filling.FillingDataManager.forawrdDoc(FillingDataManager.java:158)
    at com.controller.Controller.forwardDoc(Controller.java:207)
    at com.managedBean.Filling.FileMB.forward(FileMB.java:298)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
    ... 27 more

Dec 11, 2014 1:29:48 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
SEVERE: org.hibernate.hql.QueryExecutionRequestException: Not supported for DML operations [update com.model.filling.Document d set d.onDeskOfPerson=:onDeskOfPerson, d.person=:person where d.file=:file]
    at org.hibernate.hql.ast.QueryTranslatorImpl.errorIfDML(QueryTranslatorImpl.java:297)
    at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:346)
    at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1149)
    at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
    at com.dao.filling.DocumentDAO.forwardTo(DocumentDAO.java:259)
    at com.service.filling.FillingDataManager.forawrdDoc(FillingDataManager.java:158)
    at com.controller.Controller.forwardDoc(Controller.java:207)
    at com.managedBean.Filling.FileMB.forward(FileMB.java:298)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:274)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

Answer: You call Document doc = (Document)queryObject.list().get(0);
what is not allowed for update queries.
Comment: i remove this line Document doc = (Document)queryObject.list().get(0);
Comment: and made this changes getSession().merge(queryObject);                but still it not working
Comment: means it's not updating  the record
Comment: @here is the error                      org.hibernate.MappingException: Unknown entity: org.hibernate.impl.QueryImpl
javax.el.ELException: org.hibernate.MappingException: Unknown entity: org.hibernate.impl.QueryImpl
Comment: @java445 You can not merge with a query object.
Comment: i found the solutions and records are updating successfully

Query Execution Request Exception


How to get the year metadata of AVAsset URL in Swift?

Question: I tried the below method on an AVAsset URL and all I am getting is nil. Is there anything wrong in my code?
func getYear(musicName: String) -> Date? {
        let url = FileManager.customFolderURL.appendingPathComponent(musicName)
        let playerItem = AVPlayerItem(url: url)
        let metadataList = playerItem.asset.metadata
        var date: Date?

        for item in metadataList {
            switch item.commonKey {
            case .commonKeyCreationDate?:
                date = item.dateValue
            default: break
            }
        }

        return date
    }

Comment: Is `metadataList` empty? Maybe use the async method with `loadMetadata(for:completionHandler:)`?
Answer: func getYear(musicName: String) -> Date? {
        let url = FileManager.customFolderURL.appendingPathComponent(musicName)
        var date: Date?
        let asset = AVAsset(url: url)
        let metaData = asset.metadata
        if let artist = metaData.first(where: {$0.commonKey == .commonKeyCreationDate}), let value = artist.dateValue {
            print(value)
            date = value
        }
        return date
    }

This Code will work if your file contains value for property .commonKeyCreationData. I didn't have appropriate file for testing. But it was returning value for property .commonKeyArtist and if we would just replace artist.dateValue to artist.stringValue.
Comment: Looks like they updated this API for iOS 16.0. The new API is a huge PITA to get data out of it.
Comment: probably Adrian, you're right


Best practice for Web Push Notifications Prompt

Question: I want to implement push notifications on my website.
The obvious option is to simply show the prompt once the user lands on the page.
But is this a good practice? I read the EDGE is auto-blocking the prompt if enough people have chosen to block the prompt.
What's the take on this?
Comment: The best practice for this is to _not_ do it.
Answer: I assume you are talking about the built-in browser prompt that asks if the user wants to allow/block push notifications, as opposed to a custom solution of your own.
First of all, these are extremely annoying for the user and very obtrusive. Having one of these pop-up without me taking any action is an immediate "block".
The second problem is that there are only 2 options: Allow and Block. "Block" is a negative word. It's like saying that the site is spam, and it is no surprise that browsers are starting to treat it as spam.
So putting this at the very start of the site interaction is a bad idea. How can a user be expected to click "allow" when they haven't even been on your site long enough to know what they are agreeing to? You will almost always get a "block" in those instances.
I recommend that if you want to support push notifications on your site then you should make this a user options somewhere. Sure, you can "advertise" this feature on your landing page if you want to promote it, but let the user read some information about what it does and what type of notifications you will be sending. Then if the user wants them let them click a button and then you can prompt for confirmation. This way, they will almost always click on "allow" because they have already made the decision to do so.
I also suggest you keep in mind that (in my opinion) this feature won't be around for much longer. It is too easy to abuse for spammers and attackers and I expect this tactic of blocking sites with a bad reputation is likely just the first step in it's demise.

In summary. Don't automatically show the prompt. Provide the user with some information about what the notifications will do. Give the user the option to agree to them before the prompt it shown.
Answer: The best time to ask a user to allow push notifications is the moment when they understand that a notification would help them accomplish their intentions. That's usually not when the page loads. Users need to understand the value of the notification, which might otherwise be a potential nuisance. Examples:

The user ordered their first package from your site, and you offer to send a notification when it, and future packages, have been shipped
The user has bid on an auction item for the first time and might want to allow notifications to prevent from being outbid at the last minute

It's crucial to explain what the user will receive in return for allowing notifications before you show the permission dialog.
This article has some good suggestions and patterns for making opt-in less intrusive and more likely to be adopted.


How do I delete all empty directories in a directory from the command line?

Question: Say I have a directory named foo/. This folder includes subdirectories. How can I delete all the empty directories in one command?
Answer: Try this command:
find . -empty -type d -delete

The find command is used to search for files/directories matching a particular search criteria from the specified path, in this case the current directory (hence the .).
The -empty option holds true for any file and directory that is empty.
The -type d option holds true for the file type specified; in this case d stands for the file type directory.
The -delete option is the action to perform, and holds true for all files found in the search.
Comment: The way you would remove directories, regardless of whether or not they are empty, type the following command: `rm -rf `.  This will remove the directory, along with all its contents including files and subdirectories.  The `-r` option means delete recursively, while the `-f` command means don't prompt before deleting.  If you want to be prompted before deleting a directory/file, however, replace the `-f` option with the `-i` option.
Comment: It is possible to do this by using a pipe to feed the `stdout` of one command (e.g. `find`) into the `stdin` of the other (e.g. `rm`), however, be very careful since it may wipe out or delete files/directories that you don't want to delete!  For further information on how to do this, see the `man` pages for each of these commands.  To be safe, always test such things in a temporary directory before trying out on the real thing.
Comment: @joeybaruch On MacOS almost every directory you "visited" with Finder.app contains a `.DS_Store` hidden file, that usually stores your sorting/viewing preferences for that directory. Other apps may add other hidden files (e.g. Adobe Bridge may add a `.BridgeLabelsAndRatings` file), so perhaps those directories aren't really empty. Anyways, you can remove the `.DS_Store` file with `find . -name '.DS_Store' -delete` and then try again to remove the empty directories with the suggested command.
Comment: With the `-depth` option `find` can even match and delete directories that only become empty because all of their (empty) subdirectories were deleted. Try it out with `mkdir -p a/b/c/d && find a -depth -type d -empty -print -delete`.
Comment: I think this is the easiest way to do it so I am going to go ahead and mark this as answered.
Comment: Hey Bill, I tried to post another similiar question and it wouldn't let me because it said it was a dupe, so I was hoping you might be able to answer me here. Say I wanted to do the same thing as above but remove all directories whether they are empty or not.
Comment: What if there were some files in said directory I wanted to keep. So, I wanted to delete all directories in /foo/bar/ but keep any files that might be in there.
Comment: doesn't work in mac, only deletes the leaf empty directories, not the ones that contained only empty directories.
Answer: You can take advantage of the rmdir command's refusal to delete non-empty directories, and the find -depth option to traverse the directory tree bottom-up:
find . -depth -exec rmdir {} \;

(and ignore the errors), or append 2>/dev/null to really ignore them.
The -depth option to find starts finding at the bottom of the directory tree.
rm -rf will delete all the files in the directory (and its subdirectories, and ....) AND all the directories and everything.
Answer: rmdir *

Will delete all empty directories. It'll throw up an error for every non-empty directory and file, to stop those errors from cluttering your terminal, use
rmdir * 2> /dev/null

Comment: This is not suitable for scripting since it will exit with a non-zero status code but it works.
Comment: @the_drow how does it make unsuitable? By the way you can also use `rmdir * 2>/dev/null || true`.  (The *find(1)* way is better for scripting but for other reason: because it expresses better what you want to do.)
Comment: I often do this at `$HOME`. With an evil grin.
Comment: Because it will report failure if some of the directories are not empty.
Comment: is this faster than the find method? Has anyone compared the two?
Answer: find . -type d -empty -delete -maxdepth 1

For if you only want to delete the direct subdirectories of foo/.
Answer: Python approach
$ tree
.
├── empty_dir1
├── empty_dir2
├── subdir1
│   ├── file1.abc
│   └── file2.abc
└── subdir2
    ├── file1.abc
    └── file2.abc

4 directories, 4 files
$ python -c 'import os;empty=[r for r,s,f in os.walk(".") if not f and not s and r != "." ];map(lambda x: os.rmdir(x),empty)'
$ tree
.
├── subdir1
│   ├── file1.abc
│   └── file2.abc
└── subdir2
    ├── file1.abc
    └── file2.abc

This works like so:

we use os.walk() function to walk recursively the directory tree. On each iteration r is set to current folder that we're accessing,s contains list of directories within r, and f will contain list of files in that folder. Of course if f and s are empty, we know that r is empty.
first list-comprehension allows us to create empty , the list of all directories that are empty, based on the evaluation stated above.
second function, map() is used to perform os.rmdir() on each item in empty list. List comprehension could be used as well as alternative.

As a script this would be as so:
#!/usr/bin/env python
import os
empty=[]
for r,s,f in os.walk("."):
    if not f and not s and r != ".":
        empty.append(r)

for i in empty:
    os.rmdir(i)

Comment: too complicated for simply questions :(
Comment: @nurulhudamustaqim  Depends on point of view. For a lot of Linux users who are used to Python this is actually very modest :) And besides its variety.  Modern system administration is not limited to bash or `/bin/sh` only and Python is actually more elegant language than those two


How to sort the values based upon aggregate data in Elastic Search

Question: PUT my-data-stream/_bulk
{"create":{}}
{"timestamp":"2022-05-06T18:25:42","search_term":"hello", "counter": 10}
{"create":{}}
{"timestamp":"2022-05-06T18:25:42","search_term":"bye", "counter": 5}
{"create":{}}
{"timestamp":"2022-05-06T17:25:42","search_term":"hello", "counter": 9}
{"create":{}}
{"timestamp":"2022-05-06T17:25:42","search_term":"bye", "counter": 7}
{"create":{}}
{"timestamp":"2022-05-06T16:25:42","search_term":"hello", "counter": 5}
{"create":{}}
{"timestamp":"2022-05-06T16:25:42","search_term":"bye", "counter": 2}

Given the data set above. I want to sort (DESC) the search terms by sum of the counters which are greater than a specific timestamp.
For example: For timestamp greater than 2022-05-06T16:35:42 (which are top 4 records). Result should be
 Hello, 19 (10 + 9)
 Bye, 12 (5 + 7)

Answer: Tldr;
You can order your data using order in you aggregation.
As per the documentation here

In this case, the buckets are ordered by the actual term values, such as lexicographic order for keywords or numerically for numbers. This sorting is safe in both ascending and descending directions, and produces accurate results.

Solution
GET /74006495/_search
{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "timestamp": {
              "gte": "2022-05-06T16:35:42"
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "search_terms": {
      "terms": {
        "field": "search_term.keyword",
        "size": 10,
        "order": { "count": "desc" } // <- Here is the order by count agg
      },
      "aggs": {
        "count": {
          "sum": {
            "field": "counter"
          }
        }
      }
    }
  }
}

Answer: I used a filter by date and then aggs the results.
{
  "size": 0,
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "timestamp": {
              "gte": "2022-05-06T16:35:42"
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "search_by_day": {
      "date_histogram": {
        "field": "timestamp",
        "calendar_interval": "day"
      },
      "aggs": {
        "search_term": {
          "terms": {
            "field": "search_term.keyword",
            "size": 10
          },
          "aggs": {
            "total_counter": {
              "sum": {
                "field": "counter"
              }
            },
            "counter_bucket_sort": {
              "bucket_sort": {
                "sort": [
                  {
                    "total_counter": {
                      "order": "desc"
                    }
                  }
                ],
                "size": 3
              }
            }
          }
        }
      }
    }
  }
}

Results:
  "aggregations": {
    "search_by_day": {
      "buckets": [
        {
          "key_as_string": "2022-05-06T00:00:00.000Z",
          "key": 1651795200000,
          "doc_count": 4,
          "search_term": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
              {
                "key": "hello",
                "doc_count": 2,
                "total_counter": {
                  "value": 19
                }
              },
              {
                "key": "bye",
                "doc_count": 2,
                "total_counter": {
                  "value": 12
                }
              }
            ]
          }
        }
      ]
    }
  }

Comment: I want to sort by sum of counters.


Android Studio encoding item of listview

Question: I have a problem with ListView item using android studio.
this.setTitle("é ç è ");

ArrayList<String> Array = new ArrayList<String>();
Array.add("é ç   è");
Array.add("à de");
Array.add("chére");
List = (ListView)findViewById(R.id.LV_List );
LV_List.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_activated_1,Array));

It can't be encoded for items of ListView !!!!
looking to screeshot
http://hpics.li/48fe3c0
Info:
- Using the same code, I'had not this problem in Eclipse
- My Android Studio Version: http://img15.hostingpics.net/pics/818235Capture.png
Answer: Try to adding this in build.gradle
tasks.withType(Compile) {
options.encoding = "UTF-8"
}


What are the differences between the different anti-aliasing / multisampling settings?

Question: I'm tweaking the settings in DiRT 2 and I'm presented with these choices (in order) for multisampling:

2x MSAA
4x MSAA
8x MSAA
8x CSAA
16x CSAA
8x QCSAA

Using the nVidia Control panel I'm presented with

2x
4x
8x CSAA
8x
16x CSAA
16xQ CSAA
32x CSAA

I assume those without text on the nVidia panel are probably MSAA.
The naive guess would be bigger numbers are visually better. But then MSAA, CSAA and QCSAA come in to play (presumably different methods of performing AA) and confuse matters by not being in the right order.
For example is 8x / 8x MSAA "better" than 8x CSAA somehow? Otherwise why would it be further down the list on the nVidia panel? And is 8x QCSAA "better" than 16xCSAA as per the order in DiRT2?
In terms of image quality, performance and any other quirks,
what are the differences between the various types of AA?
I'm not asking about the algorithmic/implimentation differences; that's probably off-topic anyway.
Answer: This is a great question because other than "is AA on or off?" I hadn't considered the performance implications of all the various anti-aliasing modes.
There's a good basic description of the three "main" AA modes at So Many AA Techniques, So Little Time, but pretty much all AA these days is MSAA or some tweaky optimized version of it:

Super-Sampled Anti-Aliasing (SSAA). The oldest trick in the book - I list it as universal because you can use it pretty much anywhere: forward or deferred rendering, it also anti-aliases alpha cutouts, and it gives you better texture sampling at high anisotropy too. Basically, you render the image at a higher resolution and down-sample with a filter when done. Sharp edges become anti-aliased as they are down-sized. Of course, there's a reason why people don't use SSAA: it costs a fortune. Whatever your fill rate bill, it's 4x for even minimal SSAA.
Multi-Sampled Anti-Aliasing (MSAA). This is what you typically have in hardware on a modern graphics card. The graphics card renders to a surface that is larger than the final image, but in shading each "cluster" of samples (that will end up in a single pixel on the final screen) the pixel shader is run only once. We save a ton of fill rate, but we still burn memory bandwidth. This technique does not anti-alias any effects coming out of the shader, because the shader runs at 1x, so alpha cutouts are jagged. This is the most common way to run a forward-rendering game. MSAA does not work for a deferred renderer because lighting decisions are made after the MSAA is "resolved" (down-sized) to its final image size.
Coverage Sample Anti-Aliasing (CSAA). A further optimization on MSAA from NVidia [ed: ATI has an equivalent]. Besides running the shader at 1x and the framebuffer at 4x, the GPU's rasterizer is run at 16x. So while the depth buffer produces better anti-aliasing, the intermediate shades of blending produced are even better.

This Anandtech article has a good comparison of AA modes in relatively recent video cards that show the performance cost of each mode for ATI and NVIDIA (this is at 1920x1200):
<code>                       ---MSAA---   --AMSAA---    ---SSAA---
                 none  2x  4x  8x   2x  4x  8x    2x  4x  8x
                 ----  ----------   ----------    ----------
ATI 5870           53  45  43  34   44  41  37    38  28  16
NVIDIA GTX 280     35  30  27  22   29  28  25
</code>
So basically, you can expect a performance loss of..

no AA → 2x AA
~15% slower
no AA → 4x AA
~25% slower

There is indeed a visible quality difference between zero, 2x, 4x and 8x antialiasing. And the tweaked MSAA variants, aka "adaptive" or "coverage sample" offer better quality at more or less the same performance level. Additional samples per pixel = higher quality anti-aliasing.

Comparing the different modes on each card, where "mode" is number of samples used to generate each pixel.
<code>Mode   NVIDIA   AMD
--------------------
2+0    2x       2x
2+2    N/A      2xEQ
4+0    4x       4x
4+4    8x       4xEQ
4+12   16x      N/A
8+0    8xQ      8x
8+8    16xQ     8xEQ
8+24   32x      N/A
</code>
In my opinion, beyond 8x AA, you'd have to have the eyes of an eagle on crack to see the difference. There is definitely some advantage to having "cheap" 2x and 4x AA modes that can reasonably approximate 8x without the performance hit, though. That's the sweet spot for performance and a visual quality increase you'd notice.
Comment: Great answer, but I disagree with the last paragraph. e.g. Both 8x CSAA and 16x CSAA are noticeably more jaggy than 8x MSAA in nVidia's control panel (3D settings preview area.) IMO, it takes 16xQ CSAA to reasonably approximate 8x MSAA.
Answer: If you prune through this article you will probably be able to gather most of the information you seek, but I'll try and summarize the relevant bits.
First, you should understand that MSAA is a type of Supersampling anti-aliasing (SSAA). SSAA, also known as FSAA, removes "jags" from an image by rendering the image at a higher resolution:

Full-scene anti-aliasing by supersampling usually means that each full
  frame is rendered at double (2x) or quadruple (4x) the display
  resolution, and then down-sampled to match the display resolution. So
  a 2x FSAA would render 4 supersampled pixels for each single pixel of
  each frame. While rendering at larger resolutions will produce better
  results, more processor power is needed which can degrade performance
  and frame rate.

MSAA is a more efficient form of FSAA, but the multiplier still has the same meaning, roughly. This means (as you probably know), that a higher multiplier gives better results, but demands more processing power.
CSAA is an even more efficient form of SSAA, which uses some advanced 3D magic (just read the paper if you really must know) to deliver better results:

In summary, CSAA produces antialiased images that rival the quality of
  8x or 16x MSAA, while introducing only a minimal performance hit over
  standard (typically 4x) MSAA.

In essence, if you equate your multipliers, MSAA will produce better results than CSAA (though it is implied that the results will not be significantly better), but will demand significantly more on the processing power department.
QCSAA is simply CSAA with twice as many sample points used to perform the anti-aliasing, so obviously QCSAA is better than CSAA.
Wikipedia's Supersampling article actually provides a great image showing why more samples mean better accuracy:

All this being said, the order in which DiRT2 lists its anti-aliasing options looks perplexing, to say the least. Since I doubt you can personally tell the difference once the multiplier hits 8x and upwards, I'd stick to CSAA/QCSAA for the performance gain.
Finally, here is a nice comparison shot of the various techniques on a specific, simple, image (from the article in the first link):
Comment: @JeffMercado: CSAA is something only NVidia's cards do. AMD have an equivalent called EQAA. [See here](http://www.tomshardware.com/reviews/anti-aliasing-nvidia-geforce-amd-radeon,2868-4.html).
Comment: Excellent answer!  If you are a developer, @Aubergine, be sure to check out the [game development stack exchange](http://gamedev.stackexchange.com) as well :)
Comment: Thanks, @BlueRaja-DannyPflughoeft! I appreciate the appreciation ;)
Comment: Does using CSAA require hardware support?  Or should any card that supports MSAA in general be able to use the setting?
Comment: This is a great answer!
Comment: @TrewTzu: Much obliged.
Comment: Very detailed~~
Answer: NVIDIA has created another algorithm, FXAA (Fast Approximate Anti-Aliasing). Unlike currently used MSAA, CSAA and their variations, it works on a pixel level, never touching geometry. It finds jagged edges and smoothes them. It is faster than the rest. Like FSAA, it has no problems with alpha channels, shaders etc. However, the results are more blurry.
I see two uses for FXAA: first, if you want AA, but the penalty of MSAA/CSAA is too high for your hardware; second, if a game heavily relies on alpha and shaders and your hardware is not godly enough for FSAA.
Aliased, 4xMSAA, FXAA:
Answer: In addition to the excellent answers already here, I'd like to mention the relatively new  SMAA, or "Subpixel Morphological Antialiasing", which is, like FXAA, a post-process antialiasing method. In many cases it outperforms other AA methods in terms of the image quality/cost ratio.

WHAT IS SMAA?
In the words of the developers Jorge Jimenez, Jose I. Echevarria, and Diego Gutierrez from the Universidad de Zaragoza, and Tiago Sousa from Crytek,

SMAA is a very efficient GPU-based MLAA implementation, capable of
  handling subpixel features seamlessly, and featuring an advanced
  pattern detection & handling mechanism. (source)

Or, more extensively (with my emphases):

We present a new image-based, post-processing antialiasing technique,
  which offers practical solutions to the common, open problems of
  existing filter-based real-time antialiasing algorithms. Some of the
  new features include local contrast analysis for more reliable edge
  detection, and a simple and effective way to handle sharp geometric
  features and diagonal lines. This, along with our accelerated and
  accurate pattern classification allows for a better reconstruction of
  silhouettes. Our method shows for the first time how to combine
  morphological antialiasing (MLAA) with additional multi/supersampling
  strategies (MSAA, SSAA) for accurate subpixel features, and how to
  couple it with temporal reprojection; always preserving the sharpness
  of the image. All these solutions combine synergies making for a very
  robust technique, yielding results of better overall quality than
  previous approaches while more closely converging to MSAA/SSAA
  references but maintaining extremely fast execution times.
  Additionally, we propose different presets to better fit the available
  resources or particular needs of each scenario. (source)

HOW DOES IT WORK?
SMAA is based on MLAA and FXAA:

MLAA (Morphological AA) and FXAA (Fast Aproximate AA) are post AA modes
  that use blur filters. First, they detect contrasts ("edges") in the
  frame and then blur it along the gradient.
This results in highly reduced visible "jaggies" that also covers
  alpha-textures, but it also blurs everything, including textures. It is
  also the cheapest form of AA and often used in console version of
  games.

The detection of edges of SMAA, however, is comparable to that of SSAA:

The alisasing "detection" is upgraded and is closer to the detection
  used in MSAA then the detection used in MLAA and FXAA. The result is
  that SMAA still remains very cheap, still smoothes alpha-tectures and
  still greatly reduces the visible "jaggies", but doesnt blur the image
  as much. (source)

This post by SomeoneSimple on the Anandtech forums explains briefly what SMAA does, and how it can work in conjunction with MSAA:

SMAA Injector on its default 'SMAA_PRESET_HIGH' is just a bit more
  GPU-intensive then plain FXAA, so performance loss is pretty
  negligible in most cases.
SMAA doesn't compare to MSAA though. MSAA actually adds
  (subpixel-)detail to smooth polygon edges, SMAA only tries to hide
  jaggies (but does a good job doing so). Most noticeably, you'll still
  have pixel-crawling/flickering with SMAA.
However, SMAA does support being used in combination with MSAA. That's
  the 'subpixel' part of its name, unlike any other post-process AA
  filter (i know of), it can correctly detect gradients, thus it can be
  used in conjunction with other forms of non-PP AA, like MSAA and SSAA.
That said, I'm currently using 1.2x OGSSAA (NV custom resolution
  override) with SMAA injected, in games that don't play nice with MSAA.
  SMAA takes care of anti-aliasing, and SSAA greatly lessens the amount
  of pixel-crawling. It looks gorgeous, far better than only 1.2x OGSSAA
  or SMAA on its own.

I will not go into further detail here, as the other answers have already provided background information on the mechanism of different AA techniques.
You can read more about this specific method in their paper (PDF); or by leafing through their slideshow presentation (direct link); or look into the code on GitHub.

COMPARISON WITH SEVERAL OTHER AA TECHNIQUES
A few screenshots that compare SMAA with other antialiasing techniques:

(source)

(source)

(source)
A video comparison using Crysis 2/CryEngine 3, that implemented it for the first time (Youtube):

Here is a direct link to the original video, unspoiled by compression.
And the following is a comparison with some MLAA, SRAA and FXAA methods (sourced from the paper linked above):

IMPLEMENTATION
A version of SMAA, made injectable by Andrej Dudenhefner, can be downloaded here, and injected into many DirectX 9/10/11 (x86) applications.
This article describes how to do so in Fallout: New Vegas, but this method is very similar in most Bethesda games. It also provides some more information comparing and illustrating the different AA techniques.
Comment: For some reason, I cannot reach [iryoku.com](https://iryoku.com), where most of the sources presented here can be found ([it doesn't seem to be down](https://www.isitdownrightnow.com/iryoku.com.html), however). In any case, the paper is also accessible [here](https://projet.liris.cnrs.fr/imagine/pub/proceedings/EUROGRAPHICS2012/issue2/pdf/v31i2pp355-364.pdf). Sadly, I haven't been able to find an uncompressed version of the video.
Answer: msaa is the slowest and is generally better looking than csaa equivalent.
8x msaa is the best quality, but the most expensive. csaa is nvidia's alternative solution, which works more efficiently. but 8x msaa really looks good.


How to prioritize content and functionality

Question: During a brainstorm activity it's sometimes easy to come up with a lot of ideas and solutions to various user problems. How do you prioritize the ideas to focus your resources and avoid scope creep?
Comment: You might want to expand on your question some more. Editing it to be more concrete and maybe adding things you have tried already or experience with will make it a lot more *answerable*.
Comment: Agree with kontur on this one. We'll need much more to go on here, an explanation of the specific problem that you have around the brainstorming would possibly help. In particular it's not really a UX question currently, but a project-management one, or something similar.
Answer: Call out the constraints
There is often a lot of emphasis on allowing free thinking during blue sky design sessions. While that can be really helpful in coming up with excellent ideas which might be really innovative, at times you can be sadled with a whole bunch of ideas which sound great but cannot be implemented due to the time frame, technology restrictions or budget limitations. I would recommmend doing the following before you start a design brainstorming session.

Inform the participants of the problem statement at hand
Highlight the objective of what you plant to achieve ( You might not know what you hope to achieve but you would have a generic idea like build an e-commerce website or a build an iphone app or so on)
Highlight the restrictions in technology and timeline and budget (if applicable)
Start the brain storming session
Collect the ideas and start to prioritize them on the following order:
<code>- The minimum product requirements to have a minimum viable product
- The must have features in a full fledged product
- The important features which can perhaps wait till phase 2 or even version 1.1
- The nice to have features
</code>
The features should be analyzed on basis of what you plan to achieve and what the end impact is going to be.

I recommend looking at this article Best Brainstorming Techniques for additional inputs. To quote the article :

Establish the Ground Rules Taking an "other worlds" approach, or similar methods that go outside the familiar, can bring on some crazy
  suggestions—and that's a good thing. That old saw that no idea is a
  bad idea? A truly groundbreaking idea could be left unspoken because
  of self-editing, says Buffalo State's Puccio: "When we're asked to
  come up with 'good' ideas, we get so focused on evaluating the quality
  of the idea that we sometimes dismiss ideas prematurely—ideas that
  might actually turn out to be workable or valuable or breakthrough."
  But some evidence reveals that the most productive brainstorming
  approach is to have individuals develop ideas independently, then to
  have the group dissect and think critically about the ideas, according
  to Jonah Lehrer in his book Imagine: How Creativity Works (Houghton
  Mifflin Harcourt, 2012). Another option is to get people out of their
  comfort zones: Rich's Rife suggests asking an executive to toss out a
  really crazy idea before the meeting. "This gives permission for
  everyone else to think that way," Rife says.
Plan for Implementation Once participants have brainstormed all these blue-sky ideas, 9 times out of 10, they never get off the
  whiteboard. Experts agree that charting an implementation plan before
  the meeting even starts can ensure the best ideas move forward from
  blue sky to production line. "Your success rate will be much higher if
  you know what the next steps are in advance," notes Phillips of
  Phillips + Co.

Other articles which give excellent inputs on how to conduct and follow up on brain storming sessions are :
Brainstorming 2.0: Making Ideas That Really Happen
#34 – HOW TO RUN A BRAINSTORMING MEETING


ValueError: Attempted relative import in non-package in pyspark/not able to find the kmodes module(pyspark)

Question: ValueError: Attempted relative import in non-package in pyspark. Above error is coming when i am trying to use kmode in pyspark .So i parrelelize the kmode package by using
sc.addFile("home/pyspark-distributedkmodesmaster/pyspark_kmodes/pyspark_kmodes.py") .If i am not using the sc context add file  code  it is throwing error -"not able to find the kmodes module".
I am using below code/link or kmodes pyspark package -
"https://github.com/ThinkBigAnalytics/pyspark-distributed-kmodes/blob/master/pyspark_kmodes"
Answer: It's a package and you're only deploying one of the py files contained in it. Since there is a relative import in pyspark_kmodes.py:

from .Kmodes import KModes

The . in  .Kmodes means it should look for file KModes.py in the same folder (within the package folder)
Comment: hey,thanks,I  merged all files in one py and then bring it spark context.It is working now


How to stop a process named "Code" that has high CPU usage?

Question: I have one process named "Code" that has high CPU usage. I don't know what this process is and how I can stop it.

Can you help me fix this?
Comment: isn't this VSCode ?
Comment: Yes, it really was VSCode. It is strange that he loaded the CPU so much, and it was closed. Thank you!
Answer: It's most likely VS Code. You can kill the process from a terminal using the following command:
killall code

Or, since you know the ID of the process (it's shown in the screenshot you provided):
kill -9 9661

You can also right-click on the process in System Monitor and select Kill.
Comment: It really was VSCode, I reinstall it and the problem is gone, thank you for your help!
Answer: ps - aux | grep code
kill {id}
Answer: by the name of the process you can use the console command
pkill <process name>

the documentation is written here
Answer: Recommended distribution of VS Code for Ubuntu is through deb.
So if that snap is not depended by any other application, then remove it
snap remove code
and install VS Code
Comment: Yes, it really was VS Code. Reinstalling helped. Thank you!


System Activity Report (sar) - how can I preserve color, but disable extra header lines? (and use less)

Question: If you run sar without parameters, the output is in color, but with extra headers inserted after each page. If you run sar | cat the extra headers are removed, but so is the coloring.
If you would like to pipe into less, running sar | less have the same effect as using cat  - extra headers are removed, but so are colors. If you would like to preserve color with less, you can use unbuffer (which is installed as a part of expect) and less -R, but then the extra headers appear again.
I believe this is better shown in pictures below (the extra headers are marked in image 2).
The result of sar | less:

The result of unbuffer sar | less -R:

So is it at all possible to preserve colors with the sar command using less, and at the same time not have the extra header lines for each page (as marked in image 2)?
I reckon it might be possible to do this with some elaborate awk/grep/sed piping (and maybe chained commands), but I would prefer a more straight solution with the commands themselves, if this is at all possible. This is also due to the fact that I would like to pipe the result to less using a single command.
I'm using Ubuntu Server 22.04.
Comment: Does `S_COLORS=always sar | less` do the trick? I don't have a working `sar` to test with.
Answer: I have never used sar, but man sar mentions that sar has an environment variable whose value controls this behavior:

S_COLORS
By default statistics are displayed in color when the output is connected to a terminal.  Use this
variable to change the settings. Possible values for this variable are never, always or auto  (the
latter is equivalent to the default settings).

There are various tools that change their output depending on whether they are being piped to something or just printing toa terminal and many have an always option to ensure color is used regardless. For instance, see the --color options of grep and ls. It looks like sar is using an environment variable for the same thing, so just try this:
S_COLORS=always sar | less -R

The -R option for less allows the preservation of colors and hyperlinks in the text being piped.
Comment: Thanks. I must admit that I had overlooked that entry in the man page. I guess I was focused on command options, and not an environment variable.


PHPUnit stops execution after setExpectedException()

Question: I have the following pseudo code
public function testSomething() {
    // assert something
    // assert something else

    $this->setExpectedException(...);
    // trigger my exception here

    // do one last thing
}

The issue I see, code after the exception being triggered is never made. Is this correct?
This is just a general wondering here - if this is normal I will refactor my test to perform the try/catch directly and fail() the test if nothing is caught.
Answer: The code after the exception should not be made.  Think of the setExpectedException as making the test into a try -- catch So the code after the exception is thrown will not be executed.
If you need to do/check things after the exception, you should catch it.  Though one warning with your catch, be specific about what exception is being thrown.  PHPUnit throws exceptions for failed tests and you could accidentally catch this exception which may result in your test falsely passing.
Update:
If the code that you are executing is cleaning up, consider also moving it into the tearDown method of the test.
Comment: Better to put the code that must be executed after the test into `tearDown` which PHPUnit will call whether or not an exception is thrown.
Comment: Good point.  I was mostly considering other assertions that you would potentially want to make.