What is the difference between a Singleton pattern and a static class in Java?

Question: How is a singleton different from a class filled with only static fields?
Comment: Are you asking "what are the practical differences?"
Comment: i'm just curious about the general differences of the two i.e. Is there something unique about a Singleton that makes it different from a class that has all it's methods and attributes set to static?
Comment: DCL way of implementing singleton has only static field instance holding a static reference to the singleton object and then lazily instantiated in static method. In this case this Singleton implementation has only static field and methods and they are same(Not different as question asks). That's one implementation. Other can be through Enum.
Answer: Almost every time I write a static class, I end up wishing I had implemented it as a non-static class. Consider:

A non-static class can be extended. Polymorphism can save a lot of repetition.
A non-static class can implement an interface, which can come in handy when you want to separate implementation from API.

Because of these two points, non-static classes make it possible to write more reliable unit tests for items that depend on them, among other things.
A singleton pattern is only a half-step away from static classes, however. You sort of get these benefits, but if you are accessing them directly within other classes via `ClassName.Instance', you're creating an obstacle to accessing these benefits. Like ph0enix pointed out, you're much better off using a dependency injection pattern. That way, a DI framework can be told that a particular class is (or is not) a singleton. You get all the benefits of mocking, unit testing, polymorphism, and a lot more flexibility.
Comment: @nanosoft: When I said "a static class," I wasn't referring to Java's ["static nested classes"](http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html), but rather a "class filled with only static fields", as the OP was asking about. All of the statements I make here apply if you think in terms of using static methods, regardless of the nature of the class that they're in: they cannot implement interfaces or be extended. Sorry for any confusion I may have caused by saying "static class"--that's a term that's more common in other languages, but doesn't apply in Java.
Comment: In java, nested static class can extend other class(and also can be extended by other classes) and implement interfaces. check http://stackoverflow.com/a/37114702/1406510
Comment: If I'm not mistaken, Junit seems to ignore static initialization pretty severely.
Answer: Let me sum up :)
The essential difference is: The existence form of a singleton is an object, static is not. This conduced the following things:

Singleton can be extended. Static can't be.
Singleton creation may not be threadsafe if it isn't implemented properly. Static is threadsafe.
Singleton can be passed around as an object. Static can't be.
Singleton can be garbage collected. Static can't be.
Singleton is better than static class!
More here that I haven't realized yet :)

Last but not least, whenever you are going to implement a singleton, please consider to redesign your idea to not use this God object (believe me, you will tend to put all the "interesting" stuff in this class) and use a normal class named "Context" or something like that instead.
Comment: +1 for the "God Object" principle. Love it.
Comment: In java, nested static class can extend other class(and also can be extended by other classes). static nested class can be very much passed as object. It can be garbage collected as well. check http://stackoverflow.com/a/37114702/1406510
Comment: Static classes can be thread safe or not thread-safe ..
Comment: I'm hung up on the not in bullet point two, are you using it in a distributive way, or are you targeting the predicate or the dependent clause?  Are you saying  "static may be threadsafe if it isn't implemented properly"?  Or are you saying "static may be threadsafe if it is implemented properly?"  Or are you saying "static may not be threadsafe if it is implemented properly"?  Can you  clarify what you saying is different about static, maybe a code example?
Comment: this's the most concise answer <3
Answer: A singleton can be initialized lazily, for one.
Comment: Statics fields aren't really lazy loaded.  Static fields are loaded when the class is loaded by a class loader.  A singleton may be written such that the singleton instance is not initialized on class loading, but instead on the first request for the singleton instance.  Of course, the most common approach for singletons is not lazy.
Comment: @Tom Hawtin - tackline: what do you mean by that?
Answer: I think, significant thing is 'object' in object oriented programing. Except from few cases we should restrict to usage of static classes. That cases are:

When the create an object is meaningless. Like methods of java.lang.Math. We can use the class like an object. Because the behavior of Math class methods doesn't depend on the state of the objects to be created in this class.
Codes to be used jointly by more than one object method, the codes that do not reach the object's variables and are likely to be closed out can be static methods

Another important thing is singleton is extensible. Singleton can be extended. In the Math class, using final methods, the creation and extension of the object of this class has been avoided. The same is true for the java.lang.System class. However, the Runtime class is a single object, not a static method. In this case you can override the inheritance methods of the Runtime class for different purposes.
You can delay the creation of a Singleton object until it is needed (lazy loading). However, for static method classes, there is no such thing as a condition. If you reach any static member of the class, the class will be loaded into memory.
As a result, the most basic benefit to the static method class is that you do not have to create an object, but when used improperly, it will remove your code from being object-oriented.
Comment: #1 should be taken in context. Take a "meaningless" `Date.Now` call. yet 99.99% of the time using the static `Date.Now` method call makes mocking tests nearly impossible. Or rather, static methods *don't* generally allow injection and mocking.
Answer: The difference is language independent. Singleton is by definition: "Ensure a class has only one instance and provide a global point of access to it. " a class filled with only static fields is not same as singleton but perhaps in your usage scenario they provide the same functionality. But as JRL said lazy initiation is one difference.
Answer: At least you can more easily replace it by a mock or a stub for unit testing. But I am not a big fan of singletons for exactly the reason you are describing : it are global variables in disguise.
Comment: @BenoitParis - it reduces the absolute number of global variables but does not solve any of the evils associated with them.
Comment: You shouldn't have global variables in the first place. Even having static methods is not really OOP.
Comment: @D.Shawley Quite. Singletons just add more complexity whilst addressing none of the problems caused.
Comment: The cleanest way to make something a singleton (assuming server side programming) is to declare a named bean via a Spring application context.

If you set scope="singleton" then calling appContext.getBean() repeatedly returns the same instance. If you set scope="prototype" then every invocation returns a new instance. Means the code doesn't have to implement or worry getInstance(), you just get the bean.

Singleton is the default since most beans are singletons anyway.
Comment: Actually, I think having a singleton helps you reduce the number of global variables. You have one reference to an object. It could wrap all the static fields into it.
Comment: @BenoitParis Anything you can access through a Singleton is a global variable just as much as any other... it's just accessed as Singleton.getInstance().whatever() instead of another way.
Comment: @D.Shawley - My bad. Can you elaborate a bit?
Comment: @locka Any kind of dependency injection container with a singleton scope, not just Spring.
Comment: @locka Absolutely! Using dependency injection to inject singletons is the way to go provided it are either infrastructure services like database connectors,caches,...  or 'stateless' service beans in the meaning that they do not have externally visible internal state. Then the other code will not make dangerous assumptions and life is a lot simpler.
Answer: A singleton is a class with just one instance, enforced.  That class may have state (yes I know static variables hold state), not all of the member variables or methods need be static.
A variation would be a small pool of these objects, which would be impossible if all of the methods were static.
Comment: Question asks about fields, not methods.
Comment: A small pool of singleton objects?  I guess that makes sense, for  some value of "small".
Answer: A singleton class will have an instance which generally is one and only one per classloader. So it can have regular methods(non static) ones and they can be invoked on that particular instance.
While a Class with only static methods, there is really no need in creating an instance(for this reason most of the people/frameworks make these kind of Util classes abstract). You will just invoke the methods on class directly.
Answer: The first thing that comes to mind is that if you want to use a class with only static methods and attributes instead of a singleton you will have to use the static initializer to properly initialise certain attributes. Example:
class NoSingleton {
  static {
    //initialize foo with something complex that can't be done otherwise
  }
  static private foo;
}

This will then execute at class load time which is probably not what you want. You have more control over this whole shebang if you implement it as a singleton. However I think using singletons is not a good idea in any case.
Comment: I think for you to say that singletons are "not a good idea", when we don't know anything about the context that he might be using them, is a little rash.  There are no absolutes in programming, and there is almost always a use case that makes one or the other the best.  It's like telling someone the word "duck" always refers to an animal.  But context is important, since it could mean something completely different like "Duck when someone throws a show at you."  P.S. But I did not downvote you.
Answer: NOTE: The examples are in C#, as that is what I am more familiar with, but the concept should apply to Java just the same.
Ignoring the debate on when it is appropriate to use Singleton objects, one primary difference that I am aware of is that a Singleton object has an instance that you can pass around.
If you use a static class, you hard-wire yourself to a particular implementation, and there's no way to alter its behavior at run-time.
Poor design using static class:
public class MyClass
{
   public void SomeMethod(string filename)
   {
      if (File.Exists(filename))
        // do something
   }
}

Alternatively, you could have your constructor take in an instance of a particular interface instead.  In production, you could use a Singleton implementation of that interface, but in unit tests, you can simply mock the interface and alter its behavior to satisfy your needs (making it thrown some obscure exception, for example).
public class MyClass
{
   private IFileSystem m_fileSystem;

   public MyClass(IFileSystem fileSystem)
   {
      m_fileSystem = fileSystem;
   }

   public void SomeMethod(string filename)
   {
      if (m_fileSystem.FileExists(filename))
         // do something
   }
}

This is not to say that static classes are ALWAYS bad, just not a great candidate for things like file systems, database connections, and other lower layer dependencies.
Answer: One of the main advantages of singletons is that you can implement interfaces and inherit from other classes.  Sometimes you have a group of singletons that all provide similar functionality that you want to implement a common interface but are responsible for a different resource.
Comment: Nested static class can also extend another class and implement interface. http://stackoverflow.com/a/37114702/1406510
Answer: Singleton Class :
Singleton Class is class of which only single instance can exists per classloader.
Helper Class (Class with only static fields/methods) :
No instance of this class exists. Only fields and methods can be directly accessed as constants or helper methods.
These few lines from this blog describes it nicely:

Firstly the Singleton pattern is very
  useful if you want to create one
  instance of a class. For my helper
  class we don't really want to
  instantiate any copy's of the class.
  The reason why you shouldn't use a
  Singleton class is because for this
  helper class we don't use any
  variables. The singleton class would
  be useful if it contained a set of
  variables that we wanted only one set
  of and the methods used those
  variables but in our helper class we
  don't use any variables apart from the
  ones passed in (which we make final).
  For this reason I don't believe we
  want a singleton Instance because we
  do not want any variables and we don't
  want anyone instantianting this class.
  So if you don't want anyone
  instantiating the class, which is
  normally if you have some kind of
  helper/utils class then I use the what
  I call the static class, a class with
  a private constructor and only
  consists of Static methods without any
  any variables.


Study data science at university

Question: Is it a waste to study data science in university, despite the advancement of artificial intelligence and automation of analysis?
regards
Answer: Whether or not it's a waste of your time and resource significantly depends on the rigor of the course and how up to date it is with current technologies and advances in data science.
Online courses could be a great way to self-teach data science. However, it often comes with the compromise of not teaching you enough of the relevant math. While you might get away with not knowing the math for a lot of the applications you might encounter, you will most definitely be missing out crucial insights. The math matters.
Recently, many universities have been updating their applied CS related courses to the latest technologies. And universities will most likely have an emphasis on math compared to online resources. If this happens to be the case, a university course will definitely be the better choice.
In conclusion, the best choice depends on the specifics of the particular course in question and what you want to achieve by learning that material. A general answer to your question is not possible as of present, but it might be in the future; and given my personal observations of the current trend, I'd bet my money on university offered courses (which may or may not be online) rather than other online resources.
Comment: Thank you for your answer.  I studied statistics for my bachelor's degree and decided to study data science for my master's degree.  But the recent issues (such as chatgpt, etc.) that announce the automation of data science tasks, made me hesitate for this choice.

Study data science at university


Running the Cypress Test Runner Remotely

Question: Cypress has a great test runner that works really well in the local environment. Although, I haven't found a way to run something like cypress open for a remote environment. So is that a way to do this instead of using cypress run?
Comment: I have a development env running remotely, and I would like to know if there is a way to run my tests with the Test Runner from this env
Comment: What are you trying to accomplish? You could bundle it in a Docker container that you deploy remotely to run your E2E suite.
Comment: As I'm looking for something similar, could you specify whether either cypress or the browser is running on the remote? If you want to connect to a remote browser, possibly [this feature request](https://github.com/cypress-io/cypress/issues/5984) indicates that it is currently not supported. I myself was looking for the other way around as I can only run Cypress on a remote machine but still would like to see the test panel in my local browser somehow.
Answer: If you run a local Xserver, you can export the DISPLAY from the remote machine to your local. In my experience it's not very fast, but it's usable.
This is blog post is specific to WSL, but concept (and most of the commands) are the same https://dev.to/nickymeuleman/using-graphical-user-interfaces-like-cypress-in-wsl2-249j


Clagging in Diablo 2

Question: When dueling in diablo 2, I see a lot of paladins talking about "clagging." How is "clagging" done in diablo 2? And why does it work?
Comment: character lagging maybe?
Comment: @Resorath It's actually c-lagging or charge-lagging. It's an exploitation on the paladin skill. I am not exactly sure how it works though.
Answer: "Clagging" refers to a glitch called "charge lagging".
What happens is this:
A Paladin moves a few screens away, turns on Vigor aura, and then uses Charge to move very fast. This causes your character not to sync properly with the game/server, because the character is moving faster then the server can update. This results in the Paladin seemingly jump/teleport (without the Teleport skill or Enigma Runeword) from place to place.
While the Paladin is desynced from the server, they can also cast Blessed hammers that are invisible to other players and/or not appear where they seem to be (the Paladin's position is not updated correctly for other players. E.g., The Paladin is actually behind a wall, but seems to be in front of your character, you shoot at him the hit animation happens but the Paladin loses no life), giving the Paladin an unfair advantage.
There is a similar glitch with Barbarians and the Increase Speed and Frenzy skill.
See it in action.

Clagging in Diablo 2


Fail-Safe Network With 2nd Switch?

Question: Is it possible to set up the same VLANs on two different switches with same IPs, but different MACs on dual port network cards? In case switch 1 is down or needs maintenance I would like switch 2 to take over the communication and vice versa as I do not want the entire network of devices to have no connectivity and make the network highly available. The whole purpose of my network is replicas and shards of the same app data distributed to make it fail safe, but the network is not fail salve in my engineering plan, yet. Best method to achieve assuming both switches are not connected, but each server is connected to both switches at the same time from different ports on their network cards? Switch used, if matters - Quanta LB6M.
Comment: Yes, that's very common. There's a bit more to a redundant network though, especially a redundant core layer. Host configurations are off-topic here, however. You could try on [sf] for an on-topic server setup (check their [help page](https://serverfault.com/help/on-topic) first), or on [su] otherwise.
Comment: OK. Thanks a lot! Thought it is here - the place to ask.
Comment: Posted on serverfault as suggested. Let's see what other pros could suggest.
https://serverfault.com/questions/1065195/vlan-network-redundancy-with-same-2nd-switch
It is explained in more details in that question.
Answer: A good way to narrow your options (as @Zac67 alludes) is to decide whether your application / servers are able to be aware of the servers being multi-homed, e.g. with each server having multiple IP addresses; or if that is unsupported by the use-case.
Link Aggregation is the simplest way to provide redundant downlinks to servers and can reduce outages (MTBF) and make recovery much faster (MTTR).  This doesn't require any application-awareness.
I suggest you read about MLAG https://en.wikipedia.org/wiki/Multi-chassis_link_aggregation_group which I think is supported by your switch.
Also, consider more featureful switches as you invest in network redundancy.  At small scale, white box switches are a terrible value proposition compared to featureful, well-supported major-brand switches.
Comment: Thank you! Will check what switches I can get. Any you could recommend?
Comment: With a small setup (just two switches, non-fat tree, ...), you'd likely want an active/passive failover - with LAG, traffic is distributed across links which may not be desired (might overstress the inter-switch links), and a passive standby NIC teaming might be more desirable (and also doesn't require MLAG).
Comment: Thank you, @Zac67. I am still researching options as it is the first time I will be doing this kind of network redundancy.

Fail-Safe Network With 2nd Switch?


Why have treasury prices risen despite increasing interest rates since the Great Recession?

Question: ETFs that track treasuries have risen despite the fact that the global economy has stabilized since 2008 and interest rates have risen (from near 0 to ~1.5%) My (very simplistic) understanding of treasury prices is that as interest rates rise, treasury bond prices decline. If this is the case, what might have contributed to the rise of an ETF like TLT (which tracks treasury prices)?
Comment: It's a small technicality but the yield on a treasuries rises and falls because of the price change of the treasury, not vice versa.
Answer: I'm not sure where you're getting your information. I used Yahoo Finance to plot the price of TLT (your long-term treasury bond ETF) against the yield on 30-year treasury bonds. The two charts are nearly perfect mirror images of each other, showing that as interest rates rise, the price of the bond ETF falls, and vice versa.
So, it looks like it's not the case that treasury prices have risen despite increasing interest rates.
Comment: Wasn't the federal interest rate 0% in 2008? And now it's not 0%, so didn't it rise? (Please forgive me if I'm misunderstanding something)
Comment: @user3586940 Well, the federal funds rate is a very short-term rate (overnight), while TLT holds long-term bonds (20 to 30 years). So it's no surprise that the yield of TLT doesn't reflect the federal funds rate. So, I decided to look at a short-term treasury bond fund, SHV. The yield of SHV *does* reflect the federal funds rate pretty well. However, the *price* of SHV essentially remains constant instead of reflecting the federal funds rate; this is because short-term bond prices are less sensitive to interest rate changes than long-term bond prices are.
Comment: I gave you best answer and upvoted, but it is your awesome comment that answered my question. I would add it to the answer.


Why banned from asking question?

Question: I don't understand why I should be banned from asking question on English Language & Usage. May you remove the block, please.
Answer: It's not possible for staff or moderators to manually remove an automatic block. There's a lot of information about question banning on Meta.SE. Users who post a lot of poor questions will usually get a notification warning them about post quality. It appears you haven't had one of those — that's unusual and a little unfortunate.
The only way of reversing a question ban is to improve your existing questions to get them upvoted. When the system next examines them, it may decide to remove the ban, or perhaps to allow a limited number of questions per week. You might get one question every six months.
You can find a list of questions in your profile and at the bottom of that list a link to deleted questions. Of your ten questions, half are either downvoted, closed or deleted
— or even downvoted, closed and deleted.
When you edit your questions to improve them (and vote to undelete them if necessary), they will be bumped on the front page and will gain more attention. This can be good! But the extra attention could also mean you get more downvotes if you don't improve them enough or rectify their on-topic-ness. You may want to re-compose the questions offline and then edit them when you're completely happy.
Comment: Stack Exchange has several mechanisms to prevent users with unconstructive motivations from causing harm to the communities hosted. Blocking those who continually post poor quality questions is one of them. Blaming a Q-ban on "argumentative trolls" (which can be flagged for moderator attention and removed, and has nothing to do with the contents of one's own posts) is ignoring the cause, and will not result in a change of effect. @Sapiens
Comment: @Sapiens If, as Andrew Leach suggests, you haven't received notifications, you might have been affected by the banning of someone else on your IP address. The [Meta.SE post](https://meta.stackexchange.com/questions/86997/what-can-i-do-when-getting-we-are-no-longer-accepting-questions-answers-from-th) Andrew Leach linked to says, "If you really, really think the ban is an error, then email the team directly using the "contact us" link provided at the bottom of every page." Give it a try. Let them know you haven't received any warnings (if that was the case) before being banned.
Comment: "The only way of reversing a question ban is to improve your existing questions to get them upvoted."

So, how reasonable is that?

As we all know, many sites are filled with argumentative trolls, who obtain their satisfaction by destroying for others. It is unfortunate that SE does not have mechanisms to avoid such nonsense.

I am very sorry, but I will not do a bit more to avoid the ban.
Comment: @Nij I did not blame argumentative trolls. Rather, I expressed interest in such mechanisms as you are providing one example of.

Why banned from asking question?


Filtration related to stopping time of Brownian Motion: Paths are measurable?

Question: Given a stopping time $T:\Omega\rightarrow \mathbb{R}$ there is a related $\sigma$-algebra used in Mörters and Peres book, Brownian Motion defined on p. 42 as
$$\mathcal{F}^+(T) = \{A\in \mathcal{A}: A\cap \{T\leq t\}\in \mathcal{F}^+(t)\text{ for all $t\geq 0$}\}$$
where $\mathcal{A}$ is a $\sigma$-algebra and $\mathcal{F}^+(t)$ is a filtration related to Brownian motion via
$$\mathcal{F}^+(t) = \bigcap_{s>t}\sigma(B(\tau):0\leq \tau\leq s).$$
Now on p. 43 they claim that $\{B(t): t\leq T\}$ is $\mathcal{F}^+(T)$ measurable. However I'm confused as to what this means. $\mathcal{F}^+(T)$ is clearly a $\sigma$-algebra on $\Omega$ while $\{B(t):t\leq T\}$ is for each $\omega\in \Omega$ a subset of $\mathbb{R}$? Could someone clarify this for me?
Answer: Measurability is defined in terms of preimages. In probability we often use more compact notation for the events that we consider, both because it aligns with our intuition and because it alleviates the notation.
We have for example
\begin{align*} \sigma ( B(\tau) : 0 \leq \tau \leq s) &=  \sigma (\lbrace B(\tau) \in B \rbrace: 0\leq \tau \leq s, B\in\mathcal{B}(\mathbb{R})) \\
&= \sigma (B(\tau)^{-1}(B):0\leq \tau \leq s, B \in \mathcal{B}(\mathbb{R})) \end{align*}
and now it is more clear that the $\sigma$-algebra is actually generated by sets in $\Omega$.
Regarding the set $\lbrace B(t):t\leq T\rbrace$ it seems to me that this is defined on the path space in the same way that the process $\lbrace B(t):t\geq 0\rbrace$ would be. So $B(\cdot,\omega)$ is considered a mapping from $\Omega$ to the space of continuous functions $C([0,\infty),\mathbb{R}) $.


Why MOSFET switching load effect gate voltage?

Question: I use this Chinese MOSFET module to drive mini DC pump using control signal from Arduino (simply on off with blibk sketch)

I know that we need to add flywheel diode but it this case unfortunately, it's not.
The problem is when the pump switch on and off there are something happen seem like voltage-spike with Arduino digital output and also effect 5V pin via internal- input eds diode of the Arduino.
My question is what actually happen and how? I think gate is isolated from other pin so I'm confusing right now. Small capacitance between those pin shouldn't be the problem.
Comment: Sounds like poor decoupling. Your schematic shows none. Is that the case?
Answer: There are a few issues with that board, but luckily enough you can cure them rather painless.
1. You really must fit a freewheeling diode across the output posts.
Best location is also the easiest, just solder it on the output terminal strip pins bottomside your pcb.
This will prevent load and load wiring inductance to push your MOSFET into avalanche at every turn-off.
Virtually any diode rated at least twice your supply and pump current would do, 1N4002 for instance or anything you have handy. Contrary to common belief a fast recovery is not really needed for "seldom" on/off switching. It could be useful for PWM driving only.
Avalanche is usually not too bad for the MOSFET itself if energy is below allowed Eas, but in turn may generate high voltage (over 100V)  high dv/dt pulses which can easily be conducted around doing weird things to your Arduino controller.
2. You must replace your IRF520 MOSFET with one suitable do be driven by Arduino 5V output.
IRF520 should be driven at least 10V for reliabily turn on, fit an IRL520 instead.
IRF may sometimes seem to working fine but it will, at best, heat more than what's due. But at worst it may only partially drive your pump and/or work today with your very specimen but not if you try do build a second one another day.
3. Not really a must but would help a lot -and I would definitely do- add some bypass capacitance across power Vcc pins.
Again solder  bottomside just across terminal strip pins, value somehow depends on load but it is not critical, a few microfarads alluminium should do.
This would create a short loop for both on and off transient currents reducing the chance to have noise around in the system and hence weird erratic controller behaviour.
4. Take care of power and controller current flows. (Credits to Kartman)
Try to keep them separated, draw the schematic of Arduino, switching module, load and power supply(ies) keeping in mind that every line you draw is not an ideal wire with zero voltage drop, but a real one with its own resistance and inductance messing up the things when shared by a fast, heavy power current and a tiny control signal.
And now last but not least:
0. Try not to buy poor enginered cheap boards.
We have come to a point where virtually nothing of the original board is left as good.
Comment: I like "0. Try not to buy poor enginered cheap boards." Yep, could not agree more.
Answer: The gate is isolated but just barely, after all the insulating oxide layer might only be a few atoms thick. Sufficiently high voltages will degrade or blow the gate oxide and there are still parasitic capacitances such as that between drain-gate through which high frequency currents on the drain can travel through to inject itself into the gate.
It doesn't matter if the capacitance is very small if the frequency or rising/falling edge is very very high, and it will be because MOSFETs can switch on and off very very quickly.
Comment: Transients can flow via the 0V wiring - you need to understand where the current is flowing and ensure your wiring makes it flow where it should. If the load current is flowing back through the Arduino, you'll most likely have problems. Current flows in a loop. Understand where the loop is.
Answer:
I know that we need to add flywheel diode but it this case unfortunately, it's not.

Without the diode, when the FET turns off, the energy stored in the inductive load means the current doesn't stop immediately. It causes drain voltage to rise until something breaks. This will usually be the MOSFET going into avalanche mode. Here the simulator predicts a nice >100V spike.

If this goes on at each PWM cycle, the MOSFET will overheat and burn very quickly. Also the ringing and voltage spiking can destroy the gate oxide insulator, which then internally shorts gate to source and/or drain, which will also destroys whatever drives the MOSFET if it is not protected against a sudden influx of high voltage on its output. Notice drain voltage the ringing reaches 40 volts here, with only a 12V supply, so that's pretty nasty. This will also create tons of electromagnetic noise, which can do funny things like make the micro crash and reboot, or even latch-up, overheat and burn if it gets coupled into an input.
So, add the diode. Pick one that switches fast enough for your PWM frequency. If you don't use PWM, just pick a diode that can handle the current. And it would be preferable to add a gate resistor to slow down the switching.

Note IRF520 is not specified to turn fully on with Vgs=5V, so it may turn on just a bit, or have a much higher RdsON than the datasheet value which is specified at Vgs=10V. Then it will overheat and burn. Fortunately it's probably a counterfeit IRF520 so maybe you got a low voltage FET instead, who knows...
Comment: This module is just piece of miserable engineering. I buy this to drive heater 12V 3A and it become heater its self.
After that ,my colleage bring this module to me again. it seem fine to drive small pump with small current until these doom happen.
Comment: Yes, if it is genuine IRF520 it will not work with 5V gate drive... too bad for arduino lol
Answer: To reduce this effect I suggest you to slow down the MOSFET command by:

Adding a 10 nF capacitor or more between the Gate and the Source, that is, in parallel to the 1 k resistor.

Adding a 1 k resistor between SIG and the GATE.

The voltage spikes amplitude depends a lot on where you put the negative clip of the probe of your scope.
To correctly measure the voltage spikes amplitude on the +5 V power supply of the microcontroller, solder a short wire on the GND signal that is near the +5 Volt pin you are probing.
If you can't solder the short wire, than look at this picture:
https://techweb.rohm.com/upload/2017/04/20A_graf03.jpg


Why do some minerals prefer diamond structures while others prefer wurtzite structures?

Question: Carbon can exist as both diamond and wurtzite structures (lonsdaleite), but diamonds are much more common than lonsdaleites in nature. Some materials like GaN preferentially form wurtzite structures. Why do minerals have such preference? Both diamond structure and wurtzite structure have similar compactness (like FCC and HCP). Moreover, in both diamond and wurtzite structures each atom is connected with four atoms in a tetrahedral symmetry, which means the local environment of atoms should be nearly the same (which is unlike FCC and HCP).
Answer: Different quantum orbital structures of elements lead to different bonding geometries. These in turn produce different crystal structures. Each element is unique when it comes to these orbital structures so the preferred stable configuration of different minerals is also unique.


Calculate the Riemann's sum

Question: Calculate the Riemann's sum of  $\:\: \displaystyle \mathbf{f(x)=\frac{1}{x+2}}\:\:$ in $\:\:\mathbf{[1,2]} \:\:$ using $\mathbf{P \in \mathbf{[1,2]}} \:\:$ uniform partition.
I need help to finished the sum, because $\left(with \:\: \mathbf{x_k=1 + hk},
 \displaystyle \mathbf{h=\frac{1}{n}} \right)$
$$\lim_{n \rightarrow \infty} \sum_{k=1}^{n} \frac{1}{1+hk+2}h=\lim_{n \rightarrow \infty} \sum_{k=1}^{n} \frac{1}{3n+k}$$
Exists other method with uniform P? I don't know how to resolve this sum
Comment: I think you've done everything you can. There is no closed form for such a sum. At least none of the answerers [here](https://math.stackexchange.com/q/73550/11619) would know of one. Quite the opposite actually. Our ability to calculate this integral by other means is the tool for finding this limit. My guess is that whoever gave this exercise either wanted you to do just this or, had in mind a fixed value of $n$, and just wanted to make you form a Riemann sum, and calculate it to approximate the integral.
Answer: I'm not sure if this is what you are expected to do here but
$$ \sum_{k=1}^{n} \frac{1}{3n+k}=\sum_{j=3n+1}^{4n} \frac{1}{j}=H(4n)-H(3n)$$
where $H(n)$ is the Harmonic number. Then you can use  the expansion $H(n)=\log n + \gamma + O(1/n)$.
(Though you normally work the other way round, you use the integral to prove the expansion).

Calculate the Riemann's sum


Why do we plot observed probability vs predicted probability when calibrating a logistic prediction model?

Question: I'm trying to wrap my head around why predicted probability is plotted on the x-axis and observed probability on the y-axis, and not the other way around.
Comment: Convention only: the (or rather one) convention is, I take it, that the observed response or outcome belongs on the $y$ axis; therefore anything else belongs on the $x$ axis. I've seen fitted on $y$ versus observed on $x$ too.
Comment: Possible duplicate: http://stats.stackexchange.com/questions/123938/how-to-determine-which-variable-goes-on-the-x-y-axes-in-a-scatterplot
Comment: I don't think they are duplicates. The linked question deals with scatter plots in general, while this question deals with a predicted versus observed quantity.
Comment: A perhaps related point is that residuals are conventionally defined as observed $-$ predicted or fitted, so points with positive residuals plot above the observed $=$ predicted line. I'd call that a very strong convention, while noting that Gauss defined residuals the other way round and that the convention is immaterial for sum of squared residuals or sum of their absolute values and so forth.
Comment: There seems to be a use for calculating fitting statistics that should be done regressing the OP (predicted on x-axis) explained in a  [paper](https://www.researchgate.net/publication/230692926_How_to_Evaluate_Models_Observed_vs_Predicted_or_Predicted_vs_Observed)
They argue that for example you should not use the root mean square error (RMSE) for PO to show model performance.

For visual explanation for me it is matter of personal preference but to get fitting statistics it has to be evaluated on OP  (or you have to adapt the measures) Although r^2 will remain the same.
Answer: We're used to thinking of the response variable on the $Y$ axis.  The observed probabilities are responses in that sense.
The explanatory / predictor variables go (by convention, if you like) on the $X$ axis.  The predicted probabilities are a [non-stochastic] function of the explanatory / predictor variables.
The mapping between a standard plot, like a scatterplot, and the plot you describe is straightforward to me.


Update an email in an active journey

Question: I have an active journey with a sent email step in it.
If I make changes in the email attached to this journey, will the email get updates automatically, or do I need to make a new draft/version of the journey for it to get updated?
Answer: No, it doesn't get updated automatically, but you can manually publish the changes to the triggered send via Email Studio as described here: Triggered Email Change Process
The triggered send for a journey's email send activity can be found in Email Studio -> Interactions  under Messages -> Email -> Journey Builder Sends -> [Journey Name] -> [Version X] -> [Email Send Activity Name]
Edit: Since the January '17 release, it should also be possible from within Journey Builder. Just got to the Details and Configuration dialog, perform changes and click done. For further details please check out the following documentation page: Update an Email in a Running Journey
Comment: Thanks, I wasn't aware that its just "triggered Sends" journey builder are using.

Update an email in an active journey


Can I play FIFA 15 with my friend who has android phone?

Question: My friend plays FIFA 15 on Android while I have the game on PS4. Am I able to play FIFA online with him?
Answer: FIFA 2015 for PS4 and FIFA 15 Ultimate Team for iOS/Android are technically different games and do not support online play with each other.  The same goes for FIFA 2016 and FIFA 16 Ultimate Team.
Answer: No.
Playing FIFA 15 across different types of devices is not supported. Each platform has an individual online gaming system. You can neither play PC to PS4 or XBox (link for FIFA 16), or those two with each other.
I cannot find any official resources to back this up, but it stands to reason that playing from phone, which has fundamentally different controls, to one of the full fledged platforms will not work either.
However, you can use the Android software Remote Play as shown in this video to use your Android device to remote control a PS4 and play like that.


Which came first: The Chicken or the Egg?

Question: Has there been any serious scientific inquiries into answering this age old question?
Comment: -1 as the attempts at answers show this question needs to be much more constrained to be answerable.
Comment: This question is invalid but it's such a known question that it's worth putting forth, if only to give an opportunity to point out why it's invalid.
Comment: Perhaps the question can be better worded as: "Are there any scientific inquiries to the Chicken or the Egg question?"
Comment: This question is more a philosophical question. The chicken or egg dilemma is not really framed in the proper way according to our understanding of biology today, it's more than 2000 years old.
Comment: Since the egg carries new mutations and recombination in each generation, and grow (usually) with the same DNA to the adult chicken/cock, we may assume the egg always comes first. In other words, the theropod lays an egg a little more avian than itself. It IS a philosophical question that, as many others, has perfectly viable biological approaches. I vote to reopen it. We should stop being so closed to "strange" questions.
Answer: Most theories about origin of life say that unicellular organisms were first and multicellularity (like chicken) evolved much later, so in that meaning egg (single cell)* was first. Also, almost all chicken ancestors lay eggs (primitive birds, non-avian reptiles, amphibians, fishes and so on...) so eggs existed much earlier than chickens.
*in the meaning of zygote. The development of chicken embryo starts in hen's oviducts, so it's not a single cell at the moment when hen lays it (Gilbert, 2000).
Comment: @Hermann_Ingjaldsson Thanks, I've fixed it. Is it better now?
Answer: This is a classic case of "it depends on the context."

The Egg: As Marta Cz-C points out, the amniotic eggs that chickens lay were inherited virtually unmodified from their theropod dinosaur ancestors. So when considering the type of eggs, the egg came first.
The Chicken: From a systematic perspective, you must first have an animal that you would call a chicken before it can lay a "chicken" egg. So considering the animal, the chicken.
Answer: The question makes the false assumption that chicken and eggs are different life forms.
A life form at stage x is not a different life form than that very life form at stage y.
You might as well ask of which came first, a 7 year old kid or an 8 year old kid.
But they are the same thing and therefore this question is invalid.
Answer: Dunno about any serious scientific inquiries into the answer but I always thought the answer is egg. At some point the modern chicken has come into being as the progeny of two pre-modern chickens, however it had to be an egg before it could be a chicken and its parents couldn't have been modern chickens.
However, all that presupposes that you can draw a line in the evolutionary history of the modern (extant) chicken and say this is modern and what goes before is not. I dunno if that really can be done.
Edit: came across this guardian article: http://www.guardian.co.uk/science/2006/may/26/uknews

"Whether chicken eggs preceded chickens hinges on the nature of chicken eggs," said panel member and philosopher of science David Papineau at King's College London.
"I would argue it's a chicken egg if it has a chicken in it. If a kangaroo laid an egg from which an ostrich hatched, that would surely be an ostrich egg, not a kangaroo egg. By this reasoning, the first chicken did indeed come from a chicken egg, even though that egg didn't come from chickens."

And from Prof. Brookfield of the University of Nottingham:

The first chicken must have differed from its parents by some genetic change, perhaps a very subtle one, but one which caused this bird to be the first ever to fulfil our criteria for truly being a chicken; Thus the living organism inside the eggshell would have had the same DNA as the chicken that it would develop into, and thus would itself be a member of the species of chicken
Comment: Evolution does not happen over the course of a generation. You are confounding evolution of a species with mutations of a single individual.
Comment: That's why I wrote I don't think its possible to draw a line in the evolutionary history and say this is an extant version of a chicken and the previous generation is not.


is it necessay to get a reference letter from the place i work to re enter japan while i am on working visa?

Question: is it necessary to get a reference letter from the place I work to re enter japan while i am on working visa? cause Iam going to my home Country.
Comment: You are in Japan on a working visa and you're asking about going out of the country ('home') for a short period?
Comment: I've answered your question, though it might be better to ask such questions on the [Expatriates Stack Exchange](https://expatriates.stackexchange.com/questions/tagged/japan).
Comment: @John The answer I had in mind but I was waiting for OP's clarification that that was actually their situation ;) For the record, the question is absolutely fine here because it is about travelling but it might be borderline off-topic at Expats because it's not about the everyday life there.
Comment: @Jan True. Maybe you're right! :-)
Answer: As of July 2012, if you wish to leave Japan for a under a year, you can pick up a "Special Re-entry Permit" at the airport just before the immigration desks:

Simply fill in the departure part, and present it with your passport and residence card at the immigration desk. The immigration officer will staple the "arrival" part to your passport, and you should fill this in for when you re-enter Japan.
See here for more information, and any conditions, etc.
Note that there are other images floating around for "special re-entry permit", but this is the only card I've ever actually seen at the airport.
Answer: According to http://www.immi-moj.go.jp/english/tetuduki/kanri/shyorui/06.html, if you are applying personally only the following documents are required:

Application form
Passport and residence card (or alien registration certificate deemed equivalent to a residence card)


Create a batch file or shortcut to PuTTY (ssh) that opens a session and runs a command

Question: I often find myself opening an SSH session to run the same single command. I have everything setup to login without entering a password (Via SSH Key-Based Auth), so I wondered if there was a way to create a shortcut or a batch file in Windows that would load PuTTY or a similar program, then fire off that command (and likely exit if result is good).
Answer: Use the commandline PuTTY version plink.exe to initate a SSH connection to a host of choice. Use the -ssh switch to connect with SSH. With the -m switch you can include a command file:
plink.exe -ssh host1 -m C:\path\to\commands.txt

You can download plink.exe from here.
Last step would be to create a shortcut including plink.exe with the desired parameters.
Check out the Plink documentation for other various parameters:
Plink.exe documentation
Comment: No need to use `-m` switch with Plink, as it allow to specify command directly on its command-line, see [my answer](https://superuser.com/a/1278446/213663).
Comment: @FreeSoftwareServers There's no difference to PuTTY in this respect. You can do `plink site command` the same way as with PuTTY (except for `command`). Plink and PuTTY has basically the same set of command-line options.
Comment: I am choosing this answer as I prefer using `-ssh host1` which relates to putty Profile vs `user@host`
Answer: To automate a command execution, use Plink (from PuTTY package), not PuTTY itself.
Plink accepts a command on its command line:
plink.exe user@host command

If you want to keep using PuTTY, you can use -m switch to specify a command file (Plink supports the -m switch too).
Answer: You can use putty configurations to achieve this.
Load putty and configure your session.
Enter the remote command that you'd like to run here:

Then, before clicking "Open", go back to the "Session" tab (at the top), and save your configuration.
Now, create a shortcut to putty.exe, adding the -load flag, for example:
%PATH_TO_PUTTY%\putty.exe -load my_config

Now, you can just click on the shortcut and it will load your session, executing your command.
Comment: Looks awesome, ill test tomorrow, i suppose i will just execute a script and it can end the session based on results of script
Comment: Yes, the session will end when the command terminates. If you'd like PuTTY to hang around once done (e.g: to inspect the output), then set "_Close window on exit_" in the "_Session_" tab.
Answer: If you're using Windows 10 or higher, you might be interested to know that Microsoft has a beta of OpenSSH, both the client and the server. You can install OpenSSH with Windows Features as below or download the portable version from GitHub.

To install the OpenSSH [client]:

Open Settings, select Apps, then select Optional Features.
Scan the list to see if the OpenSSH is already installed. If not, at the top of the page, select Add a feature, then:

Find OpenSSH Client, then select Install
[…server installation, if needed…]

Once setup completes, return to Apps and Optional Features and confirm OpenSSH is listed.
[…server configuration, if needed…]

After this, you should be able to use ssh like you would on a Unix-like system:
C:\WINDOWS\system32>ssh user@host "ls -l ~"

You should only need the server running on machines you log in to and only need the client on machines you log in from. Correspondingly, if you log into one machine as a proxy to hop into another one, that middle machine will need both.
Comment: Thats really cool to know, but I love SuperPuTTY. I will keep an eye on Windows OpenSSH as well.
Answer: Here is the script I made to hopefully save some people hours of syntax and man page research.

SingleIP, IP Range, or IPList file
Script name to run on the IP/range (actual Unix sh/ksh type script)
Optionally do nmap scan for port 22 open (i.e. subnet with some non-Linux machines)

want to avoid IPs putty cannot connect to, avoiding script being able to continue properly

Optionally run pscp command to autocache the host key (PuTTY does not do this automatically)

This batch assumes:

You have the full PuTTY package and SSH key are installed in C:\Program Files\PuTTY\
Batch scripts and IPlist files are installed in C:\Program Files\PuTTY\scripts\
The nmap and PuTTY working directories are in your command path

This is mostly useful for having a single script (such as updating an SSL certificate) across a range of machines.
Here is the complete batch file:
@ECHO OFF

rem  You must modify the CACHEKEY and SCRIPT section to reflect your SSH key location

set IPFILE=IPList_temp.txt
set runagain=n
set OPTION=1
set RANGE=
set IP=
set SCAN=n
set KEYCACHE=n

:OPTION
CLS
ECHO (Working directory is set to C:\Program Files\PuTTY\scripts\)
ECHO.
ECHO 1. Single IP
ECHO 2. IP list file
ECHO 3. IP Range
ECHO.
set /p OPTION="Choose IP type:"
IF %OPTION%==3 GOTO IPRANGE
IF %OPTION%==2 GOTO IPLIST
IF %OPTION%==1 GOTO SINGLEIP
echo Please select a valid option
GOTO OPTION

:IPRANGE
ECHO Enter the IP range(s) as in the following example. Use a space between multiple ranges:
ECHO       i.e. "10.21.0.15-99 10.21.1.15-100"
set /p RANGE=Enter Range:
echo %RANGE% > %IPFILE%
GOTO SCRIPTNAME

:SINGLEIP
set /p IP=Enter IP:
echo %IP% > %IPFILE%
GOTO SCRIPTNAME

:IPLIST
set /p IP=Enter IPList filename:
copy /Y %IP% %IPFILE%
GOTO SCRIPTNAME

:SCRIPTNAME
set /p SCRIPT=Enter script name:
if not exist %SCRIPT% (
echo filename does not exist!
GOTO SCRIPTNAME )

ECHO.
set /p SCAN=Do Nmap scan first? (recommended):
if %SCAN%==n GOTO :RUNCACHE

rem Check whether IP type is "range" as nmap cannot read an IP range from file and must be type directly in nmap command
IF %OPTION%==3 GOTO NMAPRANGE
:NMAP
echo Scanning IPs for port 22 open...
nmap --open -n -p22 -iL %IPFILE% -oG - | findstr /E Up > nmap_temp.txt
GOTO AFTERNMAP

:NMAPRANGE
echo Scanning IPs for port 22 open...
nmap --open -n -p22 %RANGE% -oG - | findstr /E Up > nmap_temp.txt

:AFTERNMAP
echo DONE
rem     nmap formatting is not correct, the following removes extra info
for /f "tokens=2" %%A in (nmap_temp.txt) do echo %%A >> nmap_temp2.txt
rem remove hidden space at end of IP (requires "repl" be in the batch file directory)
type "nmap_temp2.txt" | repl " " "" > %IPFILE%

:RUNCACHE
set /p KEYCACHE=Scan and cache SSH key (y/n) ?
if %KEYCACHE%==n GOTO SCRIPT

:CACHEKEY
rem Run through all IPs to cache the SSH Host Key if not already cached
for /F "tokens=*" %%A in (%IPFILE%) do ( echo y | "C:\Program Files\PuTTY\pscp.exe" -l root -i "C:\Program Files\PuTTY\SSH.ppk" -touch %%A:/tmp/test )

:SCRIPT
for /F "tokens=1" %%A in (%IPFILE%) do ( "C:\Program Files\PuTTY\putty.exe" -ssh %%A -t -l root -i "C:\Program Files\PuTTY\SSH.ppk" -m "C:\Program Files\PuTTY\scripts\%SCRIPT%" )
if exist nmap_temp.txt (del nmap_temp.txt)
if exist nmap_temp2.txt (del nmap_temp2.txt)
set /p runagain="Press Enter to Finish or y to rerun"
if %runagain%==y GOTO OPTION

Comment: batch contents pasted
Comment: Link only answers are frowned upon, what if your site goes down? If you want to contribute, please share the script here. Your welcome to post a source/link to the site along with the code here, but answers should be self-contained and not require following links.
Comment: Do not *"autocache"* a host key. Verifying host key is an integral part of securing your SSH session. PuTTY (and its tools) do not ask you for the host key for fun or to harass you. It has a reason! + You also should not store user data (`SSH.ppk` and the script`) to `Program Files` folder.
Comment: can you recommend how to run a script across multiple IPs without it?
a) this is not meant for a typical user desktop, more for an admin server where security is more who has access to the server
b) what exactly IS the security risk? Caching the host key is optional and should only be done once across the range. If you run the script again without caching the key you will still see and host key changes and the script will not continue on...
Comment: ......In agreement on the key thou. I point to a shared folder on our NAS where the shared folder lives, which only I have access to. I just picked a path since other users will be different
Answer: You can also look at software such as mRemoteNG, MOBAxTerm or SecureCRT which will manage your SSH connections for you, this also links with the saved PuTTY sessions so you can apply a template to the session.
Answer: This is the final "CMD" which I can just save on my FileServer and create a shortcut on my Desktop.
::FreeSoftwareServers
::Automated Opening of SSH Tunnel & Execute CMD on Remote Host
::https://superuser.com/questions/1278434/create-a-batch-file-or-shortcut-to-putty-ssh-that-opens-a-session-and-runs-a-c

