PHP stealth redirect not working

Question: I'vee got this little snippet function to redirect visitors to my pranking page without changing the URL:
function april_fools($session_id_string)
{
    if(!isset($_SESSION['session_id']) || $_SESSION['session_id'] != $session_id_string)
    {
        $_SESSION['session_id'] = $session_id_string;
        include("./april_fools/" . $date_array[2] . ".php");
        exit();
    }
}

What it should do, is that it actually includes the pranking page content and executes it, and then exits the program before continuing (next code is not evaluated). Unfortunately, that doesn't seem to work :( It relies on a specific date in year. The April Fool's date and session identificator is driven by this snippet:
$date_string = date("d-m-Y");
$date_array = explode("-", $date_string);

$session_id = base64_encode($visitor_ip . '/' . $_SERVER['HTTP_USER_AGENT'] . '/' . $date_string)
session_start();

And the actual "redirect" is made by calling the previous function:
if($date_array[0] == 1 && $date_array[1] == 4)
{
    april_fools($session_id);
}

But the function doesn't want to work, so the "redirect" doesn't happen. Any idea on how to get it working please? Best using date driven PHP...
EDIT: Solution was cookies clear. Nothing to do with actual code.
Comment: When I try to access the `./april_fools/2018.php` page, the script itself works. But the "redirect" doesn't. Something is wrong on the main redirecting page, but can't quite tell what. :(
Answer: The $date_array variable is out of scope in your april_fools() function. You need to import it using global.
function april_fools($session_id_string)
{
    global $date_array;
    if(!isset($_SESSION['session_id']) || $_SESSION['session_id'] != $session_id_string)
    {
        $_SESSION['session_id'] = $session_id_string;
        include("./april_fools/" . $date_array[2] . ".php");
        exit();
    }
}

If your calling code is inside another method you need to pass the year ($date_array[2]) as a parameter.
Or as Niet the Dark Absol says, pass it as a parameter to this function regardless of scope.
Comment: Or, better, pass it in as a parameter to the function.
Comment: Well, I edited it so the fuction takes the `$date_array` variable as a second parameter, and it still doesn't work. I mean the function itself doesn't work. It basically skips the entire function and continues after it. Like it doesn't exist. Can send complete page with the included one to look after...
Comment: Haven't checked the condition, but there is nothing else wrong with the code.
Answer: While @rollstuhlfahrer hit it on the nose, I'd do it a bit differently:
function april_fools($session_id_string){
  if(date('m') == 4 && date('d') == 1){
    if(!isset($_SESSION['session_id']) || $_SESSION['session_id'] != $session_id_string){
      $_SESSION['session_id'] = $session_id_string;
      include("./april_fools/" . date('Y') . ".php");
      exit();
    } else {
      echo 'Session already exists, Nothing to do..';
    }
  }
}

Its a variable scope issue, what you would have known if you enabled error_reporting()
Comment: If reporting was on, the if statement `if(!isset($_SESSION['...` is not true. Because it would have certainly giving you a info message about an undefined variable. Clear your cookies, do a hard refresh on the browser.
Comment: I'm using WAMP on Windows, and `notice` and `error` reporting are enabled bz default. Didn't change default behaviour. Nothing has pop out.
Comment: Oh crap :D That was it, the damn cookies :D Now it works, thank you :D So it false redirects to the page (includes that page instead of original one) and reloading the page now actually redirects the user to language preset based on IP geolocation :)

PHP stealth redirect not working


I have a sauna that requires 25A & 120V and has a plug that fits my 20A recepticles

Question: My new house has typical 15A receptacles and 14 gauge wire. In a few places it has 20A receptacles and 12 gauge wire.
My girlfriend moved into a new house with me and brought an infrared sauna. The sauna has a plug which fits in the 20A receptacles BUT the sauna indicates it needs 25A/120V. So would I need to use a 30A breaker and run 10 gauge wire to a receptacle similar to the same receptacle as the 20A circuits? Are there receptacles which look like my 20A receptacles but are rated for 25A (or higher)? What do I search for? It looks like a NEMA 5-20P but the installation manual says it requires 25A.
Thanks.
Comment: unless it is 25A *not* continuous, in which case it gets a 25A breaker. But putting a 20A plug on a 25A device sounds rather problematic. **Make/model #** would definitely help. And check if it has a UL or ETL listing.
Comment: Make/model #? With two exceptions (15A plugs can fit 20A receptacles, and there are no 40A receptacles so 50A receptacles are used for 40A devices), the plug, receptacle and breaker size must match and the wire must be large enough. So no, with rare exceptions (welders are strange, for example) if a device actually needs 25A then it needs a 25A or 30A breaker and 10 AWG (or larger) wire. Actually it gets even more complicated - many things (but I don't know about a sauna) have to be rated for 125% - e.g., if you have 24A EVSE (car charging) then it goes on a 30A breaker - so 25A is an odd size
Comment: You should feed that beast with 30 Amp circuit
Comment: Even a 30A could be problematic, 210.21(B)(2) says max amp on 30A receptacle is 24A. (I don't know why it isn't called a 24A  receptacle!)
Comment: What do the installation instructions call for? Any UL/ETL certified device will have installation instructions that will call out _all_ these details. In order for the UL listing have validity, it _must_ be installed in accordance with those instructions. If it doesn't have a UL/ETL listing, send it back to Amazon/alibaba/wherever and get a refund, then get one that does.
Answer: If the item is UL Listed (or ETL or CSA), then use it according to instructions.
Because UL has taken into account how the appliance will use power, and has determined it's appropriate for the type of socket is factory-provided.
However, if the documentation is indeed telling you to use a 25A breaker with it, then this will require a dedicated circuit to that appliance.  This is on its face a violation of NEC 210.21, however it may be permitted under one of the exceptions.  Such an exception must be a circuit dedicated to that one appliance, as the breaker protection would be insufficient for 120V loads at large.
Usually, high power 120V appliances are scams
If it is not UL Listed, then it was not legal to sell and is not safe to use. Send it back to Amazon, it wasn't even sold by Amazon, it was sold by a foreign 3rd party.  A lot of cheap Cheese junk is being shoveled onto our shores designed for "110V" but taking more than 16 amps.  That is not how North American power is done.  When power gets that big, we switch to 240V.
The standard scam these days is to take a high power appliance and say it is "110V" and show a standard plug on it. This makes people more confident about buying it, They make you think it's a miracle appliance that can just plug onto 110V when the ones at Home Depot cannot.  But this is a lie. It can't plug into a normal socket because it takes way too much power!  That's why the Home Depot ones are 240V.
The 25A size is far beyond what is possible for standard sockets.  There is an obscure socket type used for travel trailers, but it is a tiny bit too big for that size (a mistake no competent manufacturer would make, and they wouldn't design it to just miss.
As such, it appears your only option is the NEMA 14-50 RV plug, also used on ranges.  You will not use one of the two hot wires.
Comment: The sauna was bought years ago before I met my partner. She brought it with her when we moved in together. It wasn't bought on Amazon. It is a California based company. It was purchased at Costco.

Reading the instructions that I found online, the sauna is a 20A/120V device. But looking at the electronics on the actual sauna it is marked:

`
* Breaker: 25A
* Input Voltage: 120V/60HZ
* Power Range: 900-2300W
* Current Range: 7-20A
`

I'll just consult a local electrician.


How to commit batches of inserts in hibernate?

Question: I have to save a large number of objects to the database using hibernate.
Instead of commiting all of them at once, I would like to commit as soon as n (BATCH_SIZE) objects are present in the session.
Session session = getSession();
session.setCacheMode(CacheMode.IGNORE);
for(int i=0;i<objects.length;i++){
    session.save(objects[i]);
    if( (i+1) % BATCH_SIZE == 0){
        session.flush();
        session.clear();
    }
}

I would have tried something like above, but I read that session.flush() does not commit the changes to the database.
Is this the following code the correct way to do it?
Session session = getSession();
session.setFlushMode(FlushMode.COMMIT);
session.setCacheMode(CacheMode.IGNORE);
session.beginTransaction();
for(int i=0;i<objects.length;i++){
    session.save(objects[i]);
    if( (i+1) % BATCH_SIZE == 0){
        session.getTransaction().commit();
        session.clear();
        //should I begin a new transaction for next batch of objects?
        session.beginTransaction();
    }
}
session.getTransaction().commit();

Comment: Looks good to me. You keep the database transactions small and you clear the session cache so your heap doesn't fill up with detached entities. Of course you should simply test that - set the transaction timeout to a very low number (a minute for example) and let this code persist a huge volume of data and see if the code completes its job.
Answer: As far as i can tell your solution is correct.
There might only be one problem:
Depending on how you get your sessions from the SessionFactory the commit might also close your session and you would have to open a new one. According to my knowledge this always happens if you use getCurrentSession() and the session context "thread". If you are using openSession() the session seems not to get closed by a commit automatically.
You can easily check this using the isOpen() method after commiting the transaction. If the session get closed you have to open a new one before any further calls to save().


Can I allocate both "available" and "free" memory to a Minecraft server? (18.04)

Question: I have about 4GB of available memory and 1GB of free memory. Can I allocate 5GB to my Minecraft server? I am a noob, just got Ubuntu :D
I have no idea what the difference between free and available memory is.
Comment: Is the minecraft server running in a VM? if the minecraft server is standalone, it should already be using all the memory... but will only use as much as it needs
Comment: i don't reallly know-- but on windows 10, i have a .bat file that has this: java -Xmx4G -Xms4G -d64 -jar spigot-1.13.2.jar nogui

obviously on ubuntu it has to be a bash file, but i want to know if i can do
 -xmx5g -xms5g
Answer: Let's see a typical free output:
              total        used        free      shared  buff/cache   available
Mem:       32806952     7552612      780696      949180    24473644    23843300
Swap:       2097148       36864     2060284

Here available is free + part of buff/cache, you could not add them together because free will be counted twice.
Also if you allocate all available memory to your minecraft server, it means your computer will not have any memory left to use disk cache.  OS will try to swap something out, and could be incredibly slow.
Answer: Follow the 'Available' estimate, or your system will start to swap (and slow down). Remember that it's an estimate - it might be high, it might be low.
Let's review the relevant memory definitions: (from https://askubuntu.com/a/859664/19626)

Total = Used + Free
Available: Estimation of how much memory is available for starting new applications, without swapping. Unlike the data provided by the cache or free fields, this field takes into account page cache and also that not all reclaimable memory slabs will be reclaimed due to items being in use.

Note that 'Available' and 'Free' are apples-and-oranges. Do not add them and expect a useful result.


Autohide launcher does not work ubuntu 14.04

Question: Altough I've setted to autohide sometimes this feature does not work.
After restarting it works but after a short period of time again stops autohiding.
Any shortcut to hide launcher? Or how to solve problem?
Comment: I'm sorry my friend but it just enables or disables setting for hiding launcher. But not actually works. When i re-enable again it does not hides.
Answer: Identifying the root cause of the problem would require to know which kind of installed packages/applications/service may overwrite this setting.
You can of course create a keyboard shortcut to quickly re-enable Autohide with the following command:
dconf write /org/compiz/profiles/unity/plugins/unityshell/launcher-hide-mode 1

In order to identify the guilty application, you could use the following command in a terminal:
dconf watch /org/compiz/profiles/unity/plugins/unityshell/launcher-hide-mode

and use System Monitor to list the running applications/services.


How do vehicles become disabled?

Question:
Possible Duplicate:
What happens when a vehicle is "disabled" in Battlefield 3?

I noticed sometimes that when I hit a vehicle it becomes disabled.  I'm not sure if it has something to do with the HP they have left or where I hit the vehicle.  Does anyone know?
Answer: Vehicles become disabled once they drop low enough in health. I believe its in the range of 25% to 50% health.
From the help site of EA:

How do vehicles regenerate in Battlefield 3?
  Vehicles will regenerate up to 25% of hit points as long as they are not "disabled", but will require an Engineer to complete the repair in order to be useable.  A vehicle becomes disabled after taking a certain amount of damage (different for each vehicle).  Aircraft, for example, become disabled at 50% health.  The vehicle continues to be "disabled" until it's repaired to 100% hit points.

How do vehicles become disabled?


Can you ride in the same car in LEGO City Undercover for switch?

Question: Is it possible to ride in the same car when playing co-op in LEGO City Undercover on Switch?
Answer: Bought the game now and the conclusion is the following.
You can ride in the same car if:
It's a bus or limousine.
One player can stand at the roof on a car but if the car crash the player will fall of.
Answer: No, generally not. Some vehicles do let you have multiple people in them, I think. But those are special cases.


ESB cluster with WSO2 ELB ESB Server Errors

Question: INFO - WkaBasedMembershipScheme No responses received from WKA members
[2014-03-10 17:27:56,990]  INFO - WkaBasedMembershipScheme Sending JOIN message to WKA members...
[2014-03-10 17:27:56,996] ERROR - Axis2GroupChannel Unable to deserialize message:ClusterData[src=org.apache.catalina.tribes.membership.MemberImpl[tcp://{192, 168, 7, 121}:4000,{192, 168, 7, 121},4000, alive=1394443159382, securePort=-1, UDP Port=-1, id={0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 }, payload={35 10 35 77 111 110 32 77 97 ...(61)}, command={}, domain={119 115 111 50 46 99 97 114 98 ...(21)}, ]; id={35 -20 -126 -65 124 -7 72 -95 -82 44 94 -16 -47 -25 -12 58 }; sent=2014-03-10 17:27:56.994]
java.io.InvalidClassException: org.apache.catalina.tribes.membership.MemberImpl; local class incompatible: stream classdesc serialVersionUID = -3747696661765742913, local class serialVersionUID = 9101965184867046152
    at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:617)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1622)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1517)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1706)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1344)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1990)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1915)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1798)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
    at org.apache.catalina.tribes.group.RpcMessage.readExternal(RpcMessage.java:64)
    at java.io.ObjectInputStream.readExternalData(ObjectInputStream.java:1837)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
    at org.apache.catalina.tribes.io.XByteBuffer.deserialize(XByteBuffer.java:568)
    at org.apache.axis2.clustering.tribes.Axis2GroupChannel.messageReceived(Axis2GroupChannel.java:60)
    at org.apache.catalina.tribes.group.ChannelInterceptorBase.messageReceived(ChannelInterceptorBase.java:84)
    at org.apache.catalina.tribes.group.interceptors.NonBlockingCoordinator.messageReceived(NonBlockingCoordinator.java:512)
    at org.apache.catalina.tribes.group.ChannelInterceptorBase.messageReceived(ChannelInterceptorBase.java:84)
    at org.apache.catalina.tribes.group.interceptors.TcpPingInterceptor.messageReceived(TcpPingInterceptor.java:170)
    at org.apache.catalina.tribes.group.ChannelInterceptorBase.messageReceived(ChannelInterceptorBase.java:84)
    at org.apache.catalina.tribes.group.interceptors.TcpFailureDetector.messageReceived(TcpFailureDetector.java:114)
    at org.apache.catalina.tribes.group.ChannelInterceptorBase.messageReceived(ChannelInterceptorBase.java:84)
    at org.apache.catalina.tribes.group.ChannelInterceptorBase.messageReceived(ChannelInterceptorBase.java:84)
    at org.apache.catalina.tribes.group.interceptors.DomainFilterInterceptor.messageReceived(DomainFilterInterceptor.java:45)
    at org.apache.catalina.tribes.group.ChannelInterceptorBase.messageReceived(ChannelInterceptorBase.java:84)
    at org.apache.catalina.tribes.group.interceptors.OrderInterceptor.messageReceived(OrderInterceptor.java:101)
    at org.apache.catalina.tribes.group.ChannelInterceptorBase.messageReceived(ChannelInterceptorBase.java:84)
    at org.apache.catalina.tribes.group.ChannelCoordinator.messageReceived(ChannelCoordinator.java:253)
    at org.apache.catalina.tribes.transport.ReceiverBase.messageDataReceived(ReceiverBase.java:287)
    at org.apache.catalina.tribes.transport.nio.NioReplicationTask.drainChannel(NioReplicationTask.java:212)
    at org.apache.catalina.tribes.transport.nio.NioReplicationTask.run(NioReplicationTask.java:101)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Comment: What are the versions of ELB and ESB?
