how to pass a channel with flexible length to a process in nextflow

Question: I defined four boolean variables (bwa_flg, lariat_flg, gatk_flg, and deepvariant_flg) in nextflow.config.
Depending on the setting, I may have two bams (bam from bwa or/and lariat), two vcfs (vcf from gatk or/and deepvariant)
I need the bam-vcf pair to do the following analysis like phasing etc. (So I might have four pairs at most)
I tried these:
if (params.lariat_flg) {
   lariat(ch_reads).set{ch_lariatbam}
   if (params.gatk_flg) {
      gatk(ch_lariatbam)
      phase etc...
   }
   if (params.deepvariant_flg) {
      deepvariant(ch_lariatbam)
      phase etc...
   }
}

if (params.bwa_flg) { // also have to include gatk and deepvariant again from here because already used previously...
   bwa(ch_reads).set{ch_bwabam}
   if (params.gatk_flg) {
      gatk(ch_bwabam)
      phase etc...
   }
   if (params.deepvariant_flg) {
      deepvariant(ch_bwabam)
      phase etc...
   }
}

I have to write the following phase etc. four times, plus include these processes from modules four times.
how to do it smartly...
Comment: Why don't you assign the generated bam to a "bam channel" like `bam_ch` (instead of different channels for different bams) and use it for the other two conditionals (the vcf generation ones)?
Comment: @Poshi I thought of that. So I wonder how to pass a bam channel (which might have one or two bam, depending on the flag) to the next process.
Answer: If the bams are coming from the same output channel you could use the buffer operator in the workflow declaration.
workflow example {
  main:
  bwa(input)

  if ( params.bwa_flg ){
    bwa
      .out
      .bwa_out
      .buffer( size: 2 )
      .set { bam_ch }
  } else {
     bwa
      .out
      .bam_ch1
      .flatten()
      .set { bam_ch }
  }
  deepvariant( bam_ch )
  ...

And if you need a flexible input for the process you can define a function.
process deepvariant {
  input:
  path(bams)

  script:
  def process_bams = bams{ "deepvariant --input $it" }.join('\n')
  """
  ${process_bams}
  """
}

But if they are coming from different processes, but they are from the same sample id, then you can merge samples based on the same if statement principles in the workflow declaration so long as you output tuples with sample id.
workflow example {
  main:
  bwa(input)
  lariat(input)

  if ( params.bwa_flg && params.lariat_flg ){
    bwa
      .out.baw_out
      .combine( lariat.out.lariat_out, by: 0 )
      .set { bam_ch }
  } else if ( params.bwa_flg ){
     bwa
      .out
      .bam_out
      .set { bam_ch }
  } else if ( params.lariat_flg ){
    lariat
      .out
      .lariat_out
      .set { bam_ch }
  }
  deepvariant( bam_ch )
  ...

combine will only work in this example if the outputs of bwa and lariat are something like tuple val(sample_id), path(bam), emit: lariat_out
Edit:
Here is the flexible deepvariant input, assuming multiple inputs are denoted each by -i:
process deepvariant {
  input:
  tuple val(sample_id), path(bams)

  script:
  def flexi_bams = bams{ "-i $it" }.join{' '}
  """
  deepvariant ${flexi_bams} -o ${sample_id}.output
  """

Comment: thanks for the answer. I think bam_ch would better receive from different processes, like the second way you provide, and then use combine. but in this way the length of bam_ch will be 2 or 3, depending on the flag. how does deepvariant define the input channel with flexible length?
Comment: Does deepvariant use all the bams together? If so it could be as simple as modifying the definition within the process. See the edit to the answer above.
Comment: no, deepvariant doesnt take two bams at one time. I want both lariat bam and bwa bam to run deepvariant separately. i.e., the deepvariant process take two channels and they run simutaneously (should I use transpose()?
Comment: You can either use the example in the original answer where I defined a flexible command using `def`, or potentially use the `concat` [operator](https://nextflow.io/docs/latest/operator.html#concat).
Comment: @dthorbur can you please help with https://stackoverflow.com/questions/77304249/nextflow-module-compilation-error-in-the-process-script and https://stackoverflow.com/questions/77304098/nextflow-data-not-being-published-to-output-dir-after-process-is-complete


Image rescaling algorithm

Question: Suppose I have to use bilinear interpolation to rescale image. I more or less understand how enlargement works in case of integer scale factor.
But what to do with non-integer scale and especially when you need to downsample an image?
Answer: Explanation
With a non-linear scale, you apply different weights for each pixel (or whatever unit you are using). You can use Euclidean distance towards the closest pixels in both directions to determine the weights.
Example
Normalization
For example, in the image below, the red image is the downsampled image (3x3) and the black image is the original image (4x4). The dots represent the sample points (center of the pixels).
You can align the two images by treating each pixel coordinate as a set of two values (x and y) between 0 and 1 (inclusive). Pixels should not be treated as square, so you should treat each pixel as a point rather than a square (when aligning the two images).

In the above image, the four corners would all carry the weight of the original image's four corners, for example. The points in the middle would carry different weights depending on the difference between the four neighboring points.
With numbers:
This is a hypothetical area to sample in larger images (not related to the image above). The distances are between original pixels are normalized from 0 to 1 to simplify the math.
The black dots represent the sample points (pixels) of the original image. The larger red dots represent the sample points of the downsampled image. The red dot in the top left is closer to the black dot in the top left than the other three surrounding dots, so that pixel will have a heavier weight for determining the color of the downsampled pixel.

Horizontal distance from:

Right 2 original (green) pixels = 0.1 pixels
Left 2 original (green) pixels = 0.9 pixels

Vertical distance from:

Top 2 original (green) pixels = 0.1 pixels
Bottom 2 original (green) pixels = 0.9 pixels

Weight for final pixel:
$$weight(0, 0) = (1.0 - 0.1)(1.0 - 0.1) = 0.81$$
$$weight(0, 1) = (1.0 - 0.1)(1.0 - 0.9) = 0.09$$
$$weight(1, 0) = (1.0 - 0.9)(1.0 - 0.1) = 0.09$$
$$weight(1, 1) = (1.0 - 0.9)(1.0 - 0.9) = 0.01$$
Subtract from 1 both the horizontal and vertical distance (because closer pixels should carry more weight). The scale factor in this example is 0.75 in each direction.
Scaling Up vs. Scaling Down
Scaling up in the same  process as scaling down. By normalizing both the original image and the new image to between (0, 0) and (1, 1), you can do either with the same process. As an exercise, in the first figure, if the red points were from the original image and the black points were from the enlarged image, you should be able to see that the process is the same.
Comment: @justanothercoder While an ok answer. It does nothing for dispelling the myth that pixels are squares. You are dealing with point samples (that are not squares). And that resampling is in fact consisting of 2 distinct phases rolled into one, making the datafield continious and then sampling said continious function.

Image rescaling algorithm


Series of hyperbolic triangles with sum of angles converging to $\pi$

Question: The sum of angles of a hyperbolic triangle is $\alpha+\beta+\gamma=\pi-A(\Delta)$ with the area $A(\Delta)$ of the triangle. Thus, if we construct a series of hyperbolic triangles where the area converges to $0$, the angle sum should approach $\pi$. I tried doing this with the following explicit construction of a triangle $z_1,z_2,z_3$ in the half-plane model:
Given two circles of radius $1$ and center $\pm 1/2$, the intersection is in $$z_1:=\frac 32 \mathrm i.$$ Then, we take the other points to be $$z_2 := -\frac 12 + \mathrm e^{\mathrm i\varphi},\quad z_3 := \frac 12 + \mathrm e^{\mathrm i(\pi-\varphi)},$$
i.e. arbitrary points on the two circles. Both points approach $z_1$ for $\varphi\to \pi/3$.

Because $z_2,z_3\to z_1$ for $\varphi\to \pi/3$, the area of the triangle should approach $0$ and the sum of angles should approach $\pi$.
This is what I thought; however, a direct calculation of the sum of angles leads to a different result.
The angle in $z_1$ is the angle between the radii of the two circles from the beginning which intersect in $z_1$, i.e. between $z_1+1/2$ and $z_1-1/2$, so
$$\alpha = \arccos\left(\frac{\Big\langle\begin{pmatrix}1/2 \\ \sqrt 3/2\end{pmatrix}, \begin{pmatrix}-1/2\\ \sqrt 3/2\end{pmatrix}\Big\rangle}{1\cdot 1}\right) = \arccos \frac 12 = \frac \pi3.$$
The angle in $z_2$ is the angle between the radii of the initial circle and the dashed circle in $z_2$, i.e. between $z_2+1/2$ and $z_2$, so
$$\beta = \arccos\left(\frac{\Big\langle \begin{pmatrix}\operatorname{Re}z_2+1/2 \\ \operatorname{Im}z_2\end{pmatrix}, \begin{pmatrix}\operatorname{Re}z_2 \\ \operatorname{Im}z_2\end{pmatrix}\Big\rangle}{1\cdot |z_2|}\right)=\arccos\left(\frac{|z_2|^2+(\cos\varphi-1/2)/2}{|z_2|}\right),$$ where $|z_2|^2=(\cos\varphi-1/2)^2+\sin^2\varphi=5/4-\cos\varphi$, so $$\beta=\arccos\left(\frac{1-(\cos\varphi)/2}{\sqrt{5/4-\cos\varphi}}\right)\to\arccos\frac{\sqrt{3}}{2}=\frac \pi6$$ for $\varphi\to\pi/3$.
The third angle $\gamma$ is equal to $\beta$ due to symmetry.
So, we get $\alpha+\beta+\gamma\to 2\pi/3$ for $\varphi\to\pi/3$, but $A(\Delta)\to 0$.
Where is the mistake; how does this make sense? Thanks!
Answer: The interior angle at $z_1$ is actually $2\pi/3$. You computed the exterior angle, not the interior one.
Comment: Let $v_1$ and $v_2$ be the vectors from the midpoints of both circles to the intersection point, then $\cos^{-1}\frac{\langle v_1,v_2\rangle}{\sqrt{\langle v_1,v_1\rangle\langle v_2,v_2\rangle}}$ is always the angle inside one circle but outside the other. This notion of inside or outside unfortunately changes under isometries of H^2. To represent oriented lines of constant curvature, and compute oriented angles and other things in a manner invariant under isometries, the hyperboloid model is more suited.
Comment: Oh, you're right, thanks!
Is there a general method to calculate the actual angle? The method I used (angle between radii) seems to work sometimes (with $\beta,\gamma$), but gives $\pi$ minus the angle at other times (with $\alpha$), which basically corresponds to a missing minus sign in the $\arccos$. Is there an easy way to "detect" when this additional minus sign is necessary?


Can't Find Main Panel Breaker

Question: A two-pole 30 amp breaker keeps tripping on a brand new dryer and is tripping more often as time goes on (was originally tripping every few weeks or so, now doing it every day), so I figured it would be worth a shot to just replace the breaker and see if that fixes it or the source is something deeper.
Unfortunately, the main panel doesn't seem to have a main 100-150 amp breaker or is a split bus, as I flipped all the breakers on the top half of the panel but the dryer was still live. It looks to be hooked up straight to the meter, so I don't think there's any sort of main switch upstream.
Comment: Are you asking if the dryer circuit could be tapped directly out of the meterbox?  If none of the breakers on the top half of the panel control the dryer why not flip the breakers on the bottom half? If you are saying the breakers for the dryer keep tripping then you obviously know where they are? I'm trying to understand but it seems like the bearings on the dryer motor may be shot if your breakers are tripping at an increasingly faster pace. This could mean the motor is struggling and therefore causing an overload situation
Comment: Can you post a photo of the label on the inside of the panel door?
Comment: @ChrisTaylor Sorry I wasn't clearer, it's the latter case. I know where the dryer circuit breaker is, I'm just trying to replace it. I know the fact that it's tripping usually means the appliance is pulling too much load, but the dryer is brand new, and this also happened occasionally with the previous dryer that we replaced this one with. I figured with how cheap breakers are, it's worth a shot before calling a professional to diagnose.
Comment: @ThreePhaseEel added a photo to the main post!
Comment: Can you post photos of the two boxes below the meter?
Answer: That's not a split bus (Rule of Six). For one thing, it is too new - Rule of Six panels were outlawed before CH panels started getting branded Eaton.    For another, all the breakers are accounted for, there would need to be a  "Main Lighting" breaker.
By the way, CH is a great panel.
I wonder if the main panel used to be here, and is now on the other side of the wall, and this one was installed as a subpanel to handle the dozen or so circuits that were impracticable to route to the new location.
Comment: Thanks so much for the clarification! The other side of the wall, in this case, is right in our living room and I don't see anything noticeable on the wall at that point.
Answer: The Panel Designation CH24CCR is a Main Lug Only Panel. This means it doesn't have a Main Breaker and looking at your meter location and nipple running into your panel, there is no enclosed main breaker or fused disconnect. They do make a main breaker kit but you would have to find a cover with a hole for it. Looking at your photos I would say your best bet would to replace the panel with the correct configuration.
As far as your dryer circuit goes. When you reset and run your dryer does the circuit breaker get hotter than normal? It should not really feel hot to the touch. If it is heating up you may have a damaged breaker or lugs and it's slowly heating up enough to trip the bi-metal device inside. It will continue to weaken until and trip more frequently as time goes on. That sounds something like you are experiencing. It might also be a loose connection at the breaker lugs, but if it is tripping the breaker, I would bet it is already damaged. So you might see about replacing the breaker make sure you clean the conductors and follow the torque table on the label when tightening up the conductors.
The only real way to verify that it is the breaker or an overload is if you have an ammeter. you can check both conductors coming out of the breaker and see is the amperage is too high for the circuit. If its pulling less than 21A the dryer is operating ok. Leave the ammeter on the circuit and check back from time to time to see if the amperage is changing before the breaker trips. The more expensive ammeters will have a peak amperage button so you can check and see if the current spikes while in use.
Remember you will have to be checking amperage's while the power is on. So exercise extreme caution while testing. If you feel you are not experienced enough then seek qualified help.
good luck and stay safe.
Comment: From the photo of the label, it seems to say you can either feed the main lugs directly from another breaker or install a breaker as a "backfed" main in this box (which didn't happen here).  I wonder if the large dark box to the lower right of the panel is a fused disconnect of some kind that feeds the main lugs of the switch panel.
Comment: @Upnorth - You are correct. You can install a "backfed" main. I didn't mention it because it has to be approved as main breaker which have some blurred line requirements. This can be found in NEC Article 408.37(D) and further requirements in 110.3 in particular (A)(1) Informational note number 2. In short it must be approved for that purpose and installed with a tamperproof  fastener. I know GE has some approved kits for this but I am not sure if this type of Cutler Hammer does.
Answer: I rarely turn a main off to replace a breaker but I do make sure the breaker is in the off position prior to pulling the breaker or installing. I would check outside the home for a main at the service drop it is unusual for the main to be prior to the meter but I have seen it.

Can't Find Main Panel Breaker


Format a partition stil working after 2 weeks

Question: I'm trying to format a partition large 185 gb using gparted on an usb pendrive, but it's still working after 2 weeks... it's normal or my program chashes. The last voice of the list says "creation new file system ntfs" and still doing. Help i don't know what to do...
Comment: 185 GB on a pendrive? Did you maybe buy one of those bogus 1TB or 2TB Chinese drives that don't work?
Answer: Do you mean that your machine has been trying to format a 185GB for 2 weeks none stop? If this is the case GParted has crashed as any formating program should do this job in a few hours at most. Swtcich of your system & try again. If you get the same problem, you should investigate:
1- Run some tests on your hard disk (Here are 2 free toolkits that will help you:
A- Hiren's boot CD, http://www.hirensbootcd.org/download/
B- Ultimate boot CD, http://www.majorgeeks.com/files/details/ultimate_boot_cd_(ubcd).html)
2- Read GParted help on memory requirements, etc.
3- Seek help from GParted's manufacturers, if needed.
Good luck.
Comment: Hiren's boot cd is a collection of pirated software. Please keep to the Stack Exchange policy and avoid linking this kind of stuff.


What do ripples on the water indicate?

Question: Occasionally while fishing in Stardew Valley, I'll see ripples on the surface of the water (little animated circles). Does this indicate the presence of a rare type of fish? Are my fishing chances higher in that location? What does it indicate (if anything)?
The screenshot below illustrates what I'm talking about:
Comment: Can you include a screenshot? Pretty sure I know what you mean, but want to be sure.,
Comment: [Is this the ripples you speak of? not the best screenshot, but I think it's what you're referring to](http://images.akamai.steamusercontent.com/ugc/306614004554213225/FD8E074DE0D6767DD08452C91A2D99E37AB44A1D/).
Comment: Yep, that's what I'm talking about. I've added a screenshot above.
Comment: Excellent. It's gotta have something to do with fish, but I've never had  fishing rod with me when I've seen them. I'll need to start carrying one all the time.
Answer: The bubbles you occasionally see indicate a higher activity of fish in that tile. If you successfully land your lure within or close to that bubbling tile when fishing, you will get a visual confirmation with the water splashing. The area for the benefit slightly extends outside of the tile, and the different visual effects can be seen below:

Note: The Standard Fishing Visual Effect is also displayed when the bobber hits the water.
When fishing from the ripples, you will notice that fish and other debris bite much quicker. With lures and bait, you will find fish biting within the first 5 seconds of fishing.
Answer: Yah, its for quicker bites. If you see them, use them (if possible). This is especially useful for River fishing as you can always reach them. What I do is if I am going on Fishing Expeditions and need quantity of fish over quality, I go River Fishing. Now if I want quality....
...I go to Lakes and Ocean and fish in the darker water areas. There are prime locations that are good for quality gold-star fish and if you scroll down on this page... http://stardewvalleywiki.com/Fish ...then you will find many locations you probably didn't even think about fishing at. There is also a table at the bottom that defines what time of the day you should start fishing and end fishing for a specific type of fish at certain locations during specific seasons. I recommend taking a look at those tables.

What do ripples on the water indicate?


To be a scalar matrix or not to be?

Question: What follows is a pretty (but not so easy) exercise. Is fun off-topic?

Let $A, B \in M_2(\mathbb{C})$. Show that for every $m, n \in \mathbb{N}$ $$((AB)^m-(BA)^m)((AB)^n-(BA)^n)$$ is a scalar matrix (that is, of the form $\lambda I_2$).
Comment: Asking questions to quiz other users is generally frowned upon.  I'm not sure about "off-topic", though.
Answer: I don't know what trick you had in mind, but it is sufficient to note that $((AB)^m - (BA)^m)$ and $((AB)^n-(BA)^n)$ are commuting matrices, each with trace $0$.
Comment: Yes, it is the essential idea;
Comment: Yay! As long as we're having fun, then... suppose that the set of matrices $\{A_1,\dots,A_n\}$ forms a group under multiplication.  Show that
$$
\operatorname{trace}\left( \sum_{j=1}^n A_j \right) = 0 \implies \sum_{j=1}^n A_j = 0
$$
Comment: Hint. $(\sum_jA_j)A_i=?$ and $trace((\sum_jA_j)^k)= ?$.
Comment: @loupblanc there you go
Comment: Actually, I'm not sure I follow your method.  You're doing something interesting here.
Comment: What I had in mind: note $(\sum_j A_j)^2 = n\sum_j A_j$
Comment: Yes, the mean $1/n\sum_jA_j$ is a projection. It is faster.
Comment: In fact, $1/\sqrt n \sum_j A_j$ is the projection

To be a scalar matrix or not to be?


app.request.attributes.get('_route') is empty when I override 404 error page

Question: I'm trying to customize 404 error page so I did:
1) Create app/Resources/TwigBundle/views/Exception/error404.html.twig
2) I changed is_granted() for {% if app.user and is_granted('...') %} in "layout.html.twig", used by "error404.html.twig"
3) php app/console cache:clear --env=prod --no-debug
4) Access in prod enviroment to http:/localhost/app.php and cause 404 error, getting a blank page instead of my custom error page.
I checked my "prod.log" file and I saw a NotFoundHttpException and this Twig error:
request.ERROR: Exception thrown when handling an exception
(Twig_Error_Runtime: An exception has been thrown during the rendering
of a template ("Unable to generate a URL for the named route "" as
such route does not exist.") in "::layout.html.twig" at line 33.) [] []
It appears that path(app.request.attributes.get('_route')) returns an empty value.
-> How can I get current route and make error page work?<-
Thanks
Comment: When you're on a 404 page that (usually) means there's no matching route.
Comment: Do you really need variable header elements if your route is invalid? I'd recommend (more or less) static content for the error page.
Comment: What do you want to do with your current route inside the error page?
Comment: Not in my error page but in my layout, where is my header. It´s to determine the elements of my header. Its elements depends on the current route.
Comment: You may find the [WebfactoryExceptionsBundle](https://github.com/webfactory/exceptions-bundle) helpful for testing your pages here.
Answer: As Maerlyn says in his comment, it's likely that, if you're on a 404 page, there is no matching route.
However, you can retrieve useful information from the request object which may help you here:
<code>{{ app.request.uri }}
</code>
will return you the full URL of the page the user was trying to access.  And
<code>{{ app.request.pathInfo }}
</code>
will return the path (starting with a slash).
You can find out more about the methods available on the request object by looking at <code>/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Request.php</code>.


Rain dropping on balcony making noise -- how to fix?

Question: My awning is a little bit too short, causing rain to drop on my balcony railing.

I don't really care about aesthetics, just want an easy solution.
I can think of some options:

Bend the flashing from below with a stick so that it extends a little bit farther.
Tape some soft materials along the railing to cushion the rain drop. My concern here would be that the material will grow moldy over time.
Answer: Some black open-cell foam taped down with black duck-tape should do the trick.
Open-cell foam should allow the water to drain reasonably well after the rain stops, and by finding black foam & tape, it'll blend in reasonably well. Of course, if you buy some extra foam, you can replace anything that's starting to look a little grotty over time.
Odds are really good that if you start bending the flashing, you'll only give the wind easier access to lift it, allowing water underneath and/or ripping it off if the wind is strong enough. Additionally, that seems to be an apartment building type of balcony, and if so, you probably shouldn't be making permanent alterations to a place you don't own. If, on the other hand, you own the place, consider lengthening the overhang to direct water past the railing or, even better, put up a gutter to collect the water and guide it down the building properly. If water just runs off a 2nd or 3rd story balcony (based on comparison to the house shown in the background), it'll quickly dig a trench in the ground below.
Comment: Honestly, a gutter would be better than a longer overhang.
Comment: Really smart idea -- thank you! TIL about open cell vs closed cell foam.

I do own the place, but I'll try the foam trick first before extending the overhang.
Comment: Pipe insulation or pool noodle?


How can I check that my disk repartitioning has been completed safely?

Question: Background: My desktop computer came with an SSD drive with a working Windows 10 install.  I installed Linux (Mint 18.3 w/ Cinnamon) into a new extended partition with the default boot, swap, main partitions.  For some reason Windows failed to boot, but as I never use Windows I haven't worried about it.
Recently I've been running short of disk space, so the obvious solution was to eliminate the Windows partition to reclaim space.  I opened up the Disks tool and deleted the Windows partition, expecting to be able to the resize the extended partition.  Instead, the extended partition is now showing as empty, and there is empty space both before and after the extended partition.  In effect, it looks like the disk has been wiped.

However, my filesystem remains mounted and I appear to still have normal access to all my files.  df -h reports the size and usage that I expect to see.
In other words, I don't know whether or not my install is safe - is it only working now because there was an active mount when Disks clobbered the partitions?  Or is Disks misreading something and in fact it's all safe?  As you can imagine, I'm not keen to reboot and find out!
Comment: No worries. Linux Mint is off topic here, but you may find the answer you seek [on the Linux Mint Forums](https://forums.linuxmint.com/)
Comment: Just to confirm, you're running Linux Mint, yes?
Comment: Yes, sorry, I meant to check the version number before posting and forgot - Mint 18.3 w/ Cinnamon.  Will edit now.
Comment: Only Ubuntu and official flavors of Ubuntu (https://ubuntu.com/download/flavours) are on-topic here, refer to https://askubuntu.com/help/on-topic where you'll find other SE sites where you question will be welcome if you don't want to use a Mint forum. (*One advantage of Ubuntu is it's many support options, you opted for Mint so take advantage of it's support options, or SE Unix & Linux*)
Answer: You'll need to boot from a Live USB to resize your main partition. You cannot, at least easily and as far as I know at all, resize a mounted partition. If you are able to use the system then it has not been wiped.
And please remember to backup your data before resizing.


Image upload isn't working using multer

Question: I setup multer like this
let multer = require('multer');

let apiRoutes = express.Router();
let UPLOAD_PATH = '../uploads';

let storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, UPLOAD_PATH);
    },
    filename: (req, file, cb) => {
        cb(null, file.fieldname + '-' + Date.now());
    }
});

let upload = multer({ storage: storage });

and in route I am getting data and an image and use multer like!
   apiRoutes.post('/update', passport.authenticate('jwt', { session: false }), (request, response) => {

    let record = {
        name: request.body.name,
        location: request.body.location,
        about: request.body.about,
        userid: request.body.userid,
        avatar: request.body.filename
    };

    let userData = {
        name: request.body.name
    };

    if (request.body.filename) {
        upload(request, response, (error) => {
        });
    }

    profile.findOneAndUpdate({ userid: request.body.userid }, record, {new: true}, (error, doc) => {
        if (error) response.json(error);

        user.findOneAndUpdate({ _id: request.body.userid }, record, (error, result) => {
            if (error) throw error;

            response.json(doc);
        });
    });
});

What is happening with this code is that when I do not send an image to backend then I get data from front end and store it into database. But when I send image along side data then it return POST /api/1.0/profile/update 401 0.396 ms - -.
It means I am not getting any data at all. Whats wring with the code here?
Answer: You can't use Multer in your /update route. Use Multer in your router like this:
var upload = multer({ dest: 'uploads/' })
apiRoutes.post('/profile', upload.single('image'), function (req, res, next) {
  // Uploaaded

})

if you add it and still can't get our file, you should update your form with this parameter:  enctype="multipart/form-data"
Comment: It does upload without JWT Auth but I need it to be secure with authentication. calling it in callback let the image upload and doesn't matter if I use it in callback or not.
Comment: Then where should I add `passport.authenticate('jwt', { session: false })`?
Comment: Call it in callback function.

Image upload isn't working using multer


How do you purge a removed app? or delete snapshot after app removal

Question: I removed an app with snap:
sudo snap remove app-name

Then I realised I should have added --purge argument to disable snapshot. When I tried to
sudo snap remove app-name --purge

it says the app-name does not exist, which is fair.
The question is now how do I remove the saved files or the created snapshot?
Answer: As I was writing the question, I quickly realized I could use the snapshot commands:
$ snap help

...
Snapshots: saved, save, check-snapshot, restore, forget
...

Looks like I need to find the saved snapshots with saved and then forget it.
$ sudo snap saved

Set  Snap      Age    Version  Rev  Size    Notes
1    app-name  4m30s  1.2.0    25   1.89MB  auto

$ sudo snap forget 1

Works.
Hope this obvious answer could help others.


When does a smooth projective toric variety admit a symplectic structure?

Question: I'm trying to understand the relationship between toric varieties and their associated polytopes.  There is a very crisp result in the case of symplectic toric varieties, namely that there is a 1:1 correspondence between such objects and Delzant polytopes.
If I instead start with a smooth projective toric variety, I can again construct a polytope associated to it, but I'm not sure what sort of correspondence there should be.  Another version of this question is the one in the title. I'm reading Cox Little Schenck, and though the answer is no doubt in here, I'm having trouble extracting anything precise, due to my inexperience in the area.
Comment: I believe that if you start with a Delzant polytope you can always cook up a symplectic manifold, it should be explained in Guillemin's book, pag 8-9 and after
Answer: Projective toric varieties are a subset of the symplectic ones, since we can pull back the Fubini-Study form. So the answer to the question in the title is 'always', and the polytopes corresponding to projective toric varieties are a subset of the Delzant polytopes.


Use value form drop down menu?

Question: I have a menu such as this:
<select>
<option value="21">option a</option>
<option value="13">option b</option>
<option value="21">option c</option>
</select>

Depending on what option is being selected I need get the corresponding value to use elsewhere in links and images. (it also needs to pull from the default option before it is clicked)

There are several unique versions of these drop downs on page.
What is the easiest way to do this?
Comment: `` tags contains `s` not the other way around
Comment: Looking at your tags, both PHP and jQuery are good.
Comment: also select has wrong markup .. option doest not include select.
Comment: @Nerd-Herd What would I echo in PHP?
Comment: @Ankur I tried a combination of PHP/Jquery and it was a mess. there has to be a simple way to do this
Answer: Use the following on $(document).ready():
function update(val) {
  $("img").attr("src", "mysite.com/images/" + val + ".jpg");
  $("a").attr("href", "mysite.com/pages/" + val + ".jpg");
}

var defaultVal = $("select").change(function () {
  update(this.value); // update  and  with the newly selected value
}).val();

update(defaultVal); // update  and  with the default value

DEMO.
Comment: Is `imageposh` the `id` of the `img`? You need to use `jQuery("#imageposh")` instead, with the `#`.
Comment: It's effecting every image and link on my page; not just "mysite.com/pages" ones. jQuery(document).ready(function() {

`function update(val) {
  jQuery("img").attr("src", "mysite.com/images/" + val + ".jpg");
  jQuery("a").attr("href", "mysite.com/pages/" + val + ".jpg");
}

var defaultVal = jQuery("select").change(function () {
  update(this.value); // update  and  with the newly selected value
}).val();

update(defaultVal); // update  and  with the default value
});`
Comment: @SamDanger: Simply change the selector from `img` and `a` to the `id`s that you want to modify.
Comment: Now it's not effecting anything.  `jQuery("imageposh").attr("src", "mysite.com/images/" + val + ".jpg");
  jQuery("lightboxposh").attr("href", "mysite.com/pages/" + val + ".jpg");
a href="mysite.com/pages/[valuegoeshere].jpg" id="lightboxposh">

}`
Comment: Thanks for you help Joao. The only problem now is that it is the default is not working. When I use the select I get the correct url/image but it shows "/pages/mage.jpg".
Comment: I assigned an ID to (select) and now it's working . thanks big time joao!
Answer: you can get the selected value by handling change event of select drop down like this
$('#yourselectid').change(function(){
currentSelectedValue=$(this).val();
alert(currentSelectedValue);
})

Working fiddle
http://jsfiddle.net/yeZ3j/
UPDATED FIDDLE
http://jsfiddle.net/yeZ3j/1/
Updated Code:
$('select').change(function() {
    currentSelectedValue = $(this).val();
    $('img').attr('src', 'mysite.com/images/' + currentSelectedValue + '.jpg');
    $('a').attr('href', 'mysite.com/images/' + currentSelectedValue + '.jpg');

    $('body').append('
currentSource of img is :' + $('img').attr('src') + ' and anchor is: ' + $('a').attr('href'))
});
$(function() {
    $('select').trigger('change')
})

Comment: Thanks @ashirvad. Now the other points in my question; how could call it out to use in an src/href and how can use this multiple times uniquely on one page?
Comment: yes, by default the top of this list shows as selected and that needs give it's value without clicking.
Comment: It's effecting every img /href on the entire page
Comment: (document).ready(function()  guarantees that your DOM is ready for modification. So it is needed for first trigger ..
Answer: If the form is being submitted as a GET request, then this would be easy. Also remember to give a name attribute to the select.  If you want to do it server-side and the name attribute is "my_name", then PHP to change the value of a link would look like this:
$option = $_GET["my_name"];
$link_text = "link";
$img_text = "";
echo $img_text . "\n" . $link_text;

Use value form drop down menu?


Why in the object retrieved by a JPA findAll() method I cannot access to the field mapped as relationship?

Question: I am working on a Spring Boot project using Spring Data JPA and I have the following problem trying to retrieve data.
I have this User class mapping a portal_user DB table:
@Entity
@Table(name = "portal_user")
@Getter
@Setter
public class User implements Serializable {

    private static final long serialVersionUID = 5062673109048808267L;

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "middle_name")
    private String middleName;

    @Column(name = "surname")
    private String surname;

    @Column(name = "sex")
    private char sex;

    @Column(name = "birthdate")
    private Date birthdate;

    @Column(name = "tex_code")
    private String taxCode;

    @Column(name = "e_mail")
    private String eMail;

    @Column(name = "contact_number")
    private String contactNumber;

    @Temporal(TemporalType.DATE)
    @Column(name = "created_at")
    private Date createdAt;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
    @JsonManagedReference
    private Set<Address> addressesList = new HashSet<>();

    //@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    //@JsonManagedReference
    //private Set<User_UserType> userToUserTypeAssociation = new HashSet<>();

    @ManyToMany(cascade = { CascadeType.MERGE })
    @JoinTable(
        name = "portal_user_user_type",
        joinColumns = { @JoinColumn(name = "portal_user_id_fk") },
        inverseJoinColumns = { @JoinColumn(name = "user_type_id_fk") }
    )
    Set<UserType> userTypes;

    public User() {
        super();
        // TODO Auto-generated constructor stub
    }

    public User(String firstName, String middleName, String surname, char sex, Date birthdate, String taxCode,
            String eMail, String contactNumber, Date createdAt) {
        super();
        this.firstName = firstName;
        this.middleName = middleName;
        this.surname = surname;
        this.sex = sex;
        this.birthdate = birthdate;
        this.taxCode = taxCode;
        this.eMail = eMail;
        this.contactNumber = contactNumber;
        this.createdAt = createdAt;
    }

}

As you can see into this entity class there are some relationship, for example this @OnetoMany relationship:
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
@JsonManagedReference
private Set<Address> addressesList = new HashSet<>();

This is my Address entity class mapping the address table on my DB:
@Entity
@Table(name = "address")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Address implements Serializable {

    private static final long serialVersionUID = 6956974379644960088L;

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;

    @Column(name = "country")
    private String country;

    @Column(name = "province")
    private String province;

    @Column(name = "zip_code")
    private String zipCode;

    @Column(name = "street")
    private String street;

    @Column(name = "notes")
    private String notes;

    //@Column(name = "fk_user_id")
    //private int fkUserId;

    @ManyToOne
    @EqualsAndHashCode.Exclude          // Needed by Lombock in "Many To One" relathionship to avoid error
    @JoinColumn(name = "fk_user_id", referencedColumnName = "id")
    @JsonBackReference
    private User user;

    public Address(String country, String province, String zipCode, String street, String notes, User user) {
        super();
        this.country = country;
        this.province = province;
        this.zipCode = zipCode;
        this.street = street;
        this.notes = notes;
        this.user = user;
    }

}

I created this unit test method to test the retrieve of all the records into my portal_user table (and the information caming from the relationship):
@Test
@Order(2)
public void RetrieveAllUsers() {

    List<User> usersList = this.userRepository.findAll();
    System.out.println(usersList.get(0).getAddressesList());
    System.out.println(usersList.get(0).getUserTypes());
    assertTrue(true);

}

The findAll() method seems works and the list is retrieved but using the debugger I cannot see the value of the two field representing a relationship, this is what I am ontaining in the "expression" tab of the debugger.
usersList   (id=180)
    [0] User  (id=193)
        addressesList   PersistentSet  (id=199)
            Error   Exception occurred: com.sun.jdi.InvocationException: Exception occurred in target VM occurred invoking method..
        birthdate   Timestamp  (id=204)
        contactNumber   329123456" (id=208)
        createdAt   Date  (id=213)
        eMail   firstname.lastname@example.com" (id=215)
        firstName   Luca" (id=216)
        id  25
        middleName  null
        sex M
        surname Verdi" (id=217)
        taxCode XXX" (id=218)
        userTypes   PersistentSet  (id=220)
            Error   Exception occurred: com.sun.jdi.InvocationException: Exception occurred in target VM occurred invoking method..
    [1] User  (id=196)
    [2] User  (id=197)
Add new expression

As you can see, the value of the addressesList and of the userTypes fields representing my relationship is something like:
Error   Exception occurred: com.sun.jdi.InvocationException: Exception occurred in target VM occurred invoking method..

As you can see in the previous unit test method code I then tried to access it by:
usersList.get(0).getAddressesList())

but when this code is performed I obtains this exception:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.easydefi.users.entity.User.addressesList, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:606)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:218)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:585)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:327)
    at java.base/java.lang.String.valueOf(String.java:3365)
    at java.base/java.io.PrintStream.println(PrintStream.java:1047)
    at com.easydefi.users.tests.RepositoryTests.UserRepositoryTest.RetrieveAllUsers(UserRepositoryTest.java:86)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:84)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

What is the problem? What am I missing? How can i try to fix this issue?
Comment: Because your releations are declared as lazy. You can only load them lazy if you have a transaction and access the fields in the same transaction in which you fetched the entity initially. Take a look at https://stackoverflow.com/a/2991015/7082956
Comment: The EntityManager was closed by the time you did `usersList.get(0).getAddressesList()` and `usersList.get(0).getUserTypes()`. This may help you: https://vladmihalcea.com/the-best-way-to-handle-the-lazyinitializationexception/
Answer: You're trying to access to a lazy-loaded object outside of the context of an open Hibernate session. To avoid this error you have some choices, two of them:
1. Using  FetchType.EAGER Strategy
  @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
  @JsonManagedReference
  private Set<Address> addressesList = new HashSet<>();

2. Using Join Fetching
  SELECT u FROM User u JOIN FETCH u.adressesList


How do I bribe ships in Freeciv?

Question: I am playing a self-imposed "single-city challenge" game (i.e. a game where I restrict myself to having only one city). Naturally, I built the city beside a sea to be able access to the rest of the world by ship. Unfortunately, I built my city in what turned out to be a landlocked sea (a large lake). As a result, the ships I currently have are not able to go to the open seas.
I am now considering bribing the ships (trireme, caravel, or transport) of other players to gain access to the open seas, but how can I bribe the ships of other players?
Freeciv version: 2.5.10
Answer: From Freeciv 2.6.0 onwards, it is possible to bribe ships.
Below is an example of bribing a transport. Note that the transport must be empty, otherwise the bribe will fail.

It's also possible to bribe other sea units (ironclads, battleships, submarines, etc.) as long as they are not loaded:

Side note: It's also possible to bribe aircraft.
Answer: Rules for bribing enemy units are (if you haven't altered them):

Either a Diplomat or Spy can bribe an other players unit.
Can't bribe a unit if:
  Owner runs an unbribable government (e.g., democracy).
  Player doesn't have enough gold.
  It's not the only unit on the square
  You are allied with the unit owner.
Otherwise, the unit will be bribed.
  A successful briber will try to move onto the victim's square.

Quoted from: https://freeciv.fandom.com/wiki/Diplomatic_actions#Bribe_Enemy_Unit
Comment: These rules do not appear to apply to ships.
Comment: I am trying to bribe the transport of a despotic government I am at war with. I have about one million gold. My spy is on land and next to the transport I want to bribe. How do I actually bribe the transport?
Comment: It's possible. I'm going to check that from the source code, when I have the time.
Comment: Just to confirm, by "It's possible", do you mean "It's possible to bribe ships", or do you mean "It's possible that these rules do not apply to ships"?
Comment: Yeah, sorry. I meant that it's possible that ships cannot be bribed, at least the same way as the other units. They may have some special restrictions on them. Does the units have to be on the same tile to perform the bribing?
Comment: Enemy units can be bribed by attempting to move a diplomat or spy onto the enemy unit's tile. A confirmation dialog containing information about the bribe amount would then appear.

How do I bribe ships in Freeciv?


Necessary conditions for AlertDialog to open

Question: Many of us have come across the dreaded

E/WindowManager﹕ android.view.WindowLeaked

This can happen for several reasons as is mentioned here and in many other SO questions.
I have tried making sure my dialogs are in a "good place" before showing them, often wrapping them around certain conditions like:
<code>if (!isFinishing() && !isDestroyed()) {
    mDialog.show();
}
</code>
I'm curious if anyone knows of a "perfect environment" for which an AlertDialog is guaranteed to always display without error. From personal experience, even with the above conditions, the WindowLeaked error still always comes up.
Answer: This really is a problem I faced when changing the orientation of the Activity, whenever we try to display a dialog with a closed Activity this error will skyrocket. In a less important case, as in a Activity data recording information, I simply ignore the Dialog and closing with the following code:
<code>@Override
public void onPause() {
    super.onPause();
    try  {
            if  (myAlertDialog != null && myAlertDialog.isShowing())  {
                myAlertDialog.dismiss();
                myAlertDialog = null ;
            }
        }  catch  (Exception  e)  {
            e.printStackTrace();
        }
}
</code>
But if you need to keep it on the screen, the only way I found was locking the orientation of Activity.


jQuery mouseenter & click events

Question: I can' t find a solution for a RWD problem on my website.
I have one breakpoint (575.98px).
If resolution is above that breakpoint, "mouseenter" event is active to show hidden section:
if ($(window).width() > 575.98) {
    $(".name").on("mouseenter", () => {
      $(".description").fadeIn(250);

but for resolution below a breakpoint I want to off "mouseenter" event and active "onClick" event.
if ($(window).width() <= 575.98) {
  $(".name").on("click", () => {
        $(".description").show();

Currently, code is not working below decided breakpoint.
Please give me any hints of solution.
Answer: you can check out the px event.
$(".name").on("mouseenter", function() {
 if ($(window).width() > 575.98){
  $(".description").fadeIn(250);
 }
});

$(".name").on("click", function() {
 if ($(window).width() <= 575.98){
  $(".description").show();
 }
});

Comment: Thnx a lot @Cem PEHLIVAN. I checked out yours solution but finally I decided to use jQuery mobile API, so I do not need to use special jquery events for different resolutions. Bye.

jQuery mouseenter & click events


access denied when adding secrets

Question: I have created a key vault using a service principal. The service principal is given all the access from the policies for keys, secrets and certificates. Now when we try setting the secret using the same service principal we get access denied issue. we also see that there are no permission to list the keys and secrets though the SP has all the permissions in the access policies.
Comment: Is this related to code being written or an administration task? If there is code generating the error, please post it. If the error is appearing in the UI, you might want to try https://serverfault.com/
Comment: Could please post the script and the error message you observed? You will get a Forbidden error if the required permission is not set (e.g. Get-AzureKeyVaultSecret : Operation returned an invalid status code 'Forbidden').
Answer: To fix access denied you need to configure Active Directory permissions. Grant access to KeyVault.
Using PowerShell:
<code>Set-AzureRmKeyVaultAccessPolicy -VaultName 'XXXXXXX' -ServicePrincipalName XXXXX -PermissionsToKeys decrypt,sign,get,unwrapKey
</code>
Using the Azure portal:

Open Key Vaults
Select Access Policies from the Key Vault resource blade
Click the [+ Add new] button at the top of the blade
Click Select Principal to select the application you created earlier
From the Key permissions drop down, select "Decrypt", "Sign", "Get", "UnwrapKey" permissions
Save changes

For more details, refer "Authorize the application to use the key or secret"
Answer: It sounds that you have already given access to your SP with access policies and since you have a SP you probably are deploying Azure resources with that SP. Besides proper access policies you need to select "Enable access to Azure Resource Manager for template deployment" under the Advanced access policies blade. The authorization of your SP occurs after the deployment have accessed the key vault.
Answer: I think I experienced something like this running Windows Powershell ISE.  I needed to run it under administrative privilege.

access denied when adding secrets


Why the value is constant?

Question: I would like to make a procedure which updates birth date, basing on personal identity number and everything works well apart from one thing. PID is taken only once and consequently the result is the same for all 200 records. How should I change this?
For example: PID of the first value is 30052766293, so birth_date = 1930-05-27,but for left PIDs result (date) is the same
CREATE PROCEDURE proc()
BEGIN
    DECLARE s INT DEFAULT 0;
    abc:LOOP
    UPDATE people
      SET birth_date = (SELECT str_to_date(CONCAT('19',substring(PID,1,2),
                          substring(PID,3,2),
                          substring(PID,5,2)
                         )
                   , '%Y %m %d') FROM workers LIMIT 1);
      SET s = s+1;
      IF s>=200
      THEN LEAVE abc;
      END IF ;
      END LOOP;
      END $$

EDIT: people and workers are separate tables and both have the same column PID
Comment: So if you have `PID` in `people` already, why do you need to get it from `workers`?
Comment: Do you only want to change 200 records or all of them?
Comment: I benefit from this convenience because when I try to 'SELECT FROM' the  same table I get error like 'Can't specify target...'
Comment: There are exactly 200 records
Comment: If there were more or less than 200, would you want to change all of them or just 200?
Comment: I would like to change all of them
Answer: As you already have the PID value in your people table, you can simply change your UPDATE to use that value. Note that since you want to change all the values in the table, you don't even need a stored procedure, you can just run this query directly:
UPDATE people
  SET birth_date = STR_TO_DATE(CONCAT('19',SUBSTRING(PID,1,2),
                                           SUBSTRING(PID,3,2),
                                           SUBSTRING(PID,5,2)
                                      )
                             , '%Y %m %d');

Note that it looks like you could further simplify this to:
UPDATE people
  SET birth_date = STR_TO_DATE(CONCAT('19',SUBSTRING(PID,1,6))
                             , '%Y%m%d');

Why the value is constant?


Java: automatically detecting input file path

Question: I need to create a program which gets its input from a file. What do I need to use in order to automatically find the current path and then search for the input file?
Example: I place my main file in C:/*pathname*/ and my input file name is INPUT.txt. How can I make my program automatically find the C:/*pathname*/INPUT.txt path to get its input?
Comment: NIO.2 can make this pretty easy: http://docs.oracle.com/javase/tutorial/essential/io/fileio.html
Comment: You will have to recursively search for INPUT.txt in 'C:' drive also called walking the file tree. More info: http://docs.oracle.com/javase/tutorial/essential/io/walk.html
Comment: Is your input file always in the same folder as your program? Then you can use relative paths `new File(./INPUT.txt)`
Answer: You can use recursion in this case, to find your file. You start the searching process in the current/given directory, by checking if your current file matches the given file name. If you find a directory, you continue the recursion searching process in this directory.
private static final File findFile(final String rootFilePath, final String fileToBeFound) {

    File rootFile = new File(rootFilePath);
    File[] subFiles = rootFile.listFiles();
    for (File file : subFiles != null ? subFiles : new File[] {}) {
        if (file.getAbsolutePath().endsWith(fileToBeFound)) {
            return file;
        } else if (file.isDirectory()) {
            File f = findFile(file.getAbsolutePath(), fileToBeFound);
            if (f != null) {
                return f;
            }
        }
    }

    return null; // null returned in case your file is not found

}

public static void main(final String[] args){

     File fileToBeFound = findFile("C:\\", "INPUT.txt"); // search for the file in all the C drive
     System.out.println(fileToBeFound != null ? fileToBeFound.getAbsolutePath() : "Not found");

     //you can also use your current workspace directory, if you're sure the file is there
    fileToBeFound = findFile(new File(".").getAbsolutePath() , "INPUT.txt");
    System.out.println(fileToBeFound != null ? fileToBeFound.getAbsolutePath() : "Not found");
}


GIT tree is messed up

Question: My Git tree looks like this.

All I did was create two branches A and B and then merged them in one after the other after rebasing with master. then I deleted those branches from remote as well as local. But even then my tree looks like this. What could be wrong? and how can I fix it?
I am connecting to a GIT repo on VisualStudio hosted online.
Comment: What makes you think this is wrong?  You say you merged two branches; the graph above shows `master` pointing to a merge commit, with two branches; and that's what you did, so that's what I would expect to see.
Comment: as far as I know it should be a straight line when you only have a master and no other branches. Is there any document on how to read the GIT branch tree and figure out whats going on? I am trying to figure out how to read the state of the repo by looking at the branch in gitk
Comment: Beware of the multiple meanings of the word "branch", in git.  You do only have one branch (`master`), which has two branches (that have no names).  In one case we're referring to the label giving the tip commit, and in the other we're referring to the commit graph.  See also http://stackoverflow.com/questions/25068543/what-exactly-do-we-mean-by-branch
Answer: I don't think the tree is mess up.
Merge has some options(Fast Forward) that may help you. If you don't want to merge to create a separate road, you should use ff. If you're going to do what you did above, use no-ff.

git merge myBranch --ff

or

git merge myBranch --no-ff

You can try running two commands to see the difference.

GIT tree is messed up


python manage.py migrate on terminal then error show?

Question: Traceback (most recent call last):
  File "manage.py", line 16, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

Comment: Well did you forget to activate the virtual environment? (it is part of the error message)?
Comment: Here you have answer for the same question...
https://stackoverflow.com/questions/46210934/importerror-couldnt-import-django
Answer: good article to understand PYTHONPATH: https://bic-berkeley.github.io/psych-214-fall-2016/using_pythonpath.html
export PYTHONPATH="$PYTHONPATH:/home/user/work/your_django_project"


How to exclude package from Scala SBT

Question: I am at loss. I am using Scala with SBT and I had to add databricks dependency (link dependencies i get when I install databricks-connect) via unmanagedBase in the build.sbt and now when I try to run the application I get this error. I have tried excluding packages but nothing helps. Maybe I am doing it wrong. Could someone please help me. What package should I exclude to make this thing work since I am getting org.slf4j.impl.Log4jLoggerFactory cannot be cast to ch.qos.logback.classic.LoggerContext?
Comment: What did you try to exclude SBT dependency? What didn't work?
Answer: To understand what is happening (and to prevent this in the future), you probably need to read and understand SLF4J user manual.

The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks, such as java.util.logging, logback and reload4j.

In Binding with a logging framework at deployment time section it says:

slf4j-log4j12-1.7.35.jar
Binding/provider for log4j version 1.2, a widely used logging framework.
logback-classic-1.2.10.jar (requires logback-core-1.2.10.jar)
There are also SLF4J bindings/providers external to the SLF4J project, e.g. logback which implements SLF4J natively.

First you'd have to decide if you want log4j as the logger implementation or logback. The screenshot doesn't show org.slf4j:slf4j-log4j12:something, but is it included?
Assuming you want to exclude log4j binding, then that's the one you need to exclude.
To exclude something from all dependencies in a subproject:
excludeDependencies ++= Seq(
  ExclusionRule("org.slf4j", "slf4j-log4j12")
)

For more details, see Exclude Transitive Dependencies.
Comment: I really am still at loss... I don't really understand where the cast conflicts happen.

How to exclude package from Scala SBT


Pivoting results in more rows than needed

Question: I have query like this:

`SELECT [/BIC/IORSVPTX] as Region,
COUNTRY_ID,
[/BIC/IOWCNTRY] as Country,
[/BIC/IOC_TRLNO] as Trial,
[/BIC/IOWQUAL] as ResourceType,
case

    when [/BIC/IOWQUAL] like '%Supporter%'
      then 1
  when [/BIC/IOWQUAL] like '%Monitor%'
      then 3
  when [/BIC/IOWQUAL] like '%PM%'
      then 2

  end as ResourceGroup,
[1], [2], [3], [4], [5]
FROM
    (
SELECT  [/BIC/IORSVPTX],
COUNTRY_ID,
[/BIC/IOWCNTRY],
[/BIC/IOC_TRLNO],
[/BIC/IOWQUAL],    case

    when [/BIC/IOWQUAL] like '%Supporter%'
      then 1
  when [/BIC/IOWQUAL] like '%Monitor%'
      then 3
  when [/BIC/IOWQUAL] like '%PM%'
      then 2

  end as ResourceGroup,
left(CALMONTH,4) as StartYear,
right(CALMONTH,2) as StartMonth,
((left(CALMONTH,4) - 2013) * 12) + right(CALMONTH,2) AS YearMonth,
QUANTITY as Hours
         FROM dbo.Actuals
        where [/BIC/IOC_TRLNO]<>'0000' and left(CALMONTH,4)>2012 and   COUNTRY_ID='10'
and ([/BIC/IOWQUAL] like '%PM%' or [/BIC/IOWQUAL] like'%Monitor%' or [/BIC/IOWQUAL]   like '%Supporter%')
) up
PIVOT (sum(Hours) FOR YearMonth IN ([1],[2],[3],[4],[5])) AS pvt;
IN ([1],[2],[3],[4],[5])) AS pvt;`

which gives me the output with 2 rows for each ResourceType and ResourceGroup with hours for 1(Jan) and 2nd row with hours for 2(Feb) instead of 1 row
Region  COUNTRY_ID  Country Trial   ResourceType    ResourceGroup   1   2   3   4   5
North America   10  USA 3619     Monitor    3   158.5   NULL    NULL    NULL    NULL
North America   10  USA 3619     Monitor    3   NULL    42  NULL    NULL    NULL
North America   10  USA 3619     PM / LTM / RTM     2   20  NULL    NULL    NULL    NULL
North America   10  USA 3619     PM / LTM / RTM     2   NULL    22  NULL    NULL    NULL
North America   10  USA 3619     Supporter  1   18.5    NULL    NULL    NULL    NULL
North America   10  USA 3619     Supporter  1   NULL    15.75   NULL    NULL    NULL

desired output should be like this:
Region  COUNTRY_ID  Country Trial   ResourceType    ResourceGroup   1   2   3   4   5
North America   10  USA 3619     Monitor    3   158.5   42  NULL    NULL    NULL
North America   10  USA 3619     PM / LTM / RTM     2   20  22  NULL    NULL    NULL
North America   10  USA 3619     Supporter  1   18.5    15.75   NULL    NULL    NULL

I will appreciate your help!
Answer: I see a few things wrong with your current query.
First, you are using the CASE expression in the outer and the subquery. I don't fully understand why you are doing that as you created a column called ResourceGroup.
Second, you will get multiple rows if your subquery contains columns with distinct values and you apply the pivot.
For example in your subquery you are using:
left(CALMONTH,4) as StartYear,
right(CALMONTH,2) as StartMonth,

But you do not have these in the final select list, if you added them to the final select they will probably show distinct values which are causing the problem during the pivot grouping.
Based on your existing query I am guessing you want to use:
SELECT
  [/BIC/IORSVPTX] as Region,
  COUNTRY_ID,
  [/BIC/IOWCNTRY] as Country,
  [/BIC/IOC_TRLNO] as Trial,
  [/BIC/IOWQUAL] as ResourceType,
  ResourceGroup,
  [1], [2], [3], [4], [5]
FROM
(
  SELECT [/BIC/IORSVPTX],
    COUNTRY_ID,
    [/BIC/IOWCNTRY],
    [/BIC/IOC_TRLNO],
    [/BIC/IOWQUAL],
    case
      when [/BIC/IOWQUAL] like '%Supporter%' then 1
      when [/BIC/IOWQUAL] like '%Monitor%'   then 3
      when [/BIC/IOWQUAL] like '%PM%'  then 2
    end as ResourceGroup,
    ((left(CALMONTH,4) - 2013) * 12) + right(CALMONTH,2) AS YearMonth,
    QUANTITY as Hours
  FROM dbo.Actuals
  where [/BIC/IOC_TRLNO]<>'0000'
    and left(CALMONTH,4)>2012
    and   COUNTRY_ID='10'
    and ([/BIC/IOWQUAL] like '%PM%'
         or [/BIC/IOWQUAL] like'%Monitor%'
         or [/BIC/IOWQUAL] like '%Supporter%')
) up
PIVOT
(
  sum(Hours)
  FOR YearMonth IN ([1],[2],[3],[4],[5])
) AS pvt;


Embed a string of compiler options in an executable (Visual Studio)

Question: Using gcc and Makefiles, I am able to embed some compiler options into a string for an executable to access as follows:
Makefile:
CXX=/usr/bin/g++
CXXFLAGS=-ansi -Wall -c
CXXDEFINES='-DCXXCOMMAND="$(CXX) $(CXXFLAGS)"'

C++ file:
#ifdef CXXCOMMAND
    std::cout << "C++ Command: " << CXXCOMMAND << std::endl;
#endif

And then I am able to print it to the console from the executable.
Is it possible to do this in Visual Studio? Specifically I am looking to put in the optimization flags (/O2, /Od, etc...), but the more I have access to, the better things will work for me.
Microsoft Visual Studio Professional 2012
Intel C++ Composer XE 2013 SP1
Comment: possible duplicate of [Where can I modify detailed C# compiler optimization settings in Visual Studio?](http://stackoverflow.com/questions/3226157/where-can-i-modify-detailed-c-sharp-compiler-optimization-settings-in-visual-stu)
Comment: `cl` has a `/D` option that lets you define pre-processor macros; is that what you're asking?
Answer: Yes, sort of. You can define a macro in the project properties that contains a string, and embed within it any project property values you want. However, these properties, while used to construct the command line, are not the actual command line flags themselves.
For example, add the following as a Preprocessor Definition in the C/C++ Preprocessor project properties:
CXXCOMMAND="%(Optimization)"

Then CXXCOMMAND is "MinSpace" for a build set to compile with /O1.
Just be careful to have only an even number of quotes in your preprocessor define...
Comment: To find out the name of each project property, simply set it to a non-default value and then look in the .vcxproj file using a text editor.


Laravel and Mamp Localhost Error 500 Mac

Question: So after a fresh install of laravel (v5.4) and using Mamp as my local server I just get (in chrome)
The localhost page isn't working

localhost is currently unable to handle this request.
HTTP ERROR 500

I've tried countless things like changing permissions on storage or everything within the laravel directory.
Done composer update/install in the directory.
I'm running PHP v7.0.12 on my Mac (10.11.6). Cant think of anything else that would be causing this?
If I create another directory which a simple index.php with '' it loads absolutely fine so what is causing an issue with laravel?
Here's pics of my mamp setup
https://i.stack.imgur.com/hg3lV.png

https://i.stack.imgur.com/uNUU1.png
Comment: Are you using the correct url? Laravel requests always start in the public folder. So if you installed a Laravel instance in the public folder of your localhost, you need to access it via `localhost/public`
Comment: Check your storage/log/laravel.log file. It will have more information about error.
Comment: As far as I'm aware I should be accessing it via localhost:8888 (mamp opens the start page at http://localhost:8888/MAMP/?language=English). I've set the directory for the server to laravel/public so shouldn't need to access via /public
Comment: What's your apache configuration?
Comment: Have added links to screenshots of mamp config in original post
Comment: Did you run composer install in your base directory?
Answer: Open up terminal and type:
tail -n 20 /Applications/MAMP/logs/php_error.log

This may give you some clue as to what is going on.
Hope this helps, happy coding :)
Comment: This is what I got (bare in mind I did a fresh install?) - https://pastebin.com/wVC8NJjC
Comment: Appears PHP version keeps changing now dependant on directory and the version inside my laravel directory gives me 5.5.36. How do I go about changing this version to 7 globally?
Comment: You can download the version you require from http://www.mamp.info/en/downloads/\

**Also** Mamp only allows 2 versions of php to show up. Quick fix, rename the folders you're not bothered about using, for me this meant adding an "X" to to my /Applications/MAMP/bin/php/php5.4.10_X folder. Now your current version and 7.0.0  show up in the mamp prefs.

Done!
Comment: Think I've managed to get it to work now. Managed to get php 5.6.30 with php -v but i do need to do composer install after a fresh install of laravel it appears. EDIT: Tell a lie, closed terminal, reopned and the version of php has changed back to 5.5.36, whats going on?
Comment: So in my .bash_profile I had `export PATH=/Applications/MAMP/bin/php/php5.6.27/bin:$PATH`, I run source ~/.bash_profile and it shows the correct version (5.6.27). If I quit terminal and reopen and do php -v it gives me 5.5.36. Why is this not saving?
Answer: I just joined stackoverflow yesterday so I do not have enough reputation to comment. I write an answer here.
here is the short answer:
run :
PHP_VERSION=`ls /Applications/MAMP/bin/php/ | sort -n | tail -1`
echo "export PATH=/Applications/MAMP/bin/php/${PHP_VERSION}/bin:$PATH" >> .bash_profile
source ~/.bash_profile

check your php version by running php -v. close the terminal. Open another terminal and check php version again.if you see php 5 again then there are 2 possibilities:
First: you added the /path/to/php7 after /path/to/php5 and php 5 is loaded first.
Second: system loads another bash file first which your php 5 path is mentioned in it. I know that this sounds confusing having several bash file but it is. Please search for other files like bashrc or similars.
This is the long answer for anyone else:
first of all, if you are on mac, I highly suggest you to use valet to get rid of all these things.
But regarding the problem:
As you already noted that it is not a laravel issue. the php version that your machine uses is under the min required version by laravel. You have 2 versions of php at the moment. MacOs is shipped with php installed on that. I think it is the same php 5.5.36 that is making problem for you. Since Laravel 5.4, you need to use PHP >= 5.6.4.
Although you have installed parallel php 7 on your machine, you need also to check which php your machine is reading from by running which php. after that remember to add your path to php 7 installed to bash_profile or other bash files on your mac(you can have 4 or 5 bash files).
Considering you have only one bash file named as bash_profile and you are going to export the path to your php 7 to bash profile, If you run following command, that appends the path to the end of file
PHP_VERSION=`ls /Applications/MAMP/bin/php/ | sort -n | tail -1`
echo "export PATH=/Applications/MAMP/bin/php/${PHP_VERSION}/bin:$PATH" >> .bash_profile

remember to use source ~/.bash_profile in order to make changes effected.
Alternatively you can open the bash_profile file in your text editor by running:
open -a /Applications/TextEdit.app ~/.bash_profile

and add the path manually before the /path/to/php5 path.
finally you must check your php version by running php -v.
close the terminal. Open another terminal and check php version again. If you see php 7 then you are all fine. But if you see php 5 again then there are 2 possibilities:
First: you added the /path/to/php7 after /path/to/php5 and php 5 is loaded first.
Second: system loads another bash file first which your php 5 path is mentioned in it. I know that this sounds confusing having several bash file but it is. Please search for other files like bashrc or similars.


Help with proving a trigonometric identity

Question: I am attempting to prove a trigonometric identity. I have no idea how to do it without performing operations across the equal sign. This is the identity:
$$\frac{\cos(3a)}{\cos(a)}=2\cos(2a)-1$$
And here's what I have:
$$\frac{\cos(3a)}{\cos(a)}=2\cos(2a)-1$$
$$\frac{4\cos^3(a)-3\cos(a)}{\cos(a)}$$
$$\frac{(\cos(a))(4\cos^2(a)-3)}{\cos(a)}$$
$$(4\cos^2(a)-3)=2\cos(2a)-1$$
From here, I am at a loss. Thanks for the help.
Comment: Kinda surprised you knew $cos3a$ but not $cos2a$ in terms of $cos a$
Answer: Use $cos2a = 2cos^2a-1$ after the last step.
Answer: You were almost there: $4cos^2a-3=2cos^2a+2(1-sin^2a)-3=2(cos^2a-sin^2a)-1=2cos(2a)-1$


How can I group time by hour or by 10 minutes?

Question: Like when I do
SELECT [Date]
  FROM [FRIIB].[dbo].[ArchiveAnalog]
  GROUP BY [Date]

How can I specify the group period? I'm using MS SQL 2008.
I've tried this, both with % 10 and / 10.
SELECT MIN([Date]) AS RecT, AVG(Value)
  FROM [FRIIB].[dbo].[ArchiveAnalog]
  GROUP BY (DATEPART(MINUTE, [Date]) / 10)
  ORDER BY RecT

Is it possible to make Date output without milliseconds?
Comment: [All much easier in SQL Server 2022](https://stackoverflow.com/a/76813191/73226)
Comment: I know you have an answer but what is the DATATYPE of the date column you're working with?
Answer: finally done with
GROUP BY
DATEPART(YEAR, DT.[Date]),
DATEPART(MONTH, DT.[Date]),
DATEPART(DAY, DT.[Date]),
DATEPART(HOUR, DT.[Date]),
(DATEPART(MINUTE, DT.[Date]) / 10)

Comment: I made it `ROUND((DATEPART(MINUTE, DT.[Date]) / 5),0,1) * 5`, so that when I look at the data it's correlated with the nearest time slot
Comment: Year, month and day can be simplified to `DATE(DT.[Date])`.
Comment: @Keelan Doesn't work for me - however CONVERT(date, DT.[Date]) does.
Comment: `datepart(hour, workingPolicy.workingHours)/2.0` gives `1.5` while `datepart(hour, '1900-01-01 09:00:30.000')/2.0` gives `4.5` , i don't understand why? **Note:workingPolicy.workingHours=1900-01-01 09:00:30.000**. please help
Comment: Took me a while before I realized you weren't listing possible `DATEPART` options you could use but that you have to use all of the `DATEPART`'s
Answer: Short and sweet
GROUP BY DATEDIFF(MINUTE, '2000', date_column) / 10

With heavy acknowledgements to Derek's answer, which1 forms the core of this one. If you're on SQL Server 2022+, go straight to Martin's answer.
Practical usage
SELECT   DATEADD(MINUTE, DATEDIFF(MINUTE, '2000', aa.[date]) / 10 * 10, '2000')
                                                             AS [date_truncated],
         COUNT(*) AS [records_in_interval],
         AVG(aa.[value]) AS [average_value]
FROM     [friib].[dbo].[archive_analog] AS aa
-- WHERE aa.[date] > '1900-01-01'
GROUP BY DATEDIFF(MINUTE, '2000', aa.[date]) / 10
-- HAVING SUM(aa.[value]) > 1000
ORDER BY [date_truncated]

Details and extra commentary
Bin interval size
The MINUTE and 10 terms can be changed to any DATEPART and integer,2 respectively, to group into different time intervals. For example, 10 with MINUTE is ten minute intervals; 6 with HOUR is six hour intervals.
If you change the interval a lot, you might benefit from declaring it as a variable.
DECLARE @interval int = 10;

SELECT   DATEADD(MINUTE, DATEDIFF(…) / @interval * @interval, '2000')
…
GROUP BY                 DATEDIFF(…) / @interval

Value type
The actual values being grouped are a set of relative offsets from 2000-01-01 00:00. This means data sources over long time intervals are fine. Some other answers have collision between years.
Multiplying the GROUP BY expression by the interval size and wrapping it in a DATEADD invocation will return you a DATETIME value. Including it in the SELECT statement will give your output a single column with the truncated timestamp. See the "Practical Usage" example above.
Shifting the label for the bin interval
The division (/) operation after DATEDIFF truncates values to integers (a FLOOR shortcut), which yields the beginning of time intervals for each row in your SELECT output.
If you want to label each row with the middle or end of its interval, you can tweak the division in the second term of DATEADD with the bold part below:

End of interval: …) / 10 * 10 + 10 , '2000'), credit to Daniel Elkington.
Middle of interval: …) / 10 * 10 + (10 / 2.0) , '2000').

If you want to round your intervals inward such that each timestamp represents half an interval before and half an interval after it, use something like this:
DATEADD(MINUTE, ROUND(1. * DATEDIFF(MINUTE, '2000', date_column) / 10, 0) * 10, '2000')

Note the 1. to do untruncated division instead. You will need to modify your GROUP BY to match, and you may want to use the whole ROUND(…) expression to avoid any unexpected float rounding.
Date math trivia
'2000' is an "anchor date" around which SQL will perform the date math. Most sample code uses 0 for the anchor, but JereonH discovered that you encounter an integer overflow when grouping more-recent dates by seconds or milliseconds.3
If your data spans centuries,4 using a single anchor date in the GROUP BY for seconds or milliseconds will still encounter the overflow. For those queries, you can ask each row to anchor the binning comparison to its own date's midnight.
Use one of the two replacements instead of '2000' wherever it appears in the query:

DATEADD(DAY, DATEDIFF(DAY, 0, aa.[date]), 0)
CONVERT(DATETIME, CONVERT(DATE, aa.[date]))

Your query will be totally unreadable, but it will work.

1 I realized several years after posting that my code could be simplified to nearly the same as Derek's answer.
2 If you want all :00 timestamps to be eligible for binning, use an integer that your DATEPART's maximum can evenly divide into.5 As a counterexample, grouping results into 13-minute or 37-hour bins will skip some :00s, but it should still work fine.
3 The math says 232 ≈ 4.29E+9. This means for a DATEPART of SECOND, you get 4.3 billion seconds on either side, which works out to "anchor date ± 136 years." Similarly, 232 milliseconds is ≈ 49.7 days.
4 If your data actually spans centuries or millenia and is still accurate to the second or millisecond… congratulations! Whatever you're doing, keep doing it.
5 If you ever wondered why our clocks have a 12 at the top, reflect on how 5 is the only integer from 6 (half of 12) or below that is not a factor of 12. Then note that 5 × 12 = 60. You have lots of choices for bin sizes with hours, minutes, and seconds.
Comment: for SECOND as DATEPART I get an error message  (`The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.`). It seems that MINUTE is the smallest datepart you can use with this approach.
Comment: @jeroenh, you are correct. I have added a section to talk about that. tldr: Change the `0` to `'2000'` (quotes are important!) and try `SECOND` again.
Comment: To round UP to the nearest 10 minutes you can do
`GROUP BY DATEADD(MINUTE, (DATEDIFF(MINUTE, 0, date_column) / 10 * 10) + 10, 0)` (and the same in the SELECT clause).
Comment: @Michael This technique works great, but I did notice that if a given slice has a zero count, there is no corresponding row in the result set.
Comment: @howcheng Indeed. To do that, you could right-join against a table of all the possible intervals. You can generate one with a `cursor`, but I feel that's out of scope for the question.
Answer: In T-SQL you can:
SELECT [Date]
  FROM [FRIIB].[dbo].[ArchiveAnalog]
  GROUP BY [Date], DATEPART(hh, [Date])

or
by minute use DATEPART(mi, [Date])
or
by 10 minutes use DATEPART(mi, [Date]) / 10 (like Timothy suggested)
Comment: Minutes divided by 10 will create grouping by 10 minute intervals, which i what's needed. Modulo 10 makes no sense.
Comment: GROUP BY [Date], DATEPART(hh, [Date]) is a mess , not ?
Comment: @nCdy Should be all right, otherwise you get an error "...invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"
Comment: How do you group by whole date and by hours in the same time? I'm just using Min Date .
Comment: if you use Min(Date) then of course you can take out the Date in the Group By.
Comment: If possible please amend your answer to use "DATEPART(mi, [Date]) / 10" instead of the above. This initially gave me the impression that SQL interprets the '%' sign as something other than modulo.  =>
`SELECT (27 / 10) = 2`
`SELECT (27 % 10) = 7`
Answer: For a 10 minute interval, you would
GROUP BY (DATEPART(MINUTE, [Date]) / 10)

As was already mentioned by tzup and Pieter888... to do an hour interval, just
GROUP BY DATEPART(HOUR, [Date])

Comment: Minutes divided by 10 will create grouping by 10 minute intervals, which i what's needed.
Modulo 10 makes no sense.
Comment: but here I group minutes of 1980 year with minutes of 2011 :S I need to care about it.
Comment: Would % be the correct math? Wouldn't that create 10 groups. For example:

1 % 10 = 9
2 % 10 = 8

It wouldn't even necessarily be the correct chronological grouping either.

I think just a normal divide would be correct. Unless % isn't a remainder divide in sql.
Answer: The original answer the author gave works pretty well. Just to extend this idea, you can do something like
group by datediff(minute, 0, [Date])/10

which will allow you to group by a longer period then 60 minutes, say 720, which is half a day etc.
Comment: What would be the MySQL query for the above ?
Comment: this one is definitely better than the accepted answer.
one can also set an arbitrary date instead of 0, and make the resulting datediff smaller:
DATEDIFF(minute, CAST('2021-08-01' AS datetime), [Date])/10
Comment: @ChingizK. The `CAST` can be implicit. `DATEDIFF(MINUTE, '2021-08-01', [Date])/10` works fine.
Answer: Should be something like
select timeslot, count(*)
from
    (
    select datepart('hh', date) timeslot
    FROM [FRIIB].[dbo].[ArchiveAnalog]
    )
group by timeslot

(Not 100% sure about the syntax - I'm more an Oracle kind of guy)
In Oracle:
SELECT timeslot, COUNT(*)
FROM
(
    SELECT to_char(l_time, 'YYYY-MM-DD hh24') timeslot
    FROM
    (
        SELECT l_time FROM mytab
    )
) GROUP BY timeslot

Answer: For MySql:
GROUP BY
DATE(`your_date_field`),
HOUR(`your_date_field`),
FLOOR( MINUTE(`your_date_field`) / 10);

Answer: For people on SQL Server 2022+ there is now a dedicated DATE_BUCKET function that addresses this need.
Example usage
DECLARE @ArchiveAnalog TABLE
(
[Date] DATETIME2 PRIMARY KEY,
Value FLOAT
)

INSERT @ArchiveAnalog
VALUES
    ('2000-01-01 16:20:00.000', 1),  --Bucket 1
    ('2000-01-01 16:22:53.250', 2),
    ('2000-01-01 16:29:59.999', 3),
    ('2000-01-01 16:31:53.250', 4),  --Bucket 2
    ('2000-01-01 16:36:53.250', 5)

SELECT
        DATE_BUCKET (minute, 10, [Date] ) AS BucketedValue,
        MIN([Date]) AS RecT,
        COUNT(*) AS BucketCount,
        AVG(Value) AS BucketAvg
FROM @ArchiveAnalog
GROUP BY DATE_BUCKET (minute, 10, [Date] )
ORDER BY DATE_BUCKET (minute, 10, [Date] )

BucketedValue
RecT
BucketCount
BucketAvg

2000-01-01 16:20:00.0000000
2000-01-01 16:20:00.0000000
3
2

2000-01-01 16:30:00.0000000
2000-01-01 16:31:53.2500000
2
4.5

If the underlying column is indexed this can also be pretty efficient
Answer: If you want to actually display the date, have a variable grouping, and be able to specify larger time frames than 60 minutes:
DECLARE @minutes int
SET @minutes = 90

SELECT
    DATEADD(MINUTE, DATEDIFF(MINUTE, 0, [Date]) / @minutes * @minutes, 0) as [Date],
    AVG([Value]) as [Value]
FROM [FRIIB].[dbo].[ArchiveAnalog]
GROUP BY
    DATEDIFF(MINUTE, 0, [Date]) / @minutes

Answer: declare @interval tinyint
set @interval = 30
select dateadd(minute,(datediff(minute,0,[DateInsert])/@interval)*@interval,0), sum(Value_Transaction)
from Transactions
group by dateadd(minute,(datediff(minute,0,[DateInsert])/@interval)*@interval,0)

Comment: Welcome to stackoverflow. You need to fully explain your answer, and what this adds to the other 10 answers already on the site.
Answer: In SQLite, in order to group by hour, you can do:
GROUP BY strftime('%H', [FRIIB].[dbo].[ArchiveAnalog].[Date]);

and to group by each 10 minutes:
GROUP BY strftime('%M', [FRIIB].[dbo].[ArchiveAnalog].[Date]) / 10;

Answer: My solution is to use a function to create a table with the date intervals and then join this table to the data I want to group using the date interval in the table.
The date interval can then be easily selected when presenting the data.
CREATE FUNCTION [dbo].[fn_MinuteIntervals]
    (
      @startDate SMALLDATETIME ,
      @endDate SMALLDATETIME ,
      @interval INT = 1
    )
RETURNS @returnDates TABLE
    (
      [date] SMALLDATETIME PRIMARY KEY NOT NULL
    )
AS
    BEGIN
        DECLARE @counter SMALLDATETIME
        SET @counter = @startDate
        WHILE @counter <= @endDate
            BEGIN
                INSERT INTO @returnDates VALUES ( @counter )
                SET @counter = DATEADD(n, @interval, @counter)
            END
        RETURN
    END

Comment: Using a cursor will be very very slow on large data sets.
Answer: For SQL Server 2012, though I believe it would work in SQL Server 2008R2, I use the following approach to get time slicing down to the millisecond:
DATEADD(MILLISECOND, -DATEDIFF(MILLISECOND, CAST(time AS DATE), time) % @msPerSlice, time)

This works by:

Getting the number of milliseconds between a fixed point and target time:@ms = DATEDIFF(MILLISECOND, CAST(time AS DATE), time)
Taking the remainder of dividing those milliseconds into time slices:@rms = @ms % @msPerSlice
Adding the negative of that remainder to the target time to get the slice time:DATEADD(MILLISECOND, -@rms, time)

Unfortunately, as is this overflows with microseconds and smaller units, so larger, finer data sets would need to use a less convenient fixed point.
I have not rigorously benchmarked this and I am not in big data, so your mileage may vary, but performance was not noticeably worse than the other methods tried on our equipment and data sets, and the payout in developer convenience for arbitrary slicing makes it worthwhile for us.
Answer: select from_unixtime( 600 * ( unix_timestamp( [Date] ) % 600 ) ) AS RecT, avg(Value)
from [FRIIB].[dbo].[ArchiveAnalog]
group by RecT
order by RecT;

replace the two 600 by any number of seconds you want to group.
If you need this often and the table doesn't change, as the name Archive suggests, it would probably be a bit faster to convert and store the date (& time) as a unixtime in the table.
Answer: I know I am late to the show with this one, but I used this - pretty simple approach.  This allows you to get the 60 minute slices without any rounding issues.
Select
   CONCAT(
            Format(endtime,'yyyy-MM-dd_HH:'),
            LEFT(Format(endtime,'mm'),1),
            '0'
          ) as [Time-Slice]

Answer: select dateadd(minute, datediff(minute, 0, Date), 0),
       sum(SnapShotValue)
FROM [FRIIB].[dbo].[ArchiveAnalog]
group by dateadd(minute, datediff(minute, 0, Date), 0)

Comment: Please provide some explanations when you answer a question.
Answer: Try this query. It makes one column. (references @nobilist answer)
GROUP BY CAST(DATE(`your_date_field`) as varchar) || ' ' || CAST(HOUR(`your_date_field`) as varchar) || ':' || CAST(FLOOR(minute(`your_date_field`) / 10) AS varchar) || '0' AS date_format

Answer: Here is an option that provides a human readable start time of that interval (7:30, 7:40, etc).
In a temp table, it truncates seconds and milliseconds by using SMALLDATETIME, and then the main query subtracts any amount over the desired minute interval.
SELECT DATEADD(MINUTE, -(DATEDIFF(MINUTE, '2000', tmp.dt) % 10), tmp.dt)
FROM (
    SELECT CAST(DateField AS SMALLDATETIME) AS dt
    FROM MyDataTable
) tmp

It can also be done in a single line of code, but it is not as readable.
SELECT DATEADD(MINUTE, -(DATEDIFF(MINUTE, '2000', CAST(DateField AS SMALLDATETIME)) % 10), CAST(DateField AS SMALLDATETIME)) AS [interval] FROM MyDataTable


Why can't I swim from Darkshore to Felwood?

Question: I was leveling a Druid Paladin, and I wanted to see if I could swim to Felwood from Darkshore to peek in on my partner's raid team. I noticed them flying across the map. I then noticed two small bodies of water connect these two places, but I was unable in game to make this swim. It was like running into a swim-wall that prevented me from going further. I recently deactivated my account, but below is a screenshot of the map.
I'm sure there are practical reasons for this, but I'm curious if I'm the only one who has tried this or if someone knows the actual reasons for why this is not possible.
Comment: Last time I checked, those were both waterfalls because Felwood is at a much higher elevation than Darkshore is.
Answer: What Powerlord says.
Darkshore is coastal flatlands, maybe 20m above sea level.  Felwood is very high in the mountains.  The path between them is much more vertical than horizontal.
These waterways (and the Felwood cliffs generally) are actually a stepped series of cliffs.  The intermediate levels are not accessible from the bottom except via a flying mount.  If a character's ghost could not fly, they could not access their corpse - which is a lousy player experience.*
So, if you jump or fall off Felwood, and miss the pool of water at the bottom of the waterfall, you're probably going to have a bad 10 minutes.
Even if you have flight, remember, only druids have a flying form they can take while moving. Everyone else must stop to summon a flying mount (which means they can't while falling). Their only option is a slow-fall ability like a parachute cloak... and those are very tricky because Felwood's cliffs are so very tall.  You get 10-30 seconds of slow fall, and that will run out far too soon. And they typically have a 30-600 second cooldown, so you must pop it right before you smash. Even then, you can drift off another cliff, because most slow-falls are NOT steerable.
The upshot is going off cliffs as tall as Felwood's sucks, so I can see the reason for the wall.

* Because after you spend 20 minutes failing to find a path, you must return to the spirit healer and take a penalty giving 10 minutes of resurrection sickness, during which time you are too weak to fight. Major annoyance.


MSpec and base class test failure while writing test for Asp.net mvc 3 controller

Question: I am currently writing some MSpec specs for this controller which has already been implemented (yes I know doing it the "wrong" way round).
It is a "simple" problem but I'm not sure what I'm doing wrong and hopefully someone will be able to point the error of my ways.
My Controller's method is as follows:
 public ActionResult Add()
    {
        this.SetPageTitle("Add something");
        return this.View();
    }

The issue I'm having is with
this.SetPageTitle("Add something");

The method is defined in a base class (BaseController) from which the current controller (CompanyHomeController) is defined.
My spec is as follows:
[Subject(typeof(CompanyHomeController))]
public class when_the_company_add_page_is_requested
{
    static string pageTitle;

    static ActionResult result;

    static CompanyHomeController companyHomeController;

    // Arrange
    Establish a_company_home_controller_context = () =>
        {
            var companyDao = A.Fake<ICompanyDao>();
            companyHomeController = new CompanyHomeController(companyDao);

            pageTitle = "Add something";
        };

    // Act
    Because of = () => result = companyHomeController.Add();

    // Assert
    private It should_display_a_view = () => result.ShouldBeAView();

}

When I run the test, it fails and I get this message:
System.NullReferenceException: Object reference not set to an instance of an object.
at ..Commons.Hosts.Web.Mvc.Base.BaseController.SetPageTitle(String title) in C:\Projects\Commons\.Commons.Hosts\Web\Mvc\Base\BaseController.cs:line 87
at ..Hosts.Web.Areas.Company.Controllers.CompanyHomeController.Add() in C:\Projects\\Hosts\.Hosts.Web\Areas\Company\Controllers\CompanyHomeController.cs:line 93
at ..Hosts.Web.Specs.Areas.Company.Controllers.when_the_company_add_page_is_requested.<.ctor>b__1() in C:\Projects\Hosts\.Hosts.Web.Specs\Areas\Company\Controllers\CompanyHomeControllerSpecs.cs:line 43
at Machine.Specifications.Utility.RandomExtensionMethods.InvokeAll(IEnumerable`1 actions) in d:\BuildAgent-02\work\9f23de4d4da9eb12\Source\Machine.Specifications\Utility\RandomExtensionMethods.cs:line 32
at Machine.Specifications.Model.Context.EstablishContext() in d:\BuildAgent-02\work\9f23de4d4da9eb12\Source\Machine.Specifications\Model\Context.cs:line 86

I feel it's something blooming obvious, but I can't quite see it. As the CompanyHomeController is the SUT, I don't quite see why I'd have to touch upon the BaseController. Should I be stubbing the latter out? If so, why?
Answer: The SetPageTitle is probably trying to access the HttpContext which is not available in the unit test and which you might need to mock. Unfortunately as you haven't shown this method it is difficult to provide more help.
Comment: You are right that it is trying to access HttpContext. Could you please explain why I need to mock this? Since everything has already been implemented, I didn't expect that I would have to mock that out since I'd have expected the "Because of = () => result = companyHomeController.Add();" to just call the method. What is missing from my understanding?
Comment: @DavidS, the HttpContext needs to be mocked in a unit test. This is populated only when you run the application. In a unit test there is no the ASP.NET pipeline which instantiates the context. In classic ASP.NET there was the static `HttpContext.Current` which was impossible to mock but in MVC it is an abstract base class which you could mock. That's why we say that ASP.NET MVC application is easier to unit test. It uses abstractions that could be mocked. The `Because of ...` indeed calls the method but your controller doesn't have an HttpContext setup which you need to do.