set puttydir="C:\Program Files\PuTTY"
set exe=plink.exe
::Profile must exist in PuTTY
set remotehost=FileServer
set remotecmd="chmod 777 /mnt/mdadm/torrents -R"

cd %puttydir%

%exe% %remotehost% %remotecmd%

::Test First Manually in CMD Prompt
::Note Remote Host does NOT have access to BashRC Alias's
::start "C:\Program Files\PuTTY\" plink.exe -ssh FileServer touch /tmp/testfile
::start "C:\Program Files\PuTTY\" plink.exe -ssh FileServer ~/script.sh


Type Theory Lean 3 to Lean 4

Question: I'm aware of Lean's type theory. Did the type theory of lean change at all as we moved to Lean 4? Are there any references to this?
Answer: As already commented by Sebastian Ullrich, there are a few small changes to the Lean 4 kernel, detailed in his PhD thesis.  Now, that it is done (and has been for a few months), I want to make sure it gets the attention it deserves.  The details on the kernel are in Section 3.2.
Comment: @AlexByard I'm not sure I've ever recommended one read a thesis, and TBH  I haven't read Sebastian's.  That being said, it looks, from the bits I've skimmed, well organized, so at least skimming it would give you a lot of information.
Comment: Thank you, Jason. Would you recommend I read his entire thesis?
Answer: Some things changed but the type theory stayed exactly the same, so e.g. https://github.com/digama0/lean-type-theory/releases/tag/v1.0 is still a valid reference (edit: apparently this is not completely correct -- see Sebastian's comment below)
Comment: It is not exactly the same, the major additions are primitive projections, eta for structures, and primitive mutual inductive types. My PhD thesis, which should be available some time next month, gives more details.
Comment: @SebastianUllrich Given that Kevin's answer is slightly wrong, it wouldn't be bad for you to make your own short answer with what you just said.  It also wouldn't hurt to add a line about if the changes are conservative (in that you can still prove the same theorems) and if there is an automatic way to translate Lean 3 kernel-level proofs to Lean 4 (which I assume there is given the early work on the mathlib port which translated the kernel-level proofs).
Comment: @SebastianUllrich How can I read your thesis when it is complete? Are these the only additions that were made? And how would these affect me working in Lean?