Looks like the versions are not compatible with each other.
Answer: According to the error "org.apache.catalina.tribes.membership.MemberImpl"  class cannot be serialized, meaning you may have different version of this class in other ESB nodes.
Please check do you have any differences on jars you are using between each ESB instances (for example tribes_7.0.28.wso2v1.jar is the contains this class in ESB4.7 , so cross check similar way based on your ESB)
Answer: tribes is out of date. Why not use hazacast instead? in ESB 4.8, clustering agent is changed.


Does being in pitch black darkness prevent you from being detected?

Question: * minor spoilers *
I'm trying to sneak my way underground early to try to find some goodies, and there's a lot. Fortunately it's not densely populated with enemies everywhere. Came across some Yiga strongholds and don't want to alarm them, I don't have a lot of strong weapons. I haven't found the lightroot in the area so it's mostly dark.
Will enemies be able to see me in the darkness or should I just keep out of lines of sight?
Comment: Well, common sense tells that ordinary darkness (i.e. not result of a spell) will not prevent you from being spotted. In some advanced games it might reduce their accuracy, but never seen a game where it prevented enemies from spotting you when you are nearby. However, just a comment as I can't be sure about this specific game. (Played few Zelda games long ago, not this one.)
Comment: I'm talking about pitch black darkness, not just nighttime. Where you can't see a thing without a light source.
Comment: Well you can do trial and error then, and based on several attempts reach a sensible conclusion, which you can then share.
Answer: In my testing, you are just as visible in pitch black darkness as you would be on a bright sunny day to enemies. Standing a decent way away from enemies looking in your direction will alert them like normal. As far as I can see, being in the darkness does not help you avoid detection, so approach with caution as usual.
Comment: Which makes sense for monsters that live underground.  _You_ may be blind but _they_ can see just fine.
Comment: @Bobson: Except that the monsters still use torches for light. I'm focusing on Bokoblins and Yiga here, not the Frox.
Comment: I wouldn't classify Yiga as "monsters," though perhaps it's possible they have night vision tech in their masks. They've been able to spot me, even when their spotlights are not on me.


Is there a high performance Fortran compiler for Linux?