Type Theory Lean 3 to Lean 4


How can I waterproof wall sheathing along concrete steps?

Question: kick board with nothing between it and concrete is rotting. What can I do?
Comment: Any gap at all between the concrete and the sheathing? You're going to need to pull the j-channel along the bottom, so go ahead and do it.
Comment: J channel has been removed. Contractor poured steps right against the sheathing, no gap. Just unsure on what steps to take after the fact. Cannot believe what a easy and cheap thing to do prior as to just add a simple barrier.
Comment: FYI, this below a sliding patio door, the wood you see nailed to house sheathing which does a have a barrier, so hopefully
Answer: Well, you aren't going to keep all the water out. The builder should've applied a water barrier before pouring the concrete. You'll have to decide whether the sheathing is degraded enough that you need to replace it. Here's what I'd do (after letting everything dry out well):

Procure some flexible waterproof membrane such as ice and water shield or window flashing tape. It should be gummy on the back side so it bonds to itself and seals around fasteners.
Apply it to the sheathing along the concrete, tight to the joint. Use staples along the top and wherever needed to hold it securely to the sheathing. It should run up the wall at least 6" or whatever space is available.
Caulk the membrane/concrete joint with a high-quality caulk. Silicone is ok. Latex is not. Urethane is better. Create a substantial, coved bead, but try to keep it small enough that it'll be hidden under the j-channel. Use masking tape on the concrete 1/2" away from the sheathing if you like.
Reinstall your siding.
Comment: Thank you Isherwood. The wood is pretty soft where it meets the concrete. My concern is I'm assuming it's very soft behind the step where I can't see it and not sure if or how long it will take to dry out. The problem with trying to replace the wood is that the concrete abuts right next to the sheathing, so it doesn't leave any room to try and get the old sheathing out. I would prefer to replace it, but don't know if that's feasible. Maybe since it's exposed now it will dry in time as long as I can keep the rain off of it. Your solution would be the least painful, I'll just have see if it drys
Comment: I understand. You'd have to remove and replace the steps to do anything about it, though. If you have an unfinished basement you may be able to apply some backing material from the inside.


Arbitrarily Deep Nested Pattern Matching

Question: Is there a way to create a Mathematica pattern which matches expressions whose heads may be arbitrarily deep, i.e. something like f[___][___][___]...?
Comment: +1, for me, this question comes up most often when trying to match `Derivative[_][_][_]`, and it is annoying every time.
Comment: [WReach](http://stackoverflow.com/users/211232/wreach) has answered similar question in the thread ["Currying with Mathematica"](http://stackoverflow.com/questions/5686494/currying-with-mathematica/5687109#5687109). But his code works only for fixed depth of the expression.
Comment: Welcome to StackOverflow. See [this FAQ](http://meta.stackexchange.com/questions/7931/faq-for-stack-exchange-sites) if you have question about the site. Please remember to [vote for and accept](http://stackoverflow.com/faq#howtoask) good answers.
Answer: The suggested solution
There seems to be no built-in construct to pattern-test nested heads automatically. We can achieve the goal by writing a function which would, for any given (sub)expression of the form f[___]...[___], efficiently determine f (which, with a slight abuse of terminology, we may call a symbolic head for the expression). Here is the code:
ClearAll[shead];
SetAttributes[shead, HoldAllComplete];
shead[expr_] := Scan[Return, Unevaluated[expr], {-1}, Heads -> True];

Here is how it can be used  (I will use the same set of tests as @Sasha):
In[105]:= Cases[{f[1], g[f[1]], f[1, 2, 3][1], f[1][2][3][4]}, x_ /; shead[x] === f]

Out[105]= {f[1], f[1, 2, 3][1], f[1][2][3][4]}

The pattern syntax
If you prefer to use the syntax suggested by @Sasha, that version would look like
Clear[headPattern];
headPattern[head_] := _?(Function[Null, shead[#] === head, HoldFirst]);

In[108]:= Cases[{f[1], g[f[1]], f[1, 2, 3][1], f[1][2][3][4]}, headPattern[f]]

Out[108]= {f[1], f[1, 2, 3][1], f[1][2][3][4]}

Further explanations and comments
How it works
Here are some hints for the logic that lead to this solution, and how it works. The solution will be most concise and efficient if we manage to leverage some of the built-in expression-traversal functions. Some that come to mind are Map, Scan,Cases,MapIndexed,Position. Given that we need the heads, we'd need to pass the Heads->True option. I used Scan, since this one is easy to stop at any point (unlike other mentioned constructs, for which you'd typically need to throw an exception to stop them "in the middle", which is rather inelegant and induces some overhead as well) as soon as we find what we want. Our result will be the very first thing Scan finds on its depth-first expression traversal, so it is expected to be very efficient (it does not traverse the entire expression).
Avoiding the evaluation leaks
Another comment is on evaluation. You can see that HoldAllComplete attribute is used in shead, and Unevaluated is used in its body. These are very important - they serve to prevent possible evaluation of expressions passed to the function. It  may matter in cases like this:
In[110]:= m = n = 0;
g[x_] := n++;
h[x_] := m++;
{Cases[Hold[f[g[1]][h[2]]], x_ /; shead[x] === f :> Hold[x], Infinity], {m, n}}

Out[113]= {{Hold[f[g[1]][h[2]]]}, {0, 0}}

Here, we see what we'd expect - even though Cases has been traversing the entire expression and feeding its (sub)parts to shead, no evaluation of sub-parts was triggered by shead. Now we define a naive version of shead which "leaks evaluation":
sheadEval[expr_] := Scan[Return, expr, {-1}, Heads -> True]

And now,
In[114]:= {Cases[Hold[f[g[1]][h[2]]], x_ /; sheadEval[x] === f :> Hold[x], Infinity], {m, n}}

Out[114]= {{Hold[f[g[1]][h[2]]]}, {2, 1}}

The latter behavior is unsatisfactory generally. The whole code-is-data paradigm, so useful in meta - programming, is very powerful in Mathematica because you can use rules to destructure code. Possible (unwanted) evaluation during the pattern- matching would greatly impair it. The whole problem is in the sub-parts. Wrapping Hold only prevents the whole expression from evaluation. Functions like  Cases and other similar functions for code destructuring are so great because they don't evaluate sub-parts when doing the structural (syntactic) matching.
Comment on symbolic heads
The last comment here (mostly about definitions) is that the shead function returns not exactly what is normally called symbolic head in Mathematica. The difference is for atomic expressions. For example, shead[f] returns f, while for atomic expressions, the true symbolic head should coincide with the head of an expression (Symbol in this case). I have developed the symbolicHead function with this behavior here, and that one can also be successfully used in place of shead in the above, although shead is more efficient.
Comment: If I could vote this more than once I would.  You are the master instructor.
Comment: @Mr.Wizard Thanks! But it was our comment-based discussion that prompted me to do it here. I wish I always had the attitude to find decent wording for my answers.
Answer: A recursive matching strategy could be used here:
curried[head_] := _head | (x_[___] /; MatchQ[Hold[x], _[curried[head]]])

Usage:
In[26]:= $testCases = {f, f[1], g[f[1]], f[1,2,3][1], f[1][2][3][4]};
         Cases[$testCases, curried[f]]

Out[27]= {f[1],f[1,2,3][1],f[1][2][3][4]}

Update
At Leonid's suggestion, Unevaluated can be used as a clearer and faster way to avoid evaluation leaks in the pattern condition:
curried[head_] := _head | (x_[___] /; MatchQ[Unevaluated[x], curried[head]])

Comment: While I very much like the idea, I must say that the performance of this solution is inferior for even moderately deeply nested heads. The following alternative `curriedAlt[head_] := _head | (x_[___] /;
MatchQ[Unevaluated[x], curriedAlt[head]])` offers much better performance while is essentially the same idea. One can see the difference with e.g. this code `Cases[{HeadCompose[f, Sequence @@ Range[15]]}, curried[f]]` and the same with `curriedAlt`.
Comment: A very nice use of recursive patterns - +1.
Comment: So _that's_ how to make that work.  It was the first thing I tried, and I promptly made an infinite recursion.
Comment: @Leonid `Unevaluated` reflects the intent much more clearly than `Hold` and so I prefer it even if there were not a performance difference.  The `MatchQ[Hold[...], _[...]]` pattern was just me blindly following an idiom that I had used in an unrelated context.  I'll update my answer to include your suggestion.
Comment: I see - I have also used a lot the pattern similar to the one you mentioned. Whether or not to like design and other patterns, but we seem to often think in them.
Answer: How about the following:
In[277]:=
ArbitrarilyDeepHeadPattern[
  head_Symbol] := _?(Function[
    MemberQ[
      Position[#, _head, {0, Infinity}, Heads -> True], {0 ...}]])

In[281]:= Cases[{f[1], g[f[1]], f[1, 2, 3][1], f[1][2][3][4]},
 ArbitrarilyDeepHeadPattern[f]]

Out[281]= {f[1], f[1, 2, 3][1], f[1][2][3][4]}

Answer: WReach's answer made me reexamine a recursive definition, which I tried yesterday but gave up on.
I realize now that what I had actually works, it just throws an error.  It is a toy compared to Leonid's fine method, but I have a fondness for terse code, so I post it here for interest or amusement.  Make sure you do not have $RecursionLimit set to Infinity before running this.
Cases[
  {f, f[1], g[f[1]], f[1, 2, 3][1], f[1][2][3][4]},
  f // Blank@#|#0[#]@_&
]

Or even:
Cases[
  {f, f[1], g[f[1]], f[1, 2, 3][1], f[1][2][3][4]},
  p=_f|p@_
]

Comment: @Mr.Wizard I would not make any assumptions for the head depth, since it has nothing to do with the `$RecursionLimit`. But, at least conceptually, here is a way to cure your method. The problem is that there seems to be no way to evaluate `Alternatives` lazily (that is, not evaluate its second part until the first part is found to not match, by the pattern - matching), because, while the alternatives are tried from left to right, this is done inside the pattern-matcher and is out of our control. A lazy version of `Alternatives` would save your method.  Below is a possible implementation.
Comment: Continuing... `ClearAll[lazyAlternatives];
SetAttributes[lazyAlternatives, HoldRest];
lazyAlternatives[expr_] := expr;
lazyAlternatives[first_, rest__] := _?(Function[
    MatchQ[#, first] || MatchQ[#, lazyAlternatives[rest]]])`. Now, you can test: `MatchQ[HeadCompose[f, Sequence @@ Range[100]],
 p = lazyAlternatives[_f, p@_]]` gives `True`, without any generated errors. But, of course, the code is no longer as brief as you would like, since we need this auxiliary function. For very deeply nested heads, you will still to increase the `$RecursionLimit`, for this to work.
Comment: Sorry to disappoint you, but the error message is there for a reason. What you get at the end is a very deeply nested pattern with depth controlled by `$RecursionLimit`. But, it will only work for expressions with head nesting roughly not exceeding that depth. This works: `Block[{$RecursionLimit = 20, p, n = 17},
 MatchQ[HeadCompose[f, Sequence @@ Range[n]], p = _f | p@_]]
`, but if you change `n` to `18`, it will stop working.  Ironically, you'd need to set `$RecursionLimit` to `Infinity` for your construction to work.
Comment: @Leonid like I said this is just a toy, but I think it is reasonably  safe to assume that the head depth is not going to exceed 256, the default $RecursionLimit.
Comment: In a sense, the method suggested by @WReach  also implements a version of lazy `Alternatives`, where the laziness is achieved by a separate head `curried` and the `HoldAll` attributes of `Condition`. His version seems to be the most elegant way to achieve that.
Comment: Mr.Wizard But I quite like the ideas - so +1
Comment: @Leonid, I love your analyses.
Comment: @Mr.Wizard My suggestion does not really eliminate the problem with `$RecursionLimit`, it just moves it from definition-time to run-time. My other solution with `symbolicHead` function (linked from the other post) is also recursive, but has no such problem since `symbolicHead` is properly tail-recursive (in the Mathematica sense), and so depends on the `$IterationLimit` rather than `$RecursionLimit`, and poses no danger of stack exhaustion (apart from the fact that default `$IterationLimit` is much larger than default `RecursionLimit`).
Answer: Here is an alternative version of @Leonid's shead, to find the symbolic head of an expression.  (You should use the rest of his solution as is.)  My function doesn't involve any recursion, but instead it uses that Level has a special case where setting the levelspec to {-1} returns all atomic expressions, the first of which is the head itself:
shead2[expr_] := First@Level[expr, {-1}, Heads -> True];

It works in pattern matching just the same as shead does:
In[264]:= Cases[{f[1], g[f[1]], f[1, 2, 3][1], f[1][2][3][4]},
 x_ /; shead2[x] === f]

Out[264]= {f[1], f[1, 2, 3][1], f[1][2][3][4]}

And to help understand how it works, here is how Level behaves with levelspec set to {-1}:
In[263]:=
Level[#, {-1}, Heads -> True] & /@ {f[1], g[f[1]], f[1, 2, 3][1],
  f[1][2][3][4]}

Out[263]= {{f, 1}, {g, f, 1}, {f, 1, 2, 3, 1}, {f, 1, 2, 3, 4}}


If radiation didn't exist, would everything live longer?

Question: I recently noticed that dying of old age is similar to a death by radiation - hair loss, weakened immune system etc. and I was wondering - Does background radiation limit our lifespan, or that of any other living creature?
Comment: This is not a physics question, it's a biology question (as it is about the lifespan of human due to extraneous factors).
Comment: I'm voting to close this question as off-topic because it's about biology not physics
Comment: I have no idea, and this question (and this comment) probably doesn't belong here, but a nuclear physicist once suggested to me that humans may have adapted to background radiation, and that the absence of radiation would shorten life span.
Comment: To quote John Muir, "When we try to pick out anything by itself, we find it hitched to everything else in the Universe."  Eliminating the types of radiation which typically cause humans problems would have all sorts of unintended effects.  One good example is that humans might never have evolved into existence without the genetic mutations created by ionizing radiation.
Answer: There is some interesting data on the subject. People looked at the relationship between the prevalence of radon in counties in the US with the mortality due to lung cancer, and found a surprising relationship. Instead of the "more radon kills more people" correlation that was expected, there was an initial "dip" in the curve - as though "a little bit of radiation is good for you". This is phenomenological, so there is no guarantee of causality - but it does give food for thought. "What doesn't kill you makes you stronger." - could it be true in this case?
I refer you to this paper from which I will extract one quote:

and one plot:

Negative correlation. A little bit of radiation is good for you? Strange conclusion - but the data seems fairly persuasive.
Comment: That is a very weak paper from any angle, scientific, physical and especially epidemiological. I find especially this passage laughable: "We have studied correlations between radon levels and a large number of factors, and  these correlations are always too small to matter. Radon levels depend principally on geology and it is difficult to imagine how the amount of smoking can correlate with geology on a nationwide basis. Many possibilities have been considered but none can have nearly the required effect.". The paper basically ends there without ANY supporting data and no citations. LOL
Comment: I can see that negative correlation, and that data does seem to prove it - but it's only measuring radon, right? What about other radioactive sources? (Also, if most of our radiation comes from space as cosmic rays, then I think this would be only a small insight into the idea.)
Answer: Oh, I love this subject. The term here is radiation hormesis, and it's basically off-limits for nuclear regulators (If it's true, it horribly complicates the risk analysis for the use of any radiation source). The classic study comes from Taiwan http://www.jpands.org/vol9no1/chen.pdf where a number of apartment buildings were built using rebar that had been contaminated with cobalt-60 (accidental recycling). Figure 1 shows a quite remarkable decrease in cancer rates, with greater total dose and greater dose levels producing less cancer, with the effect lasting 20 years.
It's to be noted that the exposure in this case was external, rather than (for instance) ingestion of strontium-90 and caesium-137, which get concentrated in the thyroid and clearly increase the cancer risk.
As a matter of fact, I'm not at all sure I believe the results. They are too clean and the prophylactic response is both too prompt and too durable for me to accept easily. But they are certainly food for thought.
Comment: You can put this to a test easily. Send this study to the FDA as evidence that your slightly radioactive steel bars should be considered a preventative measure against cancer and be approved as a medical device. Please don't hesitate to publish the letter you will get from the FDA in return. I am sure it will be a very fun read.
Comment: Probably not a fun read - something along the lines of "the FDA adheres to the Linear No-Threshold model, and the supplied paper is incompatible with this." See the Wiki articles http://en.wikipedia.org/wiki/Linear_no-threshold_model, http://en.wikipedia.org/wiki/Linear_no-threshold_model for an introductory look at the issue.
Answer: What Floris points to is not all that strange.
Living organisms exist in a state that is extremely far removed from thermal equilibrium, a lot of work is constantly being performed to maintain itself. So, even without any radiation, the body would fall apart on quite short time scales, were it not for the processes at work that do all the self repair work. Now, the capacity of the body to repair itself exceeds the minimum requirement to stay alive by quite some margin, so a little more or less radiation should not matter. However, when the damage that needs to be repaired is very low then the repair  mechanisms may not work well. If the trigger for some mechanism to become active mis problem A but once it is at work it may also deal with problem B, then removing problem A may lead to problem B not being dealt with anymore.


Should prenasalized consonants be distinct from nasal+obstruent sequences?

Question: I have a language with CVC syllable structure and a series of prenasalized consonants. As written, therefore, a word like /anda/ would be distinct from /aⁿda/. I can barely grasp the difference here, and even less so how to romanize this. Is it realistic to have an allophonic process turn /anda/ into [a.ⁿda], or vice versa?
Answer: It's perfectly reasonable to get rid of that distinction, and have /nd/ and /ⁿd/ be treated exactly the same. Many languages in the Bantu family (the family that's most famous for its prenasalized stops) lack that distinction.
If you want to keep the distinction, it would probably be considered contrastive syllabification (the way the consonants are grouped into syllables is significant), which happens but is pretty rare. Googling that term will get you some more information on how that tends to work.
Answer: I don't think there is a difference between /aⁿda/ and /anda/.
There doesn't need to be any difference. If a diphthong can constitute a single syllable (as in "aisle," "boy," and "cow") so can a prenasalized consonant. A little practice can get you used to saying and hearing [nda] or [mbe], for example, as single syllables.
But if you WANT there to be a difference, you can make a distinction between non-syllabified nasals in prenasalized consonants vs. syllabified nasals that precede obstruants--with the phonetic difference being the length of the nasal.
So, for example, [anda] and [an̩da], which would be two- and three- syllable words respectively.
Comment: /'a.ⁿda/ and /'an.da/ could present a distinction in a language concerned with morae, since the former comprises two morae and the latter three.


Can we make electron drift velocity faster than light by reducing area of resistor?

Question: We know that $I= nqAV_d$.
Can we send high current ($I$) through a "fat wire" (more $A$) then reduce $A$ at the resistor so much that $V_d$ becomes faster than light in order to maintain $I$?
Comment: A brief comment: Almost all of condensed matter physics models are valid only in non-relativistic regime. The model for transmission of current through metal is also an example of such. So, the above equation is not valid when $V_d$ is close to speed of light.
Comment: This is somewhat similar to the following imaginary scenario https://what-if.xkcd.com/147/
Answer: A metal would melt before the drift velocity reaches anywhere near the speed of light (besides all the other mechanisms preventing the drift velocity from getting that high).
In semiconductors, and likely in metals at very high current densities as well, the drift velocity eventually stops increasing linearly with the electric field. This is known as velocity saturation and is mainly due to carriers scattering by emitting optical phonons. The saturation velocity is on the order of $10^7\ \text{cm/s}$ for most semiconductors, about 3 orders of magnitude lower than the speed of light.
Comment: wow universe really doing everything to not let us go FTL.  I thought I came across a hacky way to go FTL.
Answer: tldr: not by reducing area, but by slowing light, maybe.
If we restrict our discussion to the speed of light in a medium, it is possible to slow down the phase or group velocity of light while in a material.
However, I am not sure in practice whether you can reduce the speed of light in a semiconductor or dielectric below the drift velocity of electrons simultaneously moving through that material in a circuit.
Note that at fixed applied voltage, reducing cross-sectional area $A$ does not help as drift velocity is $v_d=\mu E$, where electron mobility $\mu$ depends on the material and electric field $E=\Delta V / \Delta x$ depends on the length $\Delta x$ of the element for fixed voltage $\Delta V$.
Rather, it is more of a materials and photonics problem whether you can pull this off. On the materials side, you simultaneously want high electron mobility $\mu$ and slow light (e.g. high dielectric constant = relative permittivity: remember $v=c/\sqrt{\epsilon_r\mu_r}$). It is a fun exercise to plug in numbers and see how far off you are for a specific material.
In my opinion, the best bet is to forget about the permittivity, optimize mobility and use clever photonics. In Hao et al. (2015) they slow the group velocity of (a narrow band of infrared) light in graphene by a factor of 163: equaling $1.839\cdot10^6\ \text{m/s}$.
If you can maintain freestanding graphene's amazing mobility of $200,000\ \text{ cm}^2/(\text{V}\cdot\text{s})=2\cdot10^3\ \text{m/s}\cdot\text{cm/V}$, you only need to apply $1\ \text{kV}$ across a centimeter of graphene to reach Hao et al.'s speed of slowed light in graphene.
Interestingly, in a chapter on breakdown of a graphene nanoribbon field-effect transistor by Amiri and Ghadiry (2017) they simulate electric fields above $1\ \text{MV/cm}$. (There are probably better, experimental references for this.)
So it seems to me if you create a photonic design that simply maintains high mobility, graphene might be able to handle the electric field necessary to go into an interesting $v_g < v_d\, (< c)$ regime, where $v_g$ is the group velocity of some bandwidth of light in graphene and $v_d$ is the drift velocity of electrons in graphene.

Other thoughts:
In principle, if the phase velocity is reduced below the speed of electrons in the material, you should be able to get Cherenkov radiation, which is a cool effect. See this paper on Cherenkov radiation in integrated nanophotonic structures for a flavor of this:  they model a single moving charge with thoughts on an application like a particle detector. (There are multiple papers on Cherenkov generation of phonons by increasing the drift velocity past the speed of sound in a material, but of course that is sound, not light. This is related to the velocity saturation in semiconductors that Puk mentioned.)


Azure CLI in Git Bash

Question: I am trying to use a bash (sh) script on windows to run a test deployment. I am running the script from the gitbash console so that I have a copy of bash, but doing so means that the azure clie is not available (i.e. azure command is not found). Does anyone know how I can get the Azure cli working in GitBash (I am assuming I just install it somewhere else) or should I change to a different way of using bash
Answer: Sometimes commands in windows git bash need .cmd appended.  Also, another way of installing the Azure-Cli is through Chocolatey https://chocolatey.org/
Try this command after Azure-Cli is installed:
az.cmd --version

Echoing mscrivo you can run the line below in CMD not PowerShell (elevated/admin)
echo "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} ${14} ${15} > "C:\Program Files\Git\mingw64\bin\az"

Now you should be able to run in Git bash:
az --version

Comment: There is also the option to create a bash alias as is stated in the issue link provided by @citleon https://github.com/Azure/azure-cli/issues/3445 . Adding `alias az='az.cmd'` to your .bashrc file will do the trick.
Comment: Just in case someone is not familiar, the command to install azd using chocolatey is `choco install azd`
Answer: artberri noted the best solution in a comment:
Add the following to your %USERPROFILE%\.bashrc or %USERPROFILE%\.profile
alias az='az.cmd'
However, if you want to be able to use az in bash scripts, you'll need something a little more drastic, run the following from cmd prompt:
echo  "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} ${14} ${15} > "%SYSTEMROOT%\az"
That will essentially create a passthrough az command in your windows folder that can be run from anywhere and passes parameters through to az.cmd.
Comment: `$SYSTEMROOT` was pointing to `c:\windows` in my computer. I didn't want to have the `az` link there. Instead you can also put it in `\mingw64\bin` which is also in your git bash path.
Comment: I could not write wiql queries with that solution. Either `az: error: unrecognized arguments: [Id],[Title] FROM WorkItems WHERE [AssignedTo]=@Me` showed up when I used `"` or `'C:\Program' is not recognized as an internal or external command` using `'` to write the query in argument
Comment: This is the only thing that worked for me. The solution above did not.
Comment: This worked. Just a little change to get mklink to work - cmd /c mklink "%SYSTEMROOT%\az" "C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd"
Comment: This works nicely unless one of our arguments is a multiline string., then the quoting is all messed up and this is why @veritas code fails. Anny suggestions on how to fix it?
Answer: In case using Git bash, navigate to the following directory:

C:\Program Files\Git\etc\profile.d

Edit aliases.sh, then add a new alias for az as below:
alias az='az.cmd'

Comment: Worked for me! Strange that somehow "az.cmd" is already "known" by Git Bash but not "az"
Comment: Not really that strange as Windows uses .bat, .cmd and .exe for executables unlike Linux that uses no extensions for executables. So adding an alias for the az.cmd makes perfect sense. Also if you take a peek in the wbin folder of the az cli installation you will see that it only contains the file az.cmd.
Answer: You have to install the CLI to your computer.
There are multiple ways to do that.
I'm a friend of NodeJS so i use npm for the installation:
npm install -g azure-cli
More details here: https://www.npmjs.com/package/azure-cli
But you can do it also in other ways. A very nice way is to use docker. There are containers from Microsoft with a preinstalled version of Azure CLI.
docker run -it --name azure microsoft/azure-cli

On Windows 10 with the ubuntu bash you can use:
echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ wheezy main" | \
     sudo tee /etc/apt/sources.list.d/azure-cli.list

sudo apt-key adv --keyserver packages.microsoft.com --recv-keys 417A0893
sudo apt-get install apt-transport-https
sudo apt-get update && sudo apt-get install azure-cli

Or as a python enthusiast run
pip install --user azure-cli

Most important is that the "az"/"az.bat" or "azure" bin is available via your path variable.
Answer: In other words Azure CLI for Windows is not compatible with Git Bash for Windows
https://github.com/Azure/azure-cli/issues/3445
Comment: Summary of the issue linked: This appears to be resolved. When I run `az.cmd` it works fine.
Answer: In your ~/bin directory (in Windows it means c:\Users\<username>\bin) I've just created a file named az with:
"C:/Program Files (x86)/Microsoft SDKs/Azure/CLI2/python.exe" -IBm azure.cli "$@"

Then make the file executable
chmod a+x az
The content is "borrowed" from az.cmd.
When trying an alias approach mentioned before I had a problem with long commands, with a lot of parameters throwing an error
"'C:\Program' is not recognized as an internal or external command,operable program or batch file."
EDIT:
I've ended using Ubuntu through WLS. For all tools like az, terraform, kubectl, istioctl. The az tool runs good in interactive mode as well.
Answer: So I arrived here looking for a way to run the same az commands in a bash shell script on Azure DevOps Linux and Windows (git bash) build agents, so I could share the same code across both types of agent. This also works for a git bash shell on Windows 10. My longer answer is here: Azure DevOps Build Pipeline can't get secrets from Key Vault when secured with vnet and firewall
The gist of it is:
if [[ $(uname -s) == "Linux" ]]; then
    azcmd="az"
else
    # If we're in a bash shell on Windows, az commands don't work, but we can call the az.cmd batch file directly from git Bash if we can find it...
    azcmd=$(where az.cmd)
fi

# Remember to specify CIDR /32 for removal
"$azcmd" keyvault network-rule remove -n <MyKeyVault> --ip-address 22.214.171.124/32

Basically just substitute "$azcmd" wherever you'd normally use az once the bootstrap code has executed.
Answer: My previous approach for this was just to add the Azure CLI Scripts folder to the $PATH inside my ~/.bashrc file. But, after updating Azure CLI to 2.2.0 via the MSI, this approach started to fail with this error:

C:\Program: can't open file 'Files': [Errno 2] No such file or directory

So, to fix this, I have my $PATH in ~/.bashrc include ~/bin and then I created a file with the following content as ~/bin/az (don't forget to chmod 0755 the new file):
#!/usr/bin/env bash

AZURE_CLI_PATH="/c/Program Files (x86)/Microsoft SDKs/Azure/CLI2"

export PATH="${PATH}:${AZURE_CLI_PATH}:${AZURE_CLI_PATH}/Scripts"
export PYTHONPATH="${AZURE_CLI_PATH}/src"
export PYTHON_CMD="$(which python)"

winpty "${PYTHON_CMD}" -m 'azure.cli' "${@}"

After closing out my GIT Bash window and re-opening it, I can now run az again:
$ az version
This command is in preview. It may be changed/removed in a future release.
{
  "azure-cli": "2.2.0",
  "azure-cli-command-modules-nspkg": "2.0.3",
  "azure-cli-core": "2.2.0",
  "azure-cli-nspkg": "3.0.4",
  "azure-cli-telemetry": "1.0.4",
  "extensions": {}
}

Answer: Don't use the MSI installer at all. Since the Azure CLI is implemented in Python, use the Python installation method as @blndev wrote. This way instead of az.cmd you get az.bat and az shell script, and the installation path will not contain spaces.
pip install --user azure-cli

More detailed info on this method can be found at https://blogs.msdn.microsoft.com/brijrajsingh/2017/03/02/installing-azure-cli-2-0-on-windows/
The symlink worked for me most of the times, but some commands are still failing, e.g.
az dls fs access set-entry ...
'C:\Program' is not recognized as an internal or external command, operable program or batch file

Answer: I tried @mscrivo's solution. When using the az command in a shell script however you still have problems due to the spaces in the path.
Therefor I created a azproxy.cmd in %SYSTEMROOT% containing
@echo off
"C:\Program Files (x86)\Microsoft SDKs\Azure\CLI2\wbin\az.cmd" %*

And then create the mklink to that file
mklink "%SYSTEMROOT%\az" "SYSTEMROOT%\azproxy.cmd"

PS the expanded value of %SYSTEMROOT% should not contain spaces of course

Azure CLI in Git Bash


Airdrop starts but never progresses

Question: I'm able to see the device I'd like to airdrop to, my iPhone. The transfer starts but stays stuck as shown below.
Answer: Airdrop relies on Bluetooth and WiFi. Basically, you can try following listed steps to resolve your issue.

Toggle Bluetooth & WIFI off, then on OR, enable AirPlane mode and turn OFF.
Check if you have VPN enabled or not?
Check if Airdrop is ON and allows connection for your contacts or Everyone on both devices.
Reboot both iPhone and Mac.

Airdrop starts but never progresses


Invalidating a specific area of data cache without flushing its content

Question: I'm currently working on a project using the Zynq-7000 SoC. We have a custom DMA IP in PL to provide faster transactions between peripherals and main memory. The peripherals are generally serial devices such as UART. The data received by the serial device is transferred immediately to the main memory by DMA.
What I try to do is to reach the data stored at a pre-determined location of the memory. Before reading the data, I invalidate the related cache lines using a function provided by xil_cache.h library as below.
Xil_DCacheInvalidateRange(INTPTR adr, u32 len);

The problem here is that this function flushes the related cache lines before invalidating them. Due to flushing, the stored data is overwritten. Hence, every time I fetch the corrupted bytes. The process has been explained in library documentation as below.

If the address to be invalidated is not cache-line aligned, the
following choices are available:

Invalidate the cache line when
required and do not bother much for the side effects. Though it sounds
good, it can result in hard-to-debug issues. The problem is, if some
other variables are allocated in the same cache line and had been
recently updated (in cache), the invalidation would result in loss of
data.
Flush the cache line first. This will ensure that if any
other variable presents in the same cache line and updated recently are
flushed out to memory. Then it can safely be invalidated. Again it
sounds good, but this can result in issues. For example, when the
invalidation happens in a typical ISR (after a DMA transfer has
updated the memory), then flushing the cache line means, losing data
that were updated recently before the ISR got invoked.

As you can guess that I cannot always allocate a memory region that has a cache-line aligned address. Therefore, I follow a different way to solve the problem so that I calculate the cache-line aligned address which is located in memory right before my buffer. Then I call the invalidation method with that address. Note that the Zynq's L2 Cache is an 8-way set-associative 512KB cache with a fixed 32-byte line size. This is why I mask the last 5 bits of the given memory address. (Check the section 3.4: L2 Cache in Zynq's documentation)
INTPTR invalidationStartAddress = INTPTR(uint32_t(dev2memBuffer) - (uint32_t(dev2memBuffer) & 0x1F));
Xil_DCacheInvalidateRange(invalidationStartAddress, BUFFER_LENGTH);

This way I can solve the problem but I'm not sure if I'm violating any of the resources that are placed before the resource allocated for DMA.(I would like to add that the referred resource is allocated at heap using the dynamic allocation operator new.) Is there a way to overcome this issue, or am I overthinking it? I believe that this problem could be solved better if there was a function to invalidate the related cache lines without flushing them.
EDIT: Invalidating resources that are not residing inside the allocated area violates the reliability of variables placed close to the referred resource. So, the first solution is not applicable. My second solution is to allocate a buffer that is 32-byte bigger than the required one and crop its unaligned part. But, this one also can cause the same problem as its last part*(parts = 32-byte blocks)* is not guaranteed to have 32 bytes. Hence, it might corrupt the resources placed next to it. The library documentation states that:

Whenever possible, the addresses must be cache-line aligned. Please
note that not just the start address, even the end address must be
cache-line aligned. If that is taken care of, this will always work.

SOLUTION: As I stated in the last edit, the only way to overcome the problem was to allocate a memory region with a Cache-Aligned address and length. I'm not able to determine the start address of the allocated area, hence I've decided to allocate a space that is two Cache-Blocks bigger than the requested one and crop the unaligned parts. The unalignment can occur at the first or the last block. In order not to violate the destruction of the resources, I saved the originally allocated address carefully and used the Cache-Aligned one in all of the operations.
I believe that there are better solutions to the problem and I keep the question open.
Answer: Your solution is correct. There is no way to flush a subset of a cache line.
Normally this behavior is transparent to programs but it becomes visible in multithreaded code and when sharing memory with hardware accelerators.


Data entry template tricks user into thinking they are done entering all data

Question: Background: Entity I'm working for uses a large number of data entry forms, somewhere along 800-900 range--partially due to regulation and partially self-inflected due to current process. The usage probably follows the 80/20 rule where 20% of forms are heavily used while 80% are seldom used.
Problem: Users are often not completing the forms because they believe they have reached the "end" of the form. Often, there is very little visual indication that there are more fields which need to be filled. Not all forms have minimum requirement rules before submission which is a problem in itself as users believe the system will flag missing fields and that's not always the case.
Potential solutions: The problem is large enough that I think it will have to be attacked from several angles.

Moving forward, newly issued forms and forms that need refactoring/updates will be required to have required fields coded before pushing to prod.
The user interface will have a few elements removed, such as a horizontal line that seems to indicate the "end" of the form, but it's sole purpose is to delineate between the submit button.
?

Here is where I'm stuck. We are working in Angular and I've been looking around for an auto-scroll. The idea is to scroll the page down once the user gets to a specific field. However, this method also makes it form specific (we would need a different trigger for each form) and not universal.
Another idea would be to use a tool such as WalkMe to indicate to the user to "scroll down" using a down arrow. The arrow would always be on so long the scroll bar isn't all the way to the bottom.
Greying out the submission button is out of the question. Users will almost definitely call our Call Center to complain that they can't submit a form and we always try to avoid more phone calls.
Another idea would be to hide the submit button until the user scrolls all the way to the bottom. However, this is similar to greying out the button in my opinion. People will call to complain they can't submit a form.
This issue is tricky enough that we've gotten feedback that fields are "missing" just because users can't see them. When I went to investigate, I was tricked the exact same way as the user was. However, our triage process helped due to me having to test a large number of forms prior to me realizing that the field was always there and I just hadn't scrolled.
Any other suggestions?
Answer: Things that come to my mind are:

Display a horizontal scroll indicator fixed to the top of the page: Maybe it is not obvious enough that there is more to see. A more prominent way of visualizing that might help
Prompt the user with a dialog if they want to navigate away and haven't submitted yet.
Display some kind of progress of all filled out forms, e.g. 23/100 forms filled
Answer: I presume this is on a PC.
Any horizontal line can trick users into thinking they've reached the bottom of the page.
Try including thin vertical lines which always run off the bottom of the page.