Question: Right now I use Sun-Studio, but Oracle is asking ridiculously high license fees for it.
Is there a high performance Fortran compiler for Linux that is comparable with Sun-Studio's performance?
GNU's Fortran compiler is a lot slower.
Comment: I thought Solaris Studio was free? http://www.oracle.com/technetwork/server-storage/solarisstudio/overview/index.html
Comment: Yes.   I just downloaded SunStudio f http://www.oracle.com/technetwork/server-storage/solarisstudio/downloads/index.html.   You need a (free) Oracle account.
Comment: There is also Pathscale Ekopath. Link [here](http://www.pathscale.com/ekopath.html), or directly [here](http://c591116.r16.cf2.rackcdn.com/ekopath/nightly/Linux/ekopath-2013-08-08-installer.run) for latest build (for some reason, the link on Pathscale's site is a bit old). [They said](http://www.pathscale.com/ekopath4-open-source-announcement) once they were going open source, but I'm not sure they finally did.
Comment: And [open64](http://www.open64.net/), derived from [SGI MIPSPro](http://en.wikipedia.org/wiki/Open64), yet running on Intel architecture.
Answer: Intel Fortran compiler is available as "try before buy", you can find it here.
Comment: Intel Fortran is rather fast, according to [Polyhedron](http://polyhedron.com/pb05-lin64-f90bench_SBhtml). Also, it's not just "try before use", but ***free for non-commercial development*** : see [here](https://registrationcenter.intel.com/RegCenter/NComForm.aspx?ProductID=1501). Btw, your link does not seem to work any longer.
Answer: Oracle Solaris Studio is (still) a free download. What's might be expensive is a full support contract.
It's still the best compiler for HPC applications on Solaris (SPARC and x86) and Linux (x86).
http://www.oracle.com/technetwork/server-storage/solarisstudio/index.html
There are lots of technical articles, community forums, and full documentation on the website.
Comment: The way I understand it, you can download the latest beta, but if you want the latest stable version, you have to pay.
Comment: Newer link [here](http://www.oracle.com/technetwork/server-storage/solarisstudio/downloads/index.html)


invalid EFI file path on windows 8

Question: I installed ubuntu 13.04 on my new notebook (that came with windows 8 installed) and now when I try to load windows 8 appear the error:

impossible to find command 'drivemap'. (this is in portuguese, I'm not sure if I translated it right
invalid EFI file path.

ubuntu is working OK. someone knows what can I do to solve this and have both SO running? I have searched on the internet but couldn't find anything I could understand. can someone help me?
Answer: First, I recommend you go into your firmware and disable Secure Boot, if you haven't already done so. This isn't always required, but Secure Boot seems to cause a lot of problems with many Ubuntu installations, so IMHO it's best to disable it. This will not solve the specific problem you're reporting, though.
Second, do one of the following things:

In Linux, install my rEFInd boot manager. There's a Debian package that you can install quite easily. The result is that when you reboot, you should see rEFInd rather than GRUB. rEFInd should enable you to boot Windows or Linux (and to boot Linux either directly or via GRUB).
In Linux, install and run the Ubuntu Boot Repair tool. This should fix your problem, but it will probably leave stray and non-functional boot entries. Some users find that it doesn't create bootable Windows entries, but it does for others.

If you try Boot Repair first and it doesn't work to your satisfaction, be sure to run it again and restore the backup files it created before trying rEFInd. There's an option in the advanced menu of Boot Repair to restore its backup files.
Comment: The boot repair tool worked fine for me.
Comment: I disabled Secure Boot before installing windows. What solution do you think I should try first?
Comment: Whichever sounds better to you, based on those descriptions. My own preference would be rEFInd, but as I maintain it, I'm biased.

invalid EFI file path on windows 8


Itô integral with respect to a diffusion

Question: Let

$(\Omega,\mathcal A,\operatorname P)$ be a probability space
$\mathbb F=(\mathcal F)_{t\ge 0}$ be a filtration on $(\Omega,\mathcal A)$
$B=(B_t)_{t\ge 0}$ be an $\mathbb F$-adapted Brownian motion with respect to $\mathbb F$

Let $H=(H_t)_{t\ge 0}$ be $\mathbb F$-adapted, locally bounded and of the form $$H_t(\omega)=\sum_{i=1}^nH_{t_{i-1}}(\omega)1_{(t_{i-1},t_i]}(t)\;\;\;\text{for all }\Omega\times[0,\infty)\;$$ for some $0=t_0<\ldots<t_n$. Let $\mathcal E$ be the space of all such $H$.
The Itô integral of $H$ with respect to $B$ is defined as $$I_\infty^B(H):=\sum_{i=1}^nH_{t_{i-1}}\left(B_{t_i}-B_{t_{i-1}}\right)\;.$$ Now, if $H$ is more general, but $\mathbb F$-progressively measurable and $$\left\|H\right\|^2:=\operatorname E\left[\int_0^\infty H_t^2\;dt\right]<\infty\;,$$ then there is a sequence of $H^n\in\mathcal E$ with $\left\|H^n-H\right\|\stackrel{n\to\infty}{\to}0$ and one defines $$\int_0^\infty H_t\;dB_t:=I_\infty^B(H):=\lim_{n\to\infty}I_\infty^B(H^n)\;\;\;\text{in }L^2(\operatorname P)\;.$$ Now, let $$H_t^{\tau}:=H_t1_{\left\{t\le \tau\right\}}\;\;\;\text{for }t\ge 0$$ for a $\mathbb F$-stopping time $\tau$ and let $I^B(H)$ be the continuous modification of the $\mathbb F$-martingale $\left(I_\infty^B(H^{(t)})\right)_{t\ge 0}$. One defines the Itô integral from $s$ to $t$ by $$\int_s^t H_r\;dB_r:=I_t^B(H)-I_s^B(H)\;,$$ if $0\le s<t$.

Question: $\;$ Let $H$ be continuous and $\mathbb F$-progressively measure with $$\int_0^TH_s^2\;ds<\infty\;\;\;\text{for all }T\ge 0\;$$ How can we show, that $$\int_0^TH_s\;dB_s=\lim_{n\to\infty}\sum_{t\in\mathcal P_T^n}H_t(B_{t'}-B_t)\;\;\;\text{for all }T\ge 0\;?\tag{1}$$ Here, $\mathcal P_T^n$ is constructed as follows:

$\mathcal P$ is a sequence of countable subsets $\mathcal P^n$ of $[0,\infty)$
$0\in\mathcal P^n\subset\mathcal P^{n+1}$
$\sup\mathcal P^n=\infty$
$\displaystyle |\mathcal P^n|:=\sup_{t\in\mathcal P^n}\min_{s\in\mathcal P^n:s\ne t}|s-t|\stackrel{n\to\infty}{\to}0$
$\mathcal P_T^n:=\mathcal P^n\cap [0,T)$ for $T>0$
$t':=t_{k+1}\wedge T$ if $t=t_k\in\mathcal P_T^n=\left\{t_0,t_1,\ldots\right\}$ with $t_0<t_1<\ldots$

For $G\in C^0(\mathbb R_{\ge o})$ one calls $$\langle G\rangle _T:=\lim_{n\to\infty}\sum_{t\in\mathcal P_T^n}|G_{t'}-G_t|^2\;\;\;\text{for }T\ge 0$$ quadratic variation of $G$ with respect to $\mathcal P$.
One can show, that $\langle B\rangle_T=T$ almost surely (independent of $\mathcal P$).
I want to show, that we can choose a sub-sequence of $\mathcal P$ such that $(1)$ holds almost surely.
Comment: what do you mean by $G \in C^0(R_{\ge 0}$
Comment: you meant in the introduction $X$ or $H$ is progressively measurable?
Comment: your question is strange, why are you defining the quadratic variation at this point?
Comment: @ConradoCosta $G\in C^0(\mathbb R_{\ge 0})$ means that $G:[0,\infty)\to\mathbb{R}$ is continuous. I've defined the quadratic variation cause it might be crucial for the question.
Comment: @ConradoCosta I thought there might be more than once plausible way to the define the *Itô integral* and it would be important to give you my construction.
Answer: Well the convergence in $(1)$ occurs in probability, uniformly  on compact time intervals (The proof of this is rather involved). You have the elementary result that convergence in probability implies almost surely convergence along a subsequence. So there is such a subsequence.
But here is an easier way to show the existence of such a subsequence. Be warned: There is some handwaving. First fix $T$. The triangle inequality gives you the following. Proving that the triangle inequality holds for the norm you defined might be a good exercise by the way.
$$\|H_n - H_m\| \leq \|H_n - H\| + \|H_m - H\|$$
Next we make use of the Ito isometry. $H_m\cdot B$ is short hand for $\int_0^TH_m \, dB$.
$$\|H_n - H_m\| = E\left[\left((H_n - H_m)\cdot B\right)^2\right]$$
Combined with the triangle inequality this shows that the sequence of $L^2$ martingales $(H_n\cdot B)$ is a Cauchy sequence if you use the expression on the RHS of the isometry above as some kind of distance metric. Since the space of  continuous $L^2$ martingales is complete under this metric, $H_n\cdot B \rightarrow X$ for some $L^2$ martingale $X$. It is this $X$ that we refer to as $H\cdot B$. All this boils down to
$$\lim_{n \rightarrow \infty}E\left[(H_n\cdot B - X)^2\right] = 0$$
I hope this looks familiar to you. This is just ordinary $L^2$ convergence. $L^2$ convergence implies convergence in probability, which in turn implies convergence almost surely along a subsequence.
Now look at the sum you defined for the Ito integral. Pick your $\mathcal{P}^n$ such that the resulting $H_n$ approximates $H$ in the appropriate sense. This is a bit restrictive but for the general case you would have to consider the result I mentioned in the first paragraph.
Comment: Why does $(1)$ hold at all?
Comment: @0xbadf00d i will get back to you in a few hours


Is it possible to find $a$ and $b$ so that I can get the form $\frac{1}{n+1}=\frac{a}{n}+b$ with constants $a$ and $b$?

Question: Is it possible to find $a$ and $b$ so that I can get the form $\frac{1}{n+1}=\frac{a}{n}+b$ with constants $a$ and $b$?
I tried but failed, because $a$ depends on $n$ in my result:
$$\frac{1}{n+1}=\frac{a}{n}+b\\ \Leftrightarrow 1=\frac{a}{n}(n+1)+b(n+1)$$
Set $b=1$:
$$1=a+\frac{a}{n}+(n+1)\\ \Leftrightarrow-n^2=an+a=a(n+1)\\ \Leftrightarrow a=\frac{-n^2}{n+1}$$
Comment: No, since $0=bn^2 + (a+b-1)n + a$ so if this was true so it will be for n+1.
Answer: I think if there exist constants $a,b$ such that:
$$\forall n \in \mathbb{N}, \hspace{0.2cm} \frac{1}{n+1} = \frac{a}{n} + b$$
Then $\forall n \in \mathbb{N}, \hspace{0.1cm} a = n(\frac{1}{n+1} - b)$. Notice that $b\neq 0$ (otherwise $a=\frac{n}{n+1})$. So that by letting $n \to \infty$ $a$ is $+/- \infty$. So the answer is no
Answer: It doesn't seem possible...
For $n=0$ you have $\frac 1{n+1}=1$ while $\frac an+b$ is undefined.
For $n\to\infty$ you have $\frac 1{n+1}\to 0$ while $\frac an+b \to b$.


Is there an official tutorial for installing Ubuntu 18.04+ on a device with an SSD and an additional internal hard drive?

Question: I don't know if there are any special instructions to follow, or if the Ubuntu (Ubiquity?) installer automatically detects this (and if it does detect the additional internal drive, what exactly would it do in the background)? I am not trying to dual-boot (I just plan to use a Windows 10 Virtual Machine, but for that, I'll need more disk space: I was planning to purchase a computer with a small 128GB SSD and a 1TB HDD, but I didn't know if Ubuntu would automatically install the bootloader and essential?? things on the SSD, and then I could use the HDD for other storage. This is because I had heard that SSDs are faster for starting up the operating system and for everyday use, but HDDs are still better for long-term storage. Is this correct as well?)
Comment: Possible duplicate of [How to install applications to a separate hdd?](https://askubuntu.com/questions/313592/how-to-install-applications-to-a-separate-hdd), especially [this answer](https://askubuntu.com/a/1139085/344926)
Comment: https://tutorials.ubuntu.com/tutorial/tutorial-install-ubuntu-desktop#0  (*I always use the 'something else' so I can setup the system exactly as i want, but that option is not usually covered in tutorials*)
Comment: Oh yes - I've seen this tutorial before. However, it does not go very in depth into the "Something else" option. Perhaps Ubuntu should add more documentation for this since it's such a hard thing to learn more about (at least on the official Ubuntu docs)?
Comment: It's not actually hard; its pretty intuitive in my opinion; though I occasionally opt to setup my partitions with `gparted`  (if using a GTK+ or gnome/mate/xfce/.. system) or `kde partition manager` (if using KDE/LXQt/.. system) first, noting the desired setup on scrap paper then start the install - just selecting my pre-prepared partitions with the installer (using something-else).  It's easy either way, but I find `gparted` easier as I'm more familiar with its controls.
Comment: I found _something_: https://www.addictivetips.com/ubuntu-linux-tips/split-ubuntu-between-hdd-ssd/. But I would feel more comfortable using information from Ubuntu itself.
Comment: there are a number of install tutorials, but I rarely touch them sorry.  try searching using https://tutorials.ubuntu.com/  (thought a search engine search with a limit on `site:*.ubuntu.com` is usually how I find things)
Comment: Related: https://askubuntu.com/q/62152/301745
Comment: Unless you use some old BIOS or new NVMe protocol drives which are not supported by your machine to boot SSD is transparent to Linux installers (assuming the distribution contains a kernel which has drivers for your disk type of course)
Answer:
but I didn't know if Ubuntu would automatically install the bootloader and essential?? things on the SSD

The UEFI part you start from BIOS. It will offer to install the bootloader on the FIRST disk it sees (sda) and offer you the option to pick another disk (sdb).

I don't know if there are any special instructions to follow,

Nope.

or if the Ubuntu (Ubiquity?) installer automatically detects this

Yes.
Basically:

Set the ssd up with a mount called /
Set the hdd up with a user named mount (I use /discworld)
What I tend to do next is edit ~/config/users-dirs.dirs to point the directories in home to /discworld. The personal files are best kept on the hdd. The config in /home/ is better kept on the ssd.

This is because I had heard that SSDs are faster for starting up the operating system

Yes. Not just starting up but also starting applications (if the config files are on the ssd)

and for everyday use, but HDDs are still better for long-term storage. Is this correct as well?)

Yes. For video, music and general personal files the hdd is best used as the "fileserver". It is also better to set all downloads in things like torrent programs, browsers to the hdd.

Is there an official tutorial for installing Ubuntu 18.04+ on a device with an SSD and an additional internal hard drive?

Nope. Not "official" since it basically has a high personal influence: what I consider best someone else might believe it not to be. But I did found a AU answer that might be helpful in explaining how to use the "something else":
How to use manual partitioning during installation? See part 2 in this answer: https://askubuntu.com/a/521195/15811
Comment: "It will offer to install it on the FIRST disk it sees (sda) and offer you the option to pick another disk (sdb)." Do you have an image of that by chance?
Comment: Sorry. my brain isn't working today. Which specific one on the page you referenced should I pay attention to?
Comment: I added all my answers to the comments into the answer.
Answer: I have Ubuntu 18.04 installed on a 128Gb SSD with no problems whatsoever.
Much depends on what you want to use the machine for but in the majority of cases 128Gb should be more than sufficient and any extraneous files such as videos and photos etc can be directed to the other HD as required.
It is possible to change things round so that you move your ~/home folder to the HD and any content currently in ~/home on the SSD there also but there is a school of thought that suggests it is better to leave ~/home where it is on the SSD (which is what I subscribe to) to aid in more speedy loading of programs.
Moving the ~/home folder is described in detail in this article.
Read down from from Migrating the Home Folder in the article if you wish to follow that route.


How can I kill myself in Nethack?

Question: I've made it a personal goal to kill myself on the first turn with every character. I've done it with Knight(by riding the pony) and Wizard(by shooting myself). How can I do it with the other ones?
Comment: a couple of thoughts:  1) I like fun! And the occasional question with a silly title is cool by me, assuming it doesn't have other baggage. 2) We disagree on how tags do or should work - feel free to weigh in on the meta post above, but depending on tags to browse generally is bad for new user engagement. 3) This particular issue isn't one I'm flexible on. This isn't really the right forum for an in-depth discussion on suicide, but "How can I kill myself" isn't a question title we're going to allow.
Comment: A wizard can't shoot himself on turn 1, at least not with force bolt. Have to take off your cloak first.
Answer: The easiest way, in Vanilla nethack is to pray. There is a 1 in 3 chance that your god will be angry enough to steal a point of wisdom, and a level. (This does not result in dying on the first turn, so you will not receive the "Do not pass go. Do not collect 200 zorkmids" message. It may count for your purposes, however.)
This does not work on nethack.alt.org, and may or may not work in other implementations. Ignoring prayer, the following strategies may be of use.
A monk can read starting scrolls until it is genocide or earth, a ranger can attempt to shoot itself with a poisoned arrow (chaotic non-orc only). A rogue can quaff their starting potion of poison. A chaotic priest could possibly kill himself with quaffed holy water. A knight can fail to mount his steed. A wizard can quaff a potion; put on a ring of polymorph; read a scroll of earth, stinking cloud, or genocide; zap themselves with or break a wand; or zap themselves with a spell.
The remaining characters tend to have a fair amount of hit points, with the exception of tourists, who could possibly be killed by a luckily tossed upwards dart. They will need the assistance of the environment. Perhaps a cross-aligned randomly generated artifact? Maybe a lucky trap?
Comment: Would those actually kill you on the first turn? The reason it's so hard to die on turn #1 (and get the [funny message](http://nethackwiki.com/wiki/Do_not_pass_go._Do_not_collect_200_zorkmids.)) is because most actions that might kill you will consume at least one turn *before* you die. I'm pretty sure that's true for praying, at least.
Comment: As far as I can tell, the "You must relearn your lessons!" punishment won't kill you in vanilla, either; it's not an NAO patch. On both, if you're already level 1, you lose maxhp but don't die.
Comment: You must relearn your lessons will kill you in vanilla, but it is true that you don't die on the first turn, and so don't receive the bonus message.
Answer: If your starting position is next to a wall, boulder, loadstone, etc, you might kill yourself by kicking it.
Answer: There is a sure fire way to die as every class on your first turn. Simply use the #quit command. Okay, it's not as interesting as the pony and I don't know if quitting actually kills you (I assume it does) but at least you have an answer to your question.
Comment: You don't die by quitting, you just quit. `You quit in The Dungeons of Doom on dungeon level 1 with 0 points,
and 0 pieces of gold, after 1 move.
You were level 1 with a maximum of 15 hit points when you quit.`

How can I kill myself in Nethack?


Show always one specific hidden file inside a specific folder

Question: I am creating a backup of .bashrc. I make a copy of it inside my backup folder.
Let's say the folder is ~/backup
previously I always created a .hidden file and put the name of files I want to hide. But now the case is opposite, I am always trying to show the hidden file.
This is the closest I came across, but no luck !! Is it possible to have Nautilus show hidden files except for one specific folder?
 and How to always show some hidden files in Nautilus?
I have tried !.bashrc in .hidden file.
Here is a screenshot to emphasize simplicity. ANY IDEAS??
Answer: The direct feature to selectively show hidden files is not available. The user case is also not quite clear. In principle, it is easy enough to hit Ctrl+h to quickly see a file you know is normally hidden.
There are workarounds you can use to achieve what you want, but unless you indicate why you would want to achieve this, it is a bit guessing.
If the reason is that you want quick access to a hidden file, i.e., for quick opening and editing, then you could create a link to the file, e.g. a link bashrc to the file .bashrc in the same directory. That is not more overhead than editing a .hidden configuration file.
That way, you see a file anytime that gives quick access to the hidden file.
Hard link or symbolic link?
In the old days, I would have recommended to make a hard link. However, graphical editors, upon saving, may make a copy and then rename the copy when the changed file is saved. This breaks the hard link. Therefore, I would recommend a symbolic link, that always links to the same file name, even if its inode has changed.
Comment: @ vanadium in my case, I am creating a backup. Usually, we do not need to visit backup in a while and because the file is hidden I might forget I made a backup of it in the first place.
Comment: Press Control+H to see all hidden files you included in the backup.


Lubuntu Clock Gone

Question: I was just exploring my new Lubuntu installation & accidentally switched off the clock...so I cant see it. How do i get it back please?
What do I need to do to be able to view the clock?
Comment: tried a reboot?
Answer: Edit the panel by right clicking it and clicking preferences, then to applets. Click add, find the clock, and add it. That should work, but comment if it doesn't.
Edit: DK Boses solutions works well, and is simpler, see comments.
Comment: When you right-click on the lxpanel, you may *first* have to click on `Add / Remove Panel Items` and *then* click on `Panel Preferences`, etc.
Answer: Thankyou for the detailed reply, but I have followed the steps carefully, as written by DK Bose, but when I click on Panel Preferences, there is no Add Clock in the list displayed.
What can you suggest that I am doing wrong?
Regards,
James

Lubuntu Clock Gone


What options do I have after dodging if I can't air combo?

Question: I'm playing on Hard mode, about ten hours through the game, and I'm noticing more and more jobber enemies don't react to getting hit. As a result, attempting to knock enemies into the air leaves me in the air with them on the ground. Not only does this not help me, it puts me in a very dangerous position if the enemies swarm underneath me or if there's somebody shooting me.
The problem is that if I light or heavy attack after dodging, I automatically do a launcher, which is something I really don't want to do. The only other option I'm aware of is just not attacking or disengaging after dodging, but this is a clunky option that drags a fight on for minutes at best and not always possible if I'm caught against a wall.
Are there any other options or weapons for me if I want to do something after dodging?
Answer: Depending on what your secondary weapon is, your heavy counter may not be a launching attack. According to this thread, having a Small Sword as your secondary will result in launching (or attempting to, at least) your enemy into the air, while a Large Sword will leave you on the ground. This is typically what type of I had as my secondary when I played through the game each time.
Another way you can ensure that you don't accidentally turn yourself into a floating target, then use your Pod's counter after a perfect evade. With Pod A, at least, you'll launch a grenade, which not only does much more damage than your typical Pod fire, it also tends to knock smaller enemies away.
Lastly, while you seem to be against it, pausing for a split second after a perfect evade is a perfectly viable strategy that I used myself from time to time. If you don't see an opening for an attack, then it might be best not to try one.
Comment: +1 - How do you use a pod counter?
Comment: @GGMG use the same button you fire with your Pod right after a perfect evade


What is the smallest CMAR number

Question: Take an integer mapping N -> N'
Where the last digit of N ( in the ones place) moves to the first digit to form N'
Example: 123->312
I am looking for the smallest number N where N' is a multiple of N:  N' = r N, r=2,3,etc
(Exclude r=1 since it's trivial)
( I have no idea if such numbers have a name, so I made one up, CMAR, based on my name)
Most of these CMAR numbers are huge. I found one of more human size, N= 142857, which I believe is the smallest possible.
Comment: Welcome to MSE. Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: Write $N=10b+a$ where $b$ has exactly $n$ digits, ($10^{n-1}\le b<10^n$) and $a$ is a digit. Then $N'=10^na+b$. We want that
$$10br+ar=10^na+b$$
That is
$$\frac ba=\frac{10^n-r}{10r-1}$$
The RHS meets these values, for the first values of $r$:
$$\frac{99\ldots98}{19}, \frac{99\ldots97}{29}, \frac{99\ldots96}{39},
\frac{99\ldots95}{49},\cdots$$
(Each numerator has $n-1$ nines).
You must find, for each value of $r$, some value of $n$ such that the corresponding fraction can be simplified, yielding an one-digit denominator and an $n$-digits numerator. Then $10^n-r$ and $10r-1$ must have a common divisor $d$ such that
$$\frac{10r-1}9\le d\le\frac{10^n-r}{10^{n-1}}$$
From the second inequality we get $r\le 10^n-d\cdot10^{n-1}$, which implies $d\le 9$. Put this in the first inequality to get $r\le 8$.The only value of $10r-1$ that has appropiate divisors is $49$, because the other are primes, $3\cdot 13$ and $3\cdot 23$ ($3$ is too small in these cases). Thus, $r=5$.
We find that $99995$ is a multiple of $7$, so for $r=n=5$ we get the smallest possible solution, which turns to be $142857$. ($99995/49=14285/7$).
Remark: If it is allowed to write zeroes at the left of $N$, then the upper bound for $d$ dissapears, and we can get other solutions, like $N=052631578947368421$ or $N=0344827586206896551724137931$.
Comment: Your derivation is pretty close to mine, but I see one difference (which doesn't effect the answer). You say r can't exceed 8. I think I found a number for r=9. It is a monster on the order of 1.01*10^43.  So one of us is wrong on that.
Comment: I was wrong on r=9. It doesn't work

What is the smallest CMAR number


Why won't my thermostat control the HVAC anymore after trying to switch thermostats?

Question: I bought a new Nest thermostat which is supposed to be compatible but needs a professional installation (advice that should have been heeded by non-professional electrician me). This is to replace an old finicky thermostat that must be original with this 20 year old house. After wiring up the Nest and starting to go through the menus, I realized it was better to let a pro do it. So I put everything back the way it was with the old thermostat.
... Or did I... With the old thermostat back on, the heat keeps going up and up without being able to be switched off or lowered by the thermostat. I can get the HVAC to turn off by removing the front face of the old thermostat (like in the pictures below) but that's all the control I have.
Here's the wiring before I attempted any changes:

And here it is after I tried to get it back on:

I've scheduled a pro to come out and install the new thermostat this coming Monday... But that's a while to wait now not being able to control the heat. Plus I'd rather have the old setup working before he gets the new one put in. So... HELP!
Additional information - maybe not relevant:
I did have the breaker to the house completely turned off while switching out thermostats. The first time I put the old one back on, the display went nuts flipping through numbers. So I took it right off, flipped the power to the house back off... Double checked the wiring and how well screwed in it all was... Then put it back on and powered back up. After that, the display is completely normal, but the HVAC ignores the settings still. The thermostat even makes the same "click" that it would if I changed the temperature above or below the current temperature, but nothing changes still.
Comment: Thanks, Brad! The top picture does show how it was originally wired. Anyways, it appears to have been fixed... With the power to the HVAC cut off, I waited until the temperature dropped below the desired temperature, put the thermostat back on and restored power and all was well after that. Must've just had one very confused thermostat.
Comment: The problem is, that without pictures of either how it was originally wired, or of the other end of the cable, there is nothing we can help with.
Answer: Nest states their thermostats do not require a Common 24 volt leg of control power to be provided to the Nest, However there are some situations where the Nest will not stay charged after a bit thus requiring a Common leg of the 24 volt power sent to it,  they allege the Common leg back feeds to  the thermostat by unused circuits and it does in many if not most cases however there are many complaining after a week or so  of the Nest no longer operating or operating normally, this is due to no Common leg in most cases.
Answer: A suggestion - return the NEST and get an Ecobee. It's a much more sophisticated device with remote temp sensors and some nice apps.
WRT the 24VAC needed to power, Ecobee comes with an adapter for your basement equipment to put the 24VAC on your existing wiring to power the Ecobee.  You don't need it if you have a "blue" 24VAC, but it's very cool theway they did it.
Note your setup indicates (via the RH, RC, and Orange) that your heat/cool switch can change the furnace mode via the thermostat. I know Ecobee can't do the auto-switchover function and I doubt Next can either - you're going to have to do the the RH RC connection in your control panel to swtich over to call for heat/call for cool.


Creating result groups in R, using each element once (combination without repetition)

Question: I have a dataset of 6 individuals: A,B,C,D,E,F
I want to group these into two groups of three individuals and have done so with the combn function in R:
m <- combn(n, 3)
This gives me all 20 possible groups where individuals occur in multiple groups. From this set of groups I then went to find all possible combinations of results, where each individual can only be used once.
I would like to do this using combinations without repetition:
C(n,r) = n! / r!(n-r)! and would therefore get 10 results that would look like this:

abc + def
abd + cef
abe + cdf
abf + cde
acd + bef
ace + bdf
acf + bde
ade + bcf
adf + bce
aef + bcd

I am not sure how to code this in R, from the list of groups that I have generated.
Edit: to generate the dataset I am using I have used the following code:
individuals <- c("a","b","c","d","e","f")
n <- length(individuals)
x <- 3
comb = function(n, x) {
  factorial(n) / factorial(n-x) / factorial(x)
}
comb(n,x)
(m <- combn(n, 3))
numbers <- m
letters <- individuals
for (i in 1:length(numbers)) {
  m[i] <- letters[numbers[i]]
}

Comment: I have added it to the question now!
Comment: I am expecting there to be 10 combinations of two groups as a result. So here the plus just represents the two groups that I would expect to get for that combination. Thank you.
Comment: Can you provide a minimal and reproducible data set from which one could provide an answer?
Comment: Thanks for your reply. Just now I am using a test dataset which I am generating as below:
'individuals <- c("a","b","c","d","e","f")
n <- length(individuals)
x <- 3
comb = function(n, x) {
  factorial(n) / factorial(n-x) / factorial(x)
}
comb(n,x)
(m <- combn(n, 3))
numbers <- m
letters <- individuals
for (i in 1:length(numbers)) {
  m[i] <- letters[numbers[i]]
}'
Comment: Please add that to the question rather than in the comment seciton
Comment: What do you mean by `+` in your expected output? Are there values attached to each groups (e.g. "abc")?
Comment: Does this answer your question? [Create Combinations in R by Groups](https://stackoverflow.com/questions/57732672/create-combinations-in-r-by-groups)
Answer: In base R:

Create combnations of 3 letters and store it in a list (asplit)
Create new combnations of 2 groups (of 3 letters)
Filter the list to only keep combinations where the both parts have no element in common

individuals <- c("a","b","c","d","e","f")
combn(individuals, 3, simplify = FALSE) |>
  combn(m = 2, simplify = FALSE) |>
  Filter(f = \(x) !any(x[[1]] %in% x[[2]]))

output
[[1]]
[[1]][[1]]
[1] "a" "b" "c"

[[1]][[2]]
[1] "d" "e" "f"

[[2]]
[[2]][[1]]
[1] "a" "b" "d"

[[2]][[2]]
[1] "c" "e" "f"

[[3]]
[[3]][[1]]
[1] "a" "b" "e"

[[3]][[2]]
[1] "c" "d" "f"

[[4]]
[[4]][[1]]
[1] "a" "b" "f"

[[4]][[2]]
[1] "c" "d" "e"

[[5]]
[[5]][[1]]
[1] "a" "c" "d"

[[5]][[2]]
[1] "b" "e" "f"

[[6]]
[[6]][[1]]
[1] "a" "c" "e"

[[6]][[2]]
[1] "b" "d" "f"

[[7]]
[[7]][[1]]
[1] "a" "c" "f"

[[7]][[2]]
[1] "b" "d" "e"

[[8]]
[[8]][[1]]
[1] "a" "d" "e"

[[8]][[2]]
[1] "b" "c" "f"

[[9]]
[[9]][[1]]
[1] "a" "d" "f"

[[9]][[2]]
[1] "b" "c" "e"

[[10]]
[[10]][[1]]
[1] "a" "e" "f"

[[10]][[2]]
[1] "b" "c" "d"

Comment: Of course, much more consistent :) Not sure how my answer scale with multiple groups (here 2) and much more combinations
Comment: This has fixed it. Thank you!!
Comment: Why the call to `asplit`? Can't you simply use `simplify = FALSE` in the first `combn` as you did in the next one? Also, this could be a nice addition to the _more canonical_ question [Create Combinations in R by Groups](https://stackoverflow.com/q/57732672/4408538)


What is this thing I found in my ceiling fan?

Question: Does anyone know what this is? I found it in one of my ceiling fans. It failed which caused the lights to stop working, but I removed it and now everything works fine. It was on the switched light leg, and had a common going to it
Comment: It's a wattage limiter. See this: https://diy.stackexchange.com/q/1511/18078
Comment: Looks like a ballast.
Comment: check the parts catalog for your fan
Answer: "Hunter" is the fan manufacturer. I haven't been able to find the model number or part number imprinted here on their website; there may be another model number somewhere on the fan that you could look up.
Given that it says "Output 120V~300W Tungsten", I am guessing that this is intended to control the fan's light fixture (Tungsten referring to old-style incandescent bulbs, and 300W being a reasonable power draw for a set of four 75W bulbs of that sort.) At a wild guess, I'd suspect that it's a remote control relay or dimmer. The fact that bypassing it enabled the lights tends to confirm this.
If so... It may not have "failed", it might just have been dimmed/switched off. Do you have the remote for this fan? If so, did you try operating that before you removed this part, making sure the remote had new batteries?
If it really has failed, you'd need to talk to Hunter to make sure what it actually is and decide whether you need a replacement.


Find the absolute extrema by Lagrange multipliers

Question: Find the absolute extrema for the function $g(x,y)=e^{x^2}-y^2$ on the unit disk $D$ given by:
$D=\{(x,y)|x^2+y^2\le1\}$. Do this by first finding all critical points of and classifying them, then use Lagrange
multipliers to find maximums or minimums on the boundary of the disk. The absolute extrema will be the largest and
smallest of these points' values.
Answer: Setting $f(x,y)=x^2+y^2-1$. We want to maximize and minimize the function $g(x,y)=e^{x^2}-y^2$ subject to the side condition $f(x,y)=0$. The gradients are  $
\nabla g\left( {x,y} \right) = 2xe^{x^2 } {\bf{i}} - 2y{\bf{j}}$ and
$\nabla f\left( {x,y} \right) = 2x{\bf{i}} + 2y{\bf{j}}$. Use the cross-product formula of Lagrange $\nabla g \times \nabla f=0$ which equivalent to write $$
\frac{{\partial g}}{{\partial x}}\frac{{\partial f}}{{\partial y}} - \frac{{\partial g}}{{\partial y}}\frac{{\partial f}}{{\partial x}} = 0.$$
So that we have $$
\frac{{\partial g}}{{\partial x}}\frac{{\partial f}}{{\partial y}} - \frac{{\partial g}}{{\partial y}}\frac{{\partial f}}{{\partial x}} = \left( {2xe^{x^2 } } \right)\left( {2y} \right) - \left( { - 2y} \right)\left( {2x} \right) = 4xye^{x^2 }  + 4xy = 0
$$
which holds iff $x=0$ or $y=0$. In case $x=0$, from the side condition $x^2+y^2=1$ so that $y=\pm1$. Similarly, in case $y=0$, from the side condition we get $x=\pm1$. Therefore, the point under consideration are $(0,-1),(0,1),(-1,0),(1,0)$. At first two points $f$ takes on the value $0$ and at the last two points $f$ takes on the value $e$. Hence, the first is a minimum and the second is a maximum.
Answer: The function $ \ z \ = \ g(x , \ y) \ = \ e^{x^2} - \ y^2 \ $ , because the coordinate variables only appear "squared", has symmetry about the $ \ z-$ axis [if $ \ (x, \ y, \ z ) \ $ is on the surface, so is $ \ (-x, \ -y, \ z ) \ $ ] .  So we can limit ourselves to examining the portion of the surface for which the projection onto the $ \ xy-$ plane is the first-quadrant portion of the unit disk.
I won't go through all of the more usual "Lagrange-multiplier calculation here, since much of it doesn't differ  from what mwomath has already done:  the "Lagrange equations" are
$$2 \ x \ e^{x^2} \ = \ \lambda \ \cdot \ 2 \ x \ \ , \ \ -2 \ y \ = \ \lambda \ \cdot \ 2 \ y \  $$
$$ \Rightarrow \ \  2 \ x \ ( \lambda \ - \ e^{x^2}) \ = \ 0 \ \ , \ \ 2 \ y \ (1 \ + \ \lambda) \ = \ 0 $$
$$ \Rightarrow \ \ x \ = \ 0 \ , \ y \ = \ 0 \ , \ \ \text{or} \ \ \lambda \ = \ e^{x^2} \ = \ -1 \ \ , $$
the last of these results offering no solution for $ \ x \ $ .  Any critical points of $ \ g(x , \ y) \ $ therefore lie on the coordinate axes.  Thus the only interior point of the disk which is a critical point is where the axes intersect each other, at the origin $ \ (0, \ 0) \ $ .  The "concavity index" tell us
$$ D \ \vert_{(0,0)} \ = \ [ \ g_{xx} \ g_{yy} \ - \ g_{xy}^2 \ ] \  \vert_{(0,0)} \ = \ [ \ ( 2 \ + \ 4 \ x ) \ e^{x^2} \ \cdot \ (-2) \ - \ 0^2 \ ] \ \vert_{(0,0)} \ = \ -4 \ \ .  $$
So the point $ \ ( 0, \ 0, \ 1 ) \ $ on the surface is a saddle point.  We might have anticipated this conclusion by noting that $  \ g(x , \ 0) \ = \ e^{x^2}  \ $ and $  \ g(0 , \ y) \  = \ 1 - y^2 \ $ , so the cross-sectional curves along the coordinate axes have oppositely-directed concavities.  This behavior of the function surface produces a saddle-point at their intersection.
At this point, we may invoke the the symmetries of the surface and those cross-sectional curves to observe that  $  \ g(x , \ 0) \ $ increases to a maximum on the unit circle at $   \ g(1 , \ 0) \ = \ e \ $ (and so also for  $   \ g(-1 , \ 0) \ $ ) and that  $  \ g(0 , \ y) \ $ decreases to a minimum at $   \ g(0 , \ 1) \ = \ 0 \ $ (and likewise at $   \ g(0 , \ -1)  \ $ ) .

It remains to check for critical points on the unit circle itself. It suffices to search along the first quadrant using $ \ y^2 \ = \ 1 \ - \ x^2 \ $ and $  \ g(x , \ y) \ \vert_{\partial D} \ = \ e^{x^2} +  \ x^2 - 1 \ $ .  So a critical point on the circle must satisfy $ \ 2 \ x \ e^{x^2} \ + \ 2 \ x \ = \ 0  $ , which only occurs for $ \ x \ = \ 0 \ $ (which we've already dealt with), so there are no other critical points on the unit circle or the unit disk.
A question of possible interest is why this search didn't pick out the maxima at $ \ (\pm 1, \ 0, \ e) \ $ .  The function $ \ e^{x^2} +  \ x^2 - 1 \ $ that we used is always "concave upward", so its derivative is not zero at $ \ x \ = \ \pm 1 \ $ ; we are forced to check these "endpoints" separately.
EDIT [1/27] --  (I delayed adding this part because I wasn't satisfied with part of the argument.)  This can also be analyzed using polar coordinates. The function becomes
$$ \ g(r, \ \theta) \ \ =  \ \ e^{r^2 \cos^2 \theta} \ - \ r^2 \ \sin^2 \theta \ \ = \ \ e^{r^2 \cos^2 \theta} \ - \ r^2 \ \cos^2 \theta \ + \ r^2 \ \ . $$
On a ray $ \ \theta \ = \ \theta_0 \ $  extending from the origin, the radial derivative is
$$ \frac{dg}{dr} \ \vert_{\theta_0} \ = \ 2 \ r \ \cos^2 \theta_0 \ e^{r^2 \cos^2 \theta_0} \ - \ 2 \ r \ \cos^2 \theta_0 \ + \ 2 \ r $$ $$ = \ \ 2 \ r \ \left[ \ \cos^2 \theta_0 \ (e^{r^2 \cos^2 \theta_0} \ - \  1 ) \ + \ 1 \ \right] \ \ . $$
The factor $ \ e^{r^2 \cos^2 \theta_0} \ $ is never less than 1 , so the factor in parentheses is non-negative, making the entire factor in brackets greater than or equal to 1 .  So the radial derivative can only be zero for $ \ r \ = \ \ 0 \ $ , indicating that there is only one critical point in the interior of the disk.
Out on the unit circle, $ \ r \ = \ 1 \ $ , the function is  $ \ g(1, \ \theta) \ \ =  \ \ e^{\cos^2 \theta} \ -  \ \cos^2 \theta \ + \ 1 \ $ , for which the angular derivative is
$$ \frac{dg}{d \theta} \ \vert_{r = 1} \ = \ - 2 \ \cos \theta \ \sin \theta \ e^{ \cos^2 \theta} \ + \ 2 \ \cos \theta \ \sin \theta \ \ = \ \ \sin \ 2 \theta \ ( 1 \ - \  e^{\cos^2 \theta}  ) \ \ . $$
In the first quadrant, the factor in parentheses is zero at $ \ \theta \ = \ \frac{\pi}{2} \ $  and $ \ \sin \ 2 \theta \ $ is zero for $ \ \theta \ = \ 0 \ , \ \frac{\pi}{2} \ $ .  So we recover the result found above that the critical points on the unit circle lie at the intersections with the coordinate axes.
[Working with Lagrange multipliers here will lead to the same conclusion.]


Using Python to extract surrounding characters of strings that appear multiple times in text

Question: I have this text:

"At vero eos et accusamus et iusto valor maximo odio dignissimos
  ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti
  quos dolores et quas molestias excepturi sint occaecati cupiditate non
  provident, similique sunt in culpa qui officia deserunt mollitia
  animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis
  est et expedita distinctio. Nam libero tempore, cum soluta nobis est
  eligendi optio cumque nihil impedit quo minus id quod maxime placeat
  facere possimus, omnis voluptas assumenda est, omnis dolor
  repellendus. Temporibus valor maximo autem quibusdam et aut
  officiis debitis aut rerum necessitatibus saepe eveniet ut et
  voluptates repudiandae sint et molestiae non recusandae. Itaque earum
  rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus
  maiores alias consequatur aut perferendis doloribus asperiores
  repellat."

Note that the string

"valor maximo"

appears two times.
I want to get the previous and next 50 characters from each of them.
The result should contain these strings:
"At vero eos et accusamus et iusto"
" odio dignissimos ducimus qui blanditiis praesenti"
"ssumenda est, omnis dolor repellendus. Temporibus "
"autem quibusdam et aut officiis debitis aut rerum "

Could be a list, dictionary, plane texts, whatever. How can I achieve this?
Comment: @Pedro will it work for multiple occurencies? If yes, could you post an answer?
Comment: Are you looking for specifically strings surrounding `valor maximo`, or all strings that repeat in the text?
Comment: What is the minimum length of the repeated string? Is it at least two words? (For example the string `"et"` appears multiple times in the text, but not in the desired result)
Comment: @Recursing 4 characters
Comment: Use some regex like `"(.{0,50}(valor maximo).{0,50})"`.
Comment: I will figure it out in a minute
Comment: strings surrounding valor maximo, in every occurence of valor maximo
Answer: I guess this will do:
import re
keyword='valor maximo'
text = """At vero eos et accusamus et iusto valor maximo odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus valor maximo autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."""
matches = re.findall('(.{0,50}(%s).{0,50})' % keyword, text, re.DOTALL)
print(sum([match.split(keyword) for match, keyword in matches], []))

The general function would be
def get_matches(text, keyword, size):
    matches = re.findall('(.{0,%d}(%s).{0,%d})' % (size, keyword, size), text, re.DOTALL)
    return sum([match.split(keyword) for match, keyword in matches], [])

Comment: Apparently you should change "string" by "keyword", right?
Comment: My output was `['At vero eos et accusamus et iusto ', ' odio dignissimos ducimus qui blanditiis praesenti', 'ssumenda est, omnis dolor repellendus. Temporibus ', ' autem quibusdam et aut officiis debitis aut rerum']`
Answer: For a non regex solution, use
def find_searchterm(word_list, searchterm, n_hood):
    results = []
    for i, _ in enumerate(word_list):
        if word_list[i:i + len(searchterm)] == searchterm:
            results.append(word_list[max(0, i - n_hood):min(i + n_hood + len(searchterm), len(word_list))])
    return results

usage:
word_list = "At vero eos et accusamus et iusto valor maximo odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus valor maximo autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.".split(" ")

searchterm = "valor maximo".split(" ")
n_hood = 50

res = find_searchterm(word_list, searchterm, n_hood)

print(res)


Is Ubuntu compatible with MacBooks?

Question: Is it possible to install and run Ubuntu on a MacBook?
Comment: To find out boot from a live CD.
Comment: Some of my friends use Ubuntu on MacBooks. No problems AFAICT.
Answer: Yes! I am in fact typing this from a MBP 7.1 (where everything except for bluetooth works) :-)
There are comprehensive instructions on the help wiki.
Answer: Yes! And it's getting better! Yesterday I downloaded an optimized official version for the Mac of Natty Alpha1. The page doesn't exists now, but I think Canonical is going to do the same for the Alpha2! :)
Answer: Yes, even now the Precise Pangolin adds more hardware compatibility.
the link:
http://cdimage.ubuntu.com/daily-live/current/
worth a spin, mate^^.

Is Ubuntu compatible with MacBooks?


Advice On Framing For Enlarged Window (and building temporary support wall)

Question: I'm hoping to enlarge a window in an exterior wall on my house. It's a gable end wall on the 1st floor of a 1.5 story house (attic space above). The joists above and below the room (and trusses of the roof) run parallel to the exterior wall (see photo below, red is new rough opening, blue are the floor joists, black is the framing).

The 38" existing rough opening for the window will be expanded to about 90".
I'm planning to:

Remove the moulding
Cut out the drywall
Remove the existing window and window framing
Cut the center out of the existing studs that are in the way (leaving some at the top and bottom for crippler studs)
Add in jack studs next to existing studs on the outside of the R.O.
Add my header (2x6's) and sill
Cut out exterior wall
Install new window

My first question is: does that sound about right?
Second, I'm wondering if I need to build a temporary wall to hold the weight of the house while the existing window faming is removed. It's a gable end wall so not sure it's carrying much weight. But if I do need a temporary wall, how would I build it? (It seems like building it parallel to the wall would just transfer the weight onto a single joist in above / below as it'd be parallel to the joists. So would I build 2 temp walls perpendicular to the wall, build them at an angle, other options?)
I don't have much experience with this all, so sorry if I made any mistakes. Thanks!
Answer: That sounds about right, except that 2x6 isn't adequate for a span of over seven feet. Even though it's not strictly load-bearing, it needs to robustly withstand sag so as not to damage the window. 2x8 is more appropriate, and 2x10 is better. If nothing else it gives more lateral stability.
You didn't explicitly mention king studs (though they're in your drawing), so I'll mention their importance. They provide critical rigidity between the top and bottom wall plates for the header. Don't be afraid to double them for that long span. Face nail into the header before adding second ones.
Whether you need a temporary wall partly depends on the nuances of the wall and roof system above:

What type of sheathing is on the wall? This can provide adequate shear support.
Is there any center bearing for the roof, such as a ridge beam? I think I'm seeing a hand-framed roof and not manufactured trusses.
Is there anything above such as a heavy window?

I would analyze the situation, and if none of those factors seem concerning I'd take the existing window framing out and assess settling. Take an initial measurement to the wall top plate and see if anything moves as you remove studs. If nothing is happening, carry on. Try to minimize human activity above. It should be fine. If you need to pause the project for more than say overnight, stick a couple temporary studs in there.
If anything does settle and you need to get it back in place, a common screw or bottle jack should do, or you may be able to bash a leg in to wedge it back up.
Answer: I had a contractor do this same setup in my place and he did not construct a temporary bracing wall.  I dont even know how you could build one even if you wanted to given that all the beams are running pararell to the wall you want are cutting into


I'm trying to mount a TV into a brick wall covered by 2"-2.5" of drywall... is this doable?

Question: I'm trying to mount a 39" TV that I have previously mounted (with no issues) into typical wooden studs with an arm mount. The mount uses two vertically oriented 5/16" bolts. After stopping by my local tool rental, I picked up a hammer drill and some lag shields, for which they recommended a 1/2" masonry bit. The bit was obviously too large as I cannot get the lag shield to stay in place.
So now I have a few 5" long 5/16" bolts, 5/16" lag shields, and a brick wall with somewhere between 2.25" and 2.5" of drywall covering it.
Provided that I go get the right (smaller) masonry bit, should the wall support my TV or am I fighting a losing battle? Should I buy even longer 5/16" bolts?
Thanks,
Kevin
Answer: I would bypass the drywall and long screws and flat mount 2x4 to the brick and then attach the TV mount to the studs with 1 1/2 wood screws.  You would cutaway enough drywall to achieve a flat mount.  You might have to add a 1x4 overtop to get the proper flush or slightly proud mounting.


MySQL Convert datetime to UTC UNIX_TIMESTAMP

Question: I'm trying to convert a datetime field, which is set to EST, to a UNIX timestamp. But the catch is, the timestamp should be set to midnight UTC.
For example,
    May 1 2015 would be 1430438400000 (01 May 2015 00:00:00 UTC).
I tried converting first the datetime to UTC, then format it to a 24-hour format, but apparently it didn't work for me. Code below:

UNIX_TIMESTAMP(DATE_FORMAT(DATE(DATE_ADD(rv.created_at,INTERVAL 4 HOUR)),'%Y-%m-%d 00:00:00'))

Can anyone help? Thanks.
UPDATE
I finally got the answer. Putting it here for future reference

FLOOR(UNIX_TIMESTAMP(DATE_SUB(DATE_FORMAT(DATE(rv.created_at),'%Y-%m-%d 00:00:00'),INTERVAL 4 HOUR))*1000)
Comment: Title says `UNIX_TIMESTAMP Converter to UTC` and question states `I'm trying to convert a datetime field` - so which is it? *Didn't work* is the worst possible explanation you can give - include error messages that you get, that helps others help you.
Comment: @N.B. modified the title. and no, there was no error. I just couldn't get the right output, which is a UTC unix timestamp.
Comment: Could [this help](https://stackoverflow.com/questions/11133760/mysql-convert-datetime-to-unix-timestamp)? It looks like your question could be a duplicate.
Answer: Unless I'm not understanding your question this works:
UNIX_TIMESTAMP(DATE_FORMAT(rv.created_at,'%Y-%m-%d 00:00:00'))
Comment: Yes that code works, but I couldn't get the right value. For example, May 20, 2017 should be 1496102400 in unix. But im getting 1496160000 as my result.
Comment: I'm getting May 20, 2017 = 1495252800. See (http://www.unixtimestampconverter.com/)


ASP.NET how to get file name in specific folder on server

Question: I have this website which I am coding in ASP.NET - C#.
My problem is that I have image boxes, but the user can upload images with any name. Now each image box has its own folder, and at any point, there can be only one file in that folder, which is a .JPG file.
the path looks like this:
Server.MapPath("img/home/1/here can be any jpg file with any name eg. whateverPic.jpg")

So, when uploading the file, the name can change at any time... then the problem comes when I want to display the image in the picture box.
All I want to do is to get the file name in folder img/home/1/.... and then I can just set the source of the picturebox to that name.
How can I get that filename in that specific folder?
Comment: Why does each image have it's own folder? Instead you should just place them all in the same folder and store the file name in a database somewhere and retrieve it when necessary.
Comment: Are you looking for [EnumerateFiles](http://msdn.microsoft.com/en-us/library/system.io.directory.enumeratefiles.aspx)?
Comment: because I have my reasons... this is acutally a very huge asp.net website and later I am going to include a slideshow... then the folders will contain more images. but just for now.... anycase
Answer: you can use this to get a list of files in the directory
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");

then just use the file name in the filePaths[0] index
Comment: Yeah, you are totally correct. I don't know where my logic was haha. Thank you:)


how to check how many Sunday is present between two dates in oracle sql

Question: I want to check the number of 'Sundays' present between 2 dates
example,
CREATED_DATE 21-10-23 06:00:00.000000000 PM  SATURDAY
UPDATED_DATE 23-10-23 06:00:00.000000000 PM MONDAY
I want to see how many 'Sundays' are there in between, in this case 1
this is my code, the case statement is to be focused,
SUM(
    CASE
        WHEN EXTRACT(HOUR FROM (UPDATEDDATE - CREATEDDATE)) <= 4   -- hours should be < or = to 4
        AND (
            EXTRACT(DAY FROM (UPDATEDDATE - CREATEDDATE)) -        -- days in between
            (
                SELECT COUNT(*)
                FROM DUAL
                WHERE TO_CHAR(CREATEDDATE + LEVEL, 'D') = '1'      -- is sunday?
                CONNECT BY CREATEDDATE + LEVEL <= UPDATEDDATE      -- checking till the end date
            ) = 0
        )
        THEN 1
        ELSE 0
    END
) AS "0_4",

I have 2 columns
CREATEDDATE  -> 04-11-23 06:00:00.000000000 PM saturday
UPDATEDDATE -> 04-11-23 08:00:00.000000000 PM saturday
I want to check if the hours between the dates is less than 4 or equal and the days between it has 'Sundays', if there is any Sunday I want the count of how many 'Sundays' present and substract if from the number of days between the both dates,
in this case, the hours between 2 dates is,
EXTRACT(HOUR FROM (UPDATEDDATE - CREATEDDATE)) -- 2hrs

and days between 2 dates is,
EXTRACT(DAY FROM (UPDATEDDATE - CREATEDDATE)) -- 0 days

here the condition is not satisfying, and also if there are sundays in between, it is not working, is the code logic is correct or not?, need help. Thank you.
Answer: You do not need to use a row generator to find all the days and can calculate the number of Sundays using the ISO weeks (which is independent of any language or territory settings that you may be using):
SELECT created_date,
       updated_date,
       -- Number of Sundays in the start week
       CASE
       WHEN TRUNC(created_date) - TRUNC(created_date, 'IW') <= 6 -- Sunday
       THEN 1
       END
       +
       -- Number of full weeks
       (TRUNC(updated_date, 'IW') - TRUNC(created_date, 'IW')) / 7
       -- Do not double count the first week
       - 1
       +
       -- Number of Sundays in the end week
       CASE
       WHEN TRUNC(updated_date) - TRUNC(updated_date, 'IW') < 6 -- Sunday
       THEN 0
       ELSE 1
       END
       AS number_of_sundays
FROM   table_name

Which, for the sample data:
CREATE TABLE table_name (created_date, updated_date) AS
  SELECT TIMESTAMP '2023-10-21 18:00:00.000000000',
         TIMESTAMP '2023-10-23 20:00:00.000000000'
  FROM   DUAL
UNION ALL
  SELECT TIMESTAMP '2023-10-21 20:00:00.000000000',
         TIMESTAMP '2023-10-22 04:00:00.000000000'
  FROM   DUAL;

Outputs:

CREATED_DATE
UPDATED_DATE
NUMBER_OF_SUNDAYS

2023-10-21 18:00:00.000000000
2023-10-23 20:00:00.000000000
1

2023-10-21 20:00:00.000000000
2023-10-22 04:00:00.000000000
1

If you want to find the difference between two timestamps excluding Sundays then you also need to consider that you may not have a complete Sunday period and can use:
SELECT created_date,
       updated_date,
       updated_date
       - created_date
       - (
           -- Time on Sundays in the start week
           LEAST(
             TRUNC(created_date, 'IW') + INTERVAL '7' DAY - created_date,
             INTERVAL '1' DAY
           )
           +
           -- Sundays in the full weeks
           (
             TRUNC(updated_date, 'IW') - INTERVAL '7' DAY - TRUNC(created_date, 'IW')
           ) / 7 * INTERVAL '1' DAY
           +
           -- Time on Sunday in the last week
           GREATEST(
             updated_date - TRUNC(updated_date, 'IW') - INTERVAL '6' DAY,
             INTERVAL '0' DAY
           )
         )
       AS time_difference_exclude_sunday
FROM   table_name

Which, for the sample data, outputs:

CREATED_DATE
UPDATED_DATE
TIME_DIFFERENCE_EXCLUDE_SUNDAY

2023-10-21 18:00:00.000000000
2023-10-23 20:00:00.000000000
+000000001 02:00:00.000000000

2023-10-21 20:00:00.000000000
2023-10-22 04:00:00.000000000
+000000000 04:00:00.000000000

If you want to filter the rows to only show those when there are 4 or less hours between the created and updated times then you can use:
SELECT *
FROM   table_name
WHERE  updated_date
       - created_date
       - (
           -- Time on Sundays in the start week
           LEAST(
             TRUNC(created_date, 'IW') + INTERVAL '7' DAY - created_date,
             INTERVAL '1' DAY
           )
           +
           -- Sundays in the full weeks
           (
             TRUNC(updated_date, 'IW') - INTERVAL '7' DAY - TRUNC(created_date, 'IW')
           ) / 7 * INTERVAL '1' DAY
           +
           -- Time on Sunday in the last week
           GREATEST(
             updated_date - TRUNC(updated_date, 'IW') - INTERVAL '6' DAY,
             INTERVAL '0' DAY
           )
         )
      <= INTERVAL '4' HOUR;

Outputs:

CREATED_DATE
UPDATED_DATE

2023-10-21 20:00:00.000000000
2023-10-22 04:00:00.000000000

fiddle

As for your question

is the code logic is correct or not?

No, it is not.
If you have the dates '2023-10-21 20:00:00.000000000' and '2023-10-22 00:00:00.000000000' so that the last day is a Sunday and the time component of updated_date is earlier in the day than the time component of the created_date then the check CREATEDDATE + LEVEL <= UPDATEDDATE will skip the final Sunday.
It also does not consider fractions of Sundays.
Comment: sir logic was right, but i'm ashamed to say its difficult to grasp the logic well, i also want to exclude the saturdays and list of particular days ( example public holidays like christmas) and exclude those days between the createddate and updateddate and give out the remaining time, i tried so many ways, but still stuck with wrong results, will you be able to show how its done sir ?
Comment: @ClintonHadrian See https://stackoverflow.com/a/43633234/1509264


Quick Release Pin spring mechanism

Question: The kind of quick-release pin shown in the picture has a cap with an interior thread so it can be removed from the pin which has an exterior thread, revealing a center rod that extends axially down through the pin. My question is this:  is the center rod a single piece that reaches down to the balls to cause them to protrude from the surface of the pin, or does that rod consist of two pieces, a long rod and a very short piece abutting it at the bottom that forces the balls outward when the center rod is pushed down into the pin?
The DIY connection, I want to make a cement mixer's barrel easy to remove from the motor shaft so I can power-wash the inside after using it. The motor isn't supposed to get wet but has no protection against water ingress. The unit ships with a large 12mm diameter pin and a cotter pin.

P.S. If it weren't for the fact that the drum is rotating, and over the course of the 360 degree sweep there are some pieces of the motor mount that are in the way if the clip has twisted slightly, these clips would work fine.  I mangled one when trying them out for this purpose.
Comment: I don't understand how the internal construction of the center pin influences the need to remove the mixer bucket for cleaning. Perhaps you could clarify how the center pin construction is important?
Comment: A better question showing how the barrel is mounted, might get an answer if that type of pin will work.  Those pins are just for holding, they do not provide any tension/tightest to the mounting.
Comment: @Crip659: unfortunately not for this mixer design.  I've tried the kind of pin you're suggesting, but it twists in place and gets jammed. I'm confident that this quick release type of pin will work better than that, though it's not as simple as I'd like. I do take you point about the mess.
Comment: It's a well-formulated question, but who can say? That's a design/engineering thing that almost no one has personal insight into. I'd _assume_ a single pin with a concentric spring, but....
Comment: @Triplefault:  I was trying to learn if the pin I received in the mail was the way it was by design or as the result of damage enroute, possibly in sorting equipment at USPS. The manila envelope the pin was shipped in was quite mangled.  The pin had a rod that consisted of two pieces, a long piece and a very short piece down near the balls. But I think the rod had been snapped where its diameter narrows.  The spring pin was jammed and could not be depressed.
Comment: @crip659 The mixing drum/barrel has a cylindrical piece at its base (imagine a short length of 75mm Ø metal pipe) and that has a 12mm Ø hole drilled on opposite sides of it.  This "pipe" fits over the motor spindle which has a matching O.D and matching 12mm holes.  Instead of securing the barrel to the motor spindle with a semi-permanent 12 mm Ø bolt with a small hole drilled through it for a cotter pin, I would use one of these quick-release pins. The spring-mechanism is basically an improvement over the cotter pin, which is a pain to remove with needle-nose pliers each day.
Comment: Cotter pins, the ones you bend over are one time use.  There are spring pins/clips that do the same job and are the proper pins for what you want.  You just push one side into the bolt/pin and the other side wraps around the pin to hold it.  For a messy job like cement mixing, you want to keep it as simple as possible.  Pulling a pin by hand is much simpler than depending on springs/rods to release balls.
Comment: The usual name the clips I was talking about are R-clips.  Mainly used on hitch pins.
Answer: The common way that these work is that the center shaft has an indentation that the balls can move into when the center pin is pressed.  The center pin is a solid rod with an area that is a smaller diameter.  When the pin is in the "locked" position, the balls sit against the large diameter of the pin.  When the pin is pressed, the balls sit against the smaller diameter and can move inwards.
Believe it or not, I actually found a YouTube video of how these work, complete with a 3D printed cutaway.  The balls are white on the right end, and the grey shaft sits between them  you can see the indentation to the left of the balls.

https://www.youtube.com/watch?v=GPmNklsSE7w
Of course, every manufacturer is free to make things the way they want, but having a single piece rod is generally going to be less complicated and therefore less expensive than two pieces, so someone would need a good reason to deviate from this basic, proven design.
Comment: Thanks for a great answer. It is as I thought. The one I bought on a bidding site arrived with an immovable spring rod and when I was finally able to pull that rod out, a second smaller piece fell out. I think it must have suffered some mishap enroute, perhaps in the USPS sorting equipment. It was shipped from overseas in a small manila envelope with a bit of bubble-wrap.
Comment: There's a lot of clever things in that design, not least being the combination of cross-drill and groove to seat the balls (albeit sacrificing a bit of strength). If the "handle" was threaded and secured with Locktite or similar it would be very difficult to work out the internal arrangement.

Quick Release Pin spring mechanism


Getting Ubuntu working properly on MSI GE62 6QF

Question: I recently bought na laptop MSI GE62 6QF (http://www.msi.com/product/notebook/GE62-6QF-Apache-Pro.html) with i7 6700 processor and NVIDIA GTX970M \ Intel 530 graphics.
I have Windows 10 installed but it's just for games, I am generally Linux user, so wanted to install Ubuntu MATE 15.10 on second ssd hard drive. And here the story begins: first I could not even launch the live CD to install it, after some research I added "nomodeset" kernel option in GRUB and was able to sucessfuly install it. After installation I had to use "nomodeset" option to launch it, otherwise it just hangs. But with that option system is very laggy, windows are rendered forever (because nouveau driver id kind of disabled).
So I wanted to install nvidia drivers, first i installed 352 NVIDIA drivers from Additional Drivers menu. After installation and reboot system is very fast but drivers does not work properly:

I could not get Compiz to work, I checked "glxinfo" command and here is the output:

name of display: :0.0 Xlib:  extension "GLX" missing on display
  ":0.0". Xlib:  extension "GLX" missing on display ":0.0". Xlib:
  extension "GLX" missing on display ":0.0". Xlib:  extension "GLX"
  missing on display ":0.0". Xlib:  extension "GLX" missing on display
  ":0.0". Xlib:  extension "GLX" missing on display ":0.0". Xlib:
  extension "GLX" missing on display ":0.0". Error: couldn't find RGB
  GLX visual or fbconfig Xlib:  extension "GLX" missing on display
  ":0.0". Xlib:  extension "GLX" missing on display ":0.0".
Xlib:  extension "GLX" missing on display ":0.0". Xlib:  extension
  "GLX" missing on display ":0.0". Xlib:  extension "GLX" missing on
  display ":0.0". Xlib:  extension "GLX" missing on display ":0.0".
  Xlib:  extension "GLX" missing on display ":0.0". Xlib:  extension
  "GLX" missing on display ":0.0".

The other thing is when I try to launch Nvidia Settings from command line I get:

Xlib:  extension "GLX" missing on display ":0.0".
  ** Message: PRIME: No offloading required. Abort
  ** Message: PRIME: is it supported? no
ERROR: nvidia-settings could not find the registry key file. This file
  should
         have been installed along with this driver at
         /usr/share/nvidia/nvidia-application-profiles-key-documentation. The
         application profiles will continue to work, but values cannot be
         prepopulated or validated, and will not be listed in the help text.
         Please see the README for possible values and descriptions.
  And there are just 2 options in window that is showed "Application profiles" and "nvidia-settings configuration"

I tried everything:

Installing newer 355 drivers using

apt-get install nvidia-355 nvidia-prime

Installing newer 4.3 RC7 kernel
Installing bumblebee
Trying nvidia-xconfig
Modifing xorg configuration manually.
Install other distrubution like Antergos - with similar issues.
Adding i915.preliminary_hw_support=1 kernel option.

I have no idea to to proceed with that, My /var/log/Xorg.0.log file:
http://pastebin.com/e4wLaefT
Please let me know if you have any suggestions what should I check or do.
Thanks in advance.
Answer: OK, I managed to get 15.10 to work flawlessly on the same Skylake Ge62 (i6700HQ + GTX970m).
It took two clean installs and a ton of hard resets... and in the end I'm not exactly sure which step made it work, but here's what I did:

disable FastBoot (both in UEFI and Windows 10), SecureBoot and SpeedStep (the latter two shouldn't matter but it won't hurt to disable them anyway)
install with nomodeset boot option
reboot and got an instant hangup
reboot again with nomodeset
update everything to get the latest stable kernel (by now 4.2.19, stock 4.2.12 works as well)
install latest Intel graphics stack (https://01.org/linuxgraphics/downloads)
install NVidia properietary driver. Beware - after this nomodeset may not work again so be prepared for a clean install if something goes wrong.
reboot. It will either hang up instantly or it will boot normally. It hung up in my case.

The thing now is to get it to boot once so the drivers can be configured by X server
-do NOT add i915.preliminary_hw_support as it's not needed anymore
-from now on delete quiet and splash from boot options every time you add something there to see what errors you get.
-firstly try intel_idle.max_cstate=1 as a boot option
-if that hangs up try acpi=noirq or acpi=hd or acpi=off
The last one gave me a first proper boot. After a restart it didn't boot again giving bumblebee errors.

this time boot with intel_idle.max_cstate=1

If it works add this line to grub permanently. This way you will get a stable system using i915. For now I didn't try to force it to use nvidia.
Hope it helps.
regards
Comment: I just tried this and looks like i915 is working properly if I add acpi=off, but other things do not work, for example touchpad or some shortcuts. If I add intel_idle.max_cstate=1 all looks good but I am unable to shut down ubuntu properly, it hangs during shutdown process with messages like "kernel BUG: soft lockup - CPU stuck for 23s!" Do you have any ideas how to solve that?
Comment: if `nomodeset` does not work for someone of you just try `nouveau.modeset=0`
Answer: I also encountered CPU lockup errors. Try to boot with only
<code>intel_idle.max_cstateate=1
</code>
Do not disable ACPI anymore. Also try to re-enable SpeedStep in UEFI.
In my case it booted normally and is working ever since. it seems you're almost there so keep trying :)
Comment: Thank you, I don't know what I did differently this time aside using stock ubuntu instead of ubuntu MATE, but it finally works!


Complex numbers - separate real/imaginary parts

Question: $$K(\omega) = \frac{1}{1 + j\omega RC}$$
Uhm...How do I separate the real part from the imaginary part here? :U And how can I find the argument? I mean, if the document I got this formula from is right, the argument should be negative...
Comment: (Damn, I was hoping people would give OP the chance to answer his own question. Oh well, what can I do...)
Comment: You should now be able to answer your own question.
Comment: What if you multiply the top and bottom of your fraction with $1-j\omega RC$?
Comment: Right, thanks! :P
Comment: Actually, I did, just forgot about conjugates, this whole complex numbers thing is quite new for me.
Comment: I had in mind you *posting* an answer to your own question, for rep and whatnot, but I suppose it is too late...
Comment: If you just want a numeric values for a particular values of $\omega$ then use a calculator that handles complex numbers, and use the formula as is. (Don't do algebraic huffing and puffing just for the sake of a dumb machine that only works with reals.)
Answer: If you have $\frac{z_1}{z_2}$ a ratio of complex numbers, multiplying
$$
\frac{z_1}{z_2}\cdot\frac{\overline{z_2}}{\overline{z_2}} = \frac{z_1\overline{z_2}}{z_2\overline{z_2}}
$$
will give you a real denominator ($\overline{z_2}$ is the complex conjugate of $z_2$). Once you do that, you need only write $z_1\overline{z_2} = x + jy$, $x,y\in\Bbb R$, as then
$$
\frac{z_1}{z_2} = \frac{x + jy}{z_2\overline{z_2}} = \frac{x}{z_2\overline{z_2}} + j\frac{y}{z_2\overline{z_2}}.
$$


How can I center this?

Question: I want to center the h1 "log in". I've tried using margin: left but when I use it the button moves also for some reason. I have used justify-content: center; for the container but since I added the button the "log in" h1 has moved and I'm not sure what to do to put it perfectly in the middle again.
https://codepen.io/i-am-programming/pen/gOmydqv

* {
  margin: 0;
  padding: 0;
  font-size: 25px;
  font-family: "Montserrat", sans-serif;
}

body {
  background: url("images/background.jpeg");
  background-size: cover;
}

a {
  text-decoration: none;
  margin-right: 30px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.7);
  padding: 8px;
  transition: 0.3s ease;
}

nav {
  margin-top: 20px;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

a:hover {
  color: black;
  background-color: rgba(255, 255, 255, 0.7);
}

.container {
  display: flex;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 500px;
  height: 450px;
  background-color: rgba(0, 0, 0, 0.7);
  justify-content: center;
}

.login {
  color: white;
  margin-top: 50px;
  font-size: 45px;
}

input {
  height: 30px;
  width: 300px;
  outline: none;
}

.username {
  position: absolute;
  top: 45%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.pass {
  position: absolute;
  top: 65%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.button {
  width: 150px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, 1200%);
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://fonts.googleapis.com/css2?family=Montserrat:wght@200&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>

      Home
      About
      Store
      Contact Us

Log In

      <input type="text" placeholder="Username" class="username" />
      <input type="password" placeholder="Password" class="pass" />
      <input type="button" class="button" value="Submit" />

Answer: add position: absolute; to .login You will probably also need to alter your transform for .button to this:  transform: translate(0%, 1200%);

* {
  margin: 0;
  padding: 0;
  font-size: 25px;
  font-family: "Montserrat", sans-serif;
}

body {
  background: url("images/background.jpeg");
  background-size: cover;
}

a {
  text-decoration: none;
  margin-right: 30px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.7);
  padding: 8px;
  transition: 0.3s ease;
}

nav {
  margin-top: 20px;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

a:hover {
  color: black;
  background-color: rgba(255, 255, 255, 0.7);
}

.container {
  display: flex;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 500px;
  height: 450px;
  background-color: rgba(0, 0, 0, 0.7);
  justify-content: center;
}

.login {
  position: absolute;
  color: white;
  margin-top: 50px;
  font-size: 45px;
}

input {
  height: 30px;
  width: 300px;
  outline: none;
}

.username {
  position: absolute;
  top: 45%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.pass {
  position: absolute;
  top: 65%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.button {
  width: 150px;
  top: 50%;
  left: 50%;
  transform: translate(0%, 1200%);
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      href="https://fonts.googleapis.com/css2?family=Montserrat:wght@200&display=swap"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="styles.css" />
    <title>Document</title>

      Home
      About
      Store
      Contact Us

Log In

      <input type="text" placeholder="Username" class="username" />
      <input type="password" placeholder="Password" class="pass" />
      <input type="button" class="button" value="Submit" />

Answer:

h1 {
  position: absolute;
  top: 0;
  left: 0;
  text-align: center;
  width: 100%;
}

/* or add to .login*/

.login {
  /*...*/
  position: absolute;
  text-align: center;
  width: 100%;
}

How can I center this?