How to make a colorful shadow using css

Question: want to make colorful shadows to buttons using CSS with root color
notes that I know ways on google but I need something special for my web bage
want to be experienced with CSS and sass
Comment: Could you show us code that you have tried?
Answer: Well, we all have different interests and desires in life, and not sure whether what I call beautiful would really be beautiful in your eyes, perhaps this seems simple and beautiful button shadow design.
#1
Sample Html Code

  <button class="button">Submit</button>

Sample CSS styles
.wrap {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.button {
  width: 140px;
  height: 45px;
  font-family: 'Roboto', sans-serif;
  font-size: 11px;
  text-transform: uppercase;
  letter-spacing: 2.5px;
  font-weight: 500;
  color: #000;
  background-color: #fff;
  border: none;
  border-radius: 45px;
  box-shadow: 0px 8px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease 0s;
  cursor: pointer;
  outline: none;
  }

.button:hover {
  background-color: #2EE59D;
  box-shadow: 0px 15px 20px rgba(46, 229, 157, 0.4);
  color: #fff;
  transform: translateY(-7px);
}

Check a live demo here
If you want to make it fancy or better, see more here
#2
Sample badge with simple and good design:
HTML

          GET UP TO

          $10,000

          PER MONTH

          AS A STARTER

CSS
body{background:#ecf0f1;}

a{text-decoration:none;}

.firstLine {
    font-size: 14px;
    font-weight: 200;
}.secondLine {
    font-size: 18px;
    line-height: 36px;
    font-weight: 600;
} .thirdLine {
    font-size: 14px;
    line-height: 32px;
    font-weight: 300;
}.fourthLine {
    font-size: 12px;
    font-weight: 300;
    position: relative;
    top: -10px;
}

.badges {
    position:relative;
    margin:140px auto;
    width:200px;
    height:200px;
    background: white;
    box-shadow: 0px 8px 15px rgba(0, 0, 0, 0.1);
    border-radius:100%;
    color: #552F87;
    line-height: 25px;
    text-align: center;
    text-transform: uppercase;
    font-family: "Open Sans",sans-serif;
    -webkit-animation: 3s ease-in-out 0s normal none infinite running swing;
    -moz-animation: 3s ease-in-out 0s normal none infinite running swing;
    -o-animation: 3s ease-in-out 0s normal none infinite running swing;
    animation: 3s ease-in-out 0s normal none infinite running swing;

    -webkit-transform-origin: 100px -71px;
    -moz-transform-origin: 100px -71px;
    -o-transform-origin: 100px -71px;
    transform-origin: 100px -71px;
}
.badges:after{
    content:'';
    position:absolute;
    top:-70px;left:99px;
    width:2px;height:81px;
    border-radius:0%;
    background:#000;
}

@-webkit-keyframes swing{
    0%{-webkit-transform:rotate(5deg);}
    50%{-webkit-transform:rotate(-5deg);}
    100%{-webkit-transform:rotate(5deg);}
}

@-moz-keyframes swing{
    0%{-moz-transform:rotate(5deg);}
    50%{-moz-transform:rotate(-5deg);}
    100%{-moz-transform:rotate(5deg);}
}

@-o-keyframes swing{
    0%{-o-transform:rotate(5deg);}
    50%{-o-transform:rotate(-5deg);}
    100%{-o-transform:rotate(5deg);}
}

@keyframes swing{
    0%{transform:rotate(5deg);}
    50%{transform:rotate(-5deg);}
    100%{transform:rotate(5deg);}
}

Demo here
Another badge demo here

How to make a colorful shadow using css


My script can't access file at temporary location

Question: I have a html for that asks for username, password and image file.
Then I use this script to upload it to snapchat story:
<?php
$target_dir = "uploads/";
$target_dir = $target_dir . basename( $_FILES["uploadFile"]["name"]);
$uploadOk=1;

if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_dir)) {
    echo "The file ". basename( $_FILES["uploadFile"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}

$user = $_POST['user'];
$pass = $_POST['pass'];
$img = $_FILES["uploadFile"]["tmp_name"];

require_once("src/snapchat.php");
$snapchat = new Snapchat($user, $pass);
$id = $snapchat->upload(Snapchat::MEDIA_IMAGE,file_get_contents($img));
$snapchat->setStory($id, Snapchat::MEDIA_IMAGE, 10);
?>

But it does not work!
It keeps saying:
Warning: file_get_contents(/tmp/phpCO1pki) [function.file-get-contents]: failed to open stream: No such file or directory in /home/u753295385/public_html/run_command.php on line 18

There's probably something I'm forgetting. If you could help me that'd be AWESOME!
Answer: That's because the file is not there any more - you moved it:
if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_dir)) {

This function moves the file from temporary directory somewhere else. So either do not move, or use the target location - $target_dir.
I don't know what Snapchat is, but if you're just using the contents of the file, you don't have to move it at all. Just check for the $_FILES["uploadFile"]["error"] and then pass the temporary name:
$id = $snapchat->upload(Snapchat::MEDIA_IMAGE,file_get_contents($_FILES["uploadFile"]["tmp_name"]));

Comment: Oh, another comment editor... Please post code at external site. Post it before posting the comment. I will not dissapear in few secconds, so there's no hurry.
Comment: I updated my script, now it gives me no error, but doesn´t upload to pic to snapchat either.

(snapchat is an app like instagram etc)
Comment: Well, that's a different problem. I never used it, so I can't help, especially since there's no error. Try to dump the image to the output by `imagepng(imagecreatefromstring(file_get_contents(//path//)))`
Comment: I don't know what that means :(
Comment: That means: Your question was solved. Ask another, after you find out some errors ("It's not working" question will be closed here). Or join some IRC channel where somebody may help you with subsequent problems.
Comment: Hey! it's working, it only uploads jpg though, it wont work when I use PNG.
Is there anyway to only allow jpg or automatically change the extension to jpg?
Comment: Changing extension is pointless. JPG and PNG are diferent way of saving the image. Extension is just part of filename. You can give it `.txt` and it's till an image.
Comment: Ok but when I change the extension from png to jpg it works, it seems to work even if it's just a part of the filename and nothing more.
Comment: Well, somebody is cheating during the check.


Integrating $\int_\Gamma exp(z) \,dz$ along the upper half unit circle directly

Question: Let $\Gamma$ be the upper half of the unit circle $|z| = 1$, directed from $z = 1$ to $z = -1$. One way to evaluate $\int_\Gamma exp(z) \,dz$ is to apply the the Fundamental Theorem of Calculus. Indeed, noting that $exp(z)$ is entire and $exp '(z) = exp(z)$ for all $z \in \mathbb{C}$, we have:
$\int_\Gamma exp(z) \,dz = exp(-1) - exp(1) = \frac{1 - e^2}{e}$.
Alternatively if we parameterise $\Gamma$ as $z(\theta) = e^{i \theta}$, $0 \leq \theta \leq \pi$ and attempt to address the integral directly we have:
$\int_\Gamma exp(z) \,dz = i \int_0^\pi exp(e^{i\theta})e^{i\theta} = i \int_0^\pi e^{cos(\theta)+i\theta}(cos(sin(\theta)) + i sin(sin(\theta)) \,d\theta $.
Is there a way in which we can evaluate this integral simply? If not, is there a better parameterisation that will allow us to evaluate $\int_\Gamma exp(z) \,dz$ without appealing to FToC?
(Note: $exp(x + i y) = e^x(cos(y) + i sin(y))$ denotes the complex exponential function.)
Answer: Starting with $i\int_0^\pi e^{e^{i\theta}}e^{i\theta}d\theta$, let $u=e^{i\theta}$.  Then we have
$$i\int_0^\pi e^{e^{i\theta}}e^{i\theta}d\theta=\int_1^{-1}e^udu=e^{-1}-e.$$
Since $e^z$ is entire, we can deform the contour of integration from the upper half circle of radius 1 in counterclockwise direction to the real axis from 1 to -1.
Answer: You are better off just leaving things alone:
$$\int_{\Gamma} dz \, e^z = i \int_0^{\pi} dt \, e^{i t} \, e^{e^{i t}} $$
Note that, no  matter what the parametrization, we will be using the FToC anyhow.  By expanding the exponentials, you are simply overcomplicating the problem.
Because $e^z$ is analytic, it doesn't matter what parametrization we use.  The answer only depends on the endpoints, thus:
$$e^{-1}-e^1$$


Polynomial Ring of a Field extension

Question: The problem is stated as follows: Let $K$ be a finite field extension of $F$ and consider $P\in K[x]$ monic irreducible. Then, there exists $Q\in K[x]$ such that $PQ\in F[x]$.
This question is essentially asking us to prove that $(P)\cap F[x]\neq\emptyset$, and I'm not sure where to begin if I take a more algebraic route. Another approach would maybe be to take a basis of $K$, i.e. $\{\alpha_1,\dots,\alpha_n\}$. If $P(x)=a_0+a_1x+\dots+a_mx^m$, then there is some formula for the coefficients $a_i=\sum_{k=1}^{n} b_{i_k}\alpha_{i_k}$ where $b_{i_k}\in F$. This will give us that $P(x)=\sum_{i=1}^m\sum_{k=1}^mb_{i_k}\alpha_{i_k}x^i$. I still don't see the proof - any suggestions would be appreciated.
Comment: Consider conjugates of $P(x)$.
Answer: There is a very simple argument (as it doesn't require separability or Galois ideas) – consider the reduction mod $P$ map from $F[X]$ to $K_{d-1}[X]$ (where $d$ is the degree of $P$). It's $F$-linear and for dimensionality reasons it can't be injective. Thus it has a nontrivial kernel and you are done.

Polynomial Ring of a Field extension


Samsung pc suite in ubuntu

Question: is there a good android pc suit in ubuntu?!
I found Odin but it's not what I am looking for, then I thought about samsung kies but it's a windows *.exe I need "wine" to run it!
What to do?
Comment: What's the "Samsung pc suite" or "Android pc suite" supposed to do?
Answer: No, apart from Heimdall, there is no Samsung specific Android pc suite for GNU/Linux.
Depending on what you do need it for, there are a lot of alternatives though. I would use kdeconnect on the Android device and your Ubuntu desktop for sharing notifications,clipboard and files (and a lot more), Syncthing for synchronizing photos in realtime, a caldav, carddav solution for sharing contacts and calendar (I don't use google services for such things). I think you can backup applications to google drive with android itself, though this is not a priority for me. For backing up sms and call logs, you can use sms backup+ on the android device and back them up to gmail or any IMAP server.
Other than that, only link I found to a similar app was qtatb, but it has not been updated since 2014 and I have never tried it.
Comment: "Apart from Odin" There is no Odin for Linux, but there is Heimdall.
Comment: @xangua You are right, I am not that good with nordic gods ;-). Corrected my answer.
Answer: Airdroid
AirDroid is also one of the most advanced android PC suites for Android, Windows, and Mac. You can install the AirDroid desktop version on Mac, Windows and Linux and the android version on your mobile phone which will allow you to connect both the devices wirelessly. You can share all the photos which are present in your mobile phone, transfer the data and do all sorts of stuff with Airdroid.
Comment: I cant see an Airdroid desktop version for linux. Can you provide a link?
Comment: Who downvoted this? He must be a dimwit.
Comment: @Bruni You dont need to download anything on your PC. Install airdroid app in your android phone and go to web.airdroid.com and you can witness the magic.
Comment: interesting. Don't like the idea of this running on a third party server though, but it sure seems convenient. I did not downvote btw.

Samsung pc suite in ubuntu


How do you know what gender your Fennekin is?

Question: So, I am very new to the game, and I really want a female Fennekin, although how do I know the gender? I know for the pickachu it's the tail shape, but no idea about the fennekin. Help?
Comment: Simple: "[*Men are from Mars* (♂), *women are from Venus* (♀).](https://en.wikipedia.org/wiki/Gender_symbol)"
Comment: You can also check out this question on how to get a female starter: https://gaming.stackexchange.com/questions/135903/what-are-the-chances-to-get-a-female-starter-and-is-there-anyway-to-increase-th
Answer: The gender of a Pokemon is displayed in a variety of places throughout the game. The two you'll see most commonly are right next to a Pokemon's name in a battle, or on the Pokemon status screen in the menu.
This picture gives an example of the battle screen:

And this picture gives an example of the Pokemon status screen:

Males have a ♂, while females have a ♀ instead.

Fennekin, like all starter Pokemon, is only generated as female one out of every eight times on average, so it may take some time to find a female one.
Comment: Further explanation, it is about the red (first and second picture) and red (seconds picture) icon. Thingy pointing up, means male. Thingy pointing down, means female. Chespin is male, Fletchling female.


How to stop this leaking spigot?

Question: This spigot leaks only when running, from the handle spindle.  I have never worked on one like this, but I assume the handle needs to be removed with the front screw, then the packing nut needs to be removed.  After that, new packing can be placed on the inside of the packing nut and retightened.  Is this correct?  Is that the type of packing that will be required?
Answer: First, hold the body of the valve still with one wrench, and tighten the packing nut a bit with another wrench. If you can snug it up and stop the leak, while still being able to turn the handle, that's all you need to do.
If that fails, you seem to have the correct idea for repacking. Do remember to turn the water off ahead of this valve or it can get very exciting when you remove the packing nut. Generally the packing (modern) may be white teflon or may be black from graphite additions as you show. It doesn't matter much. Old packing was various other things, depending on how old.
Might want to start with putting penetrating oil on the handle screw, it looks like the typical rusted-in-place likely-to-break screw we see there too often. When you get it out, consider applying anti-seize compound to a replacement, and consider a non-corroding screw for a replacement.

How to stop this leaking spigot?


Surfaces: behavior of Pluricanonical maps

Question: Let $S$ be an algebraic smooth surface (over $\Bbb{C}$).
Suppose we have some fibration $p\colon S\rightarrow C$ onto a smooth curve. Let $f$ be a fiber, a curve, say.
Let $K$ be a canonical divisor on $S$ and assume $K\cdot f=0$. My question is: can we conclude that each $m$-canonical map $\varphi_{mK}\colon S\rightarrow\Bbb{P}^N$, when defined, will contract $f$ to a point ?
Answer: If $|mK|$ is base point free and if $f$ is irreducible, then $\varphi_{mK}(f)$ is a point.
Otherwise, there exists $x$, $y\in f$ s.t. $\varphi_{mK}(x)\neq \varphi_{mK}(y)$. By the definition of $\varphi_{mK}$, it is equivalent to say that there exists $s\in H^0(S,\mathcal{O}_S(mK))$, such that $s(x)=0$ and $s(y)\neq 0$.
Let $D:=div(s)$, then $D$ is an effective divisor, linearly equivalent to $mK$, and satisfying $x\in \operatorname{Supp}(D)$ while $y\notin \operatorname{Supp}(D)$. Therefore $f$ is not a component of $D$ (since $y\notin \operatorname{Supp}(D)$), hence $D\cdot f\geq 1$ (since $D$, $f$ have no components in common and $x\in \operatorname{Supp}(D)\cap f$). So $mK\cdot f=D\cdot f\geq 1$, we get a contradiction.
Answer: One slick way to explain why the answer is yes uses the projection formula. For our purposes the following formulation is enough: if $f: X \rightarrow Y$ is a morphism between smooth projective varieties, $L$ is a line bundle on $Y$, and $C$ is a curve on $X$, then $$f^*L \cdot C = L \cdot f_*C$$ (where $f_*$ denotes the push-forward of cycles, and $\cdot$ is intersection of cycles).
By definition of the morphism $\varphi_L: X \rightarrow \mathbf{P}^n$ associated to a basepoint-free line bundle on a variety $X$, we have $\varphi_L^* \mathcal{O}(1) =L$. So if $C$ is any curve with $L \cdot C =0$, the projection formula gives $(\varphi_L)_*C \cdot \mathcal{O}(1)=0$. But $\mathcal{O}(1)$ has strictly positive degree on any curve in $\mathbf{P}^n$, so the 1-cycle $(\varphi_L)_*(C)$ must be zero: that is, $C$ must be contracted by $\varphi$.
Now just apply this in your case with $L=mK$. (Note that for each integer $m$, the conditions $K \cdot C=0$ and $mK \cdot C=0$ are equivalent.)
Comment: Thank you, this proof is more elegant, though I'll accept the one above, being more elementary.


Possible to trigger javascript animations inside an existing header element?

Question: I have a website with a php header for navigation and a separate element for content.
In the header there is a logo that links to the home page and social network buttons that do what you would expect them to.
So a standard web site.
Is it possible, on a particular page of the site, to treat the header as a background?
Or to put it another way,to have the company logo and the social network button become animated and also move around inside the header? And then fall down the page where they will become interactive.
I can animate objects inside the content element but I'm not sure how to have them overlayed on top of the header.
Thanks for any help.
Answer: Just make sure the header doesn't have overflow hidden and give those elements absolute positioning with a z-index. If the header needs overflow hidden you'l need to move those elements to the body or another parent node that doesn't have overflow hidden before they can appear outside of the header.
Answer: You might want to consider using css3's transform-property (in your case, you'll probably want translate).
That way you can move your elements around freely, ignoring any constraining parent elements.
As an example, applying
<code>transform: translate(10px, 20px);
</code>
on any element, will move it 10px to right, and 20px down.
However you still have to keep an eye on overflow:hidden and z-indices, like Mica Williamson said.


Find directories that DON'T contain a file

Question: Yes, I'm sorting out my music. I've got everything arranged beautifully in the following mantra: /Artist/Album/Track - Artist - Title.ext and if one exists, the cover sits in /Artist/Album/cover.(jpg|png).
I want to scan through all the second-level directories and find the ones that don't have a cover. By second level, I mean I don't care if /Britney Spears/ doesn't have a cover.jpg, but I would care if /Britney Spears/In The Zone/ didn't have one.
Don't worry about the cover-downloading (that's a fun project for me tomorrow) I only care about the glorious bash-fuiness about an inverse-ish find example.
Comment: related: https://serverfault.com/questions/235025/list-directories-not-containing-a-file | https://stackoverflow.com/questions/12873834/list-directories-not-containing-certain-files | https://unix.stackexchange.com/questions/85448/list-all-directories-that-do-not-have-a-file-with-a-given-file-name-inside | https://superuser.com/questions/548476/list-subdirectories-one-level-down-that-do-not-contain-a-certain-file
Comment: for anyone who's interested in downloading the covers that are missing just install https://launchpad.net/coverlovin and replace the -print in @phoibos answer with "-exec ./coverlovin.py {} \;"
Answer: Case 1: You know the exact file name to look for
Use find with test -e your_file to check if a file exists. For example, you look for directories which have no cover.jpg in them:
find base_dir -mindepth 2 -maxdepth 2 -type d '!' -exec test -e "{}/cover.jpg" ';' -print

It's case sensitive though.
Case 2: You want to be more flexible
You're not sure of the case, and the extension might be jPg, png...
find base_dir -mindepth 2 -maxdepth 2 -type d '!' -exec sh -c 'ls -1 "{}"|egrep -i -q "^cover\.(jpg|png)$"' ';' -print

Explanation:

You need to spawn a shell sh for each directory since piping isn't possible when using find
ls -1 "{}" outputs just the filenames of the directory find is currently traversing
egrep (instead of grep) uses extended regular expressions; -i makes the search case insensitive, -q makes it omit any output
"^cover\.(jpg|png)$" is the search pattern. In this example, it matches e.g. cOver.png, Cover.JPG or cover.png. The . must be escaped otherwise it means that it matches any character. ^ marks the start of the line, $ its end

Other search pattern examples for egrep:
Substitute the egrep -i -q "^cover\.(jpg|png)$" part with:

egrep -i -q "cover\.(jpg|png)$" : Also matches cd_cover.png, album_cover.JPG ...
egrep -q "^cover\.(jpg|png)$" : Matches cover.png, cover.jpg, but NOT Cover.jpg (case sensitivity is not turned off)
egrep -iq "^(cover|front)\.jpg$" : matches e.g. front.jpg, Cover.JPG but not Cover.PNG

For more info on this, check out Regular Expressions.
Comment: Absolutely beautiful — with the problem that it's not flexible to pick between cases or different extensions (I tried a wildcard but no-go). I wonder if there's a better alternative to `test`.
Comment: Hmm you can nest the find with this `-exec bash -c '[[ -n $(find "{}" -iname "cover.*") ]]' \;` but that's pretty filthy in terms of optimisation. It does work though.
Comment: I found that you can pass `test` a load of `-o EXPRESSION` for OR queries... eg: `test -e "{}/cover.jpg" -o -e "{}/cover.png"` which is better than doing a full blown search but it's still case sensitive.
Comment: I should note that comparing the performance of this (two tests, per my last comment) against the other two solutions (comm'd find and comm'd globbing) this is by far the slowest (684ms vs 40ms and 50ms respectively)
Comment: The original in-answer solution takes over a second and breaks in circumstances that have `$` in the dir name (Ke$ha, for example).
Comment: Almost downvoted as not working, but then I saw the `- print` at the end. Works beautifully!
Comment: Case 2 is the only thing I could get to work for a situation where I was searching in a directory for subdirectories that did not contain pdf files, and the subdirectory names contained spaces and commas, and the pdf files had unpredictable names so I had to find them with `"*.pdf"`.
Comment: I had no idea you could use -exec as a predicate. That's an awesome trick for other uses, too.
Answer: Simple, it transpires. The following gets a list of directories with the cover and compares that with a list of all the second-level directories. Lines that appear in both "files" are suppressed, leaving a list of directories that need covers.
comm -3 \
    <(find ~/Music/ -iname 'cover.*' -printf '%h\n' | sort -u) \
    <(find ~/Music/ -maxdepth 2 -mindepth 2 -type d | sort) \
| sed 's/^.*Music\///'

Hooray.
Notes:

comm's arguments are as follows:

-1 suppress lines unique to file1
-2 suppress lines unique to file2
-3 suppress lines that appear in both files

comm only takes files, hence the kooky <(...) input method. This pipes the content via a real [temporary] file.
comm needs sorted input or it doesn't work and find does by no means guarantee an order. It also needs to be unique. The first find operation could find multiple files for cover.* so there could be duplicate entries. sort -u quickly ruffles those down to one. The second find is always going to be unique.
dirname is a handy tool for getting a file's dir without resorting to sed (et al).
find and comm are both a bit messy with their output. The final sed is there to clean things up so you're left with Artist/Album. This may or may not be desirable for you.
Comment: your first `find` can possibly be simplified to `find ~/Music/ -iname 'cover.*' -printf '%h\n'`, avoiding the need for `dirname`. though `dirname` is handy elsewhere.
Comment: Thanks @Tom, that is a *lot* faster that forking out everywhere (29ms vs 734ms on my music dir - both "warm" finds)
Answer: This is much nicer to solve with globbing than with find.
$ cd ... # to the directory one level above the album/artist structure

$ echo */*/*.cover   # lists all the covers

$ printf "%s\n" */*/*.cover # lists all the covers, one per line

Now suppose you have no stray files in this nice structure. The current directory contains only artist subdirectories, and those contain only album subdirectories. Then we can do something like this:
$ diff  <(for x in */*/cover.jpg; do echo "$(dirname "$x")" ; done) <(printf "%s\n" */*)

The <(...) syntax is Bash process substitution: it lets you use a command in place of a file argument. It lets you treat the output of a command as a file.  So we can run two programs, and take their diff, without saving their output in temporary files. The diff program thinks it is working with two files, but in fact it's reading from two pipes.
The command that produces the right hand input to diff, printf "%s\n" */*, just lists the album directories. The left hand command iterates through the *.cover paths and prints their directory names.
Test run:
$ find .   # let's see what we have here
.
./a
./a/b
./foo
./foo/bar
./foo/baz
./foo/baz/cover.jpg

$ diff  <(for x in */*/cover.jpg; do echo "$(dirname "$x")" ; done) <(printf "%s\n" */*)
0a1,2
> a/b
> foo/bar

Aha, the a/b and foo/bar directories have no cover.jpg.
There are some broken corner cases, like that by default * expands to itself if it matches nothing. This can be addressed with Bash's set -o nullglob.
Comment: Apologies for the late reply. It's an interesting idea but: covers can be in png and jpb and , wouldn't `comm` be cleaner than `diff`?
Comment: `comm -3 <(printf "%s\n" */*/cover* | sed -r 's/\/[^\/]+$//' | sort -u) <(printf "%s\n" */*)` seems like a sensible compromise without any of `diff`'s fluff. It is, however, a little bit slower than my double-find.
Answer: Let's make it simple and easy to understand.
for dir in /*/*; do
  if [ ! -f $dir/cover.jpg ] && [ ! -f $dir/cover.png ]; then
    echo $dir
  fi
done

Make it one line (note that we need an extra ; in the one-line version):
for dir in /*/*; do if [ ! -f $dir/cover.jpg ] && [ ! -f $dir/cover.png ]; then echo $dir; fi done

Comment: Finally!  No inscrutable `find` incantations, no temporary files, just a simple answer to a simple question.
Answer: ls --color=never */*.txt | sed 's|/.*||' | sort -u -n > withtxt.txt
ls --color=never -d * | sort -u -n > all.txt
diff all.txt withtxt.txt

Will show all directories that do not have txt files in them.


If $S^{2n+1}$ is covering space of $X$, then $X$ is orientable.

Question: Is there any direct way to prove that $n$-manifold is orientable? In AT we can just calculate $n$'th homology group and check whether it's $\mathbb Z$ or $0$. But I want a geometric method, using differential forms. Thanks!
Comment: Are you intending to do any of your homework yourself or have you posted it all?
Comment: Sorry,I have thought these problems for a long time,but I can't find any idea, so I just have to find help...
Comment: Interesting question, btw (one in the title, I mean).
Answer: If you have a nowhere vanishing n-form, then the manifold is orientable.
Comment: But how to construct this n-form?I have an idea:for any deck transformation ,it's free, so degree is 1 ,i.e. keep orientable, then we can construct n-form of X from local n-form of S^(2n+1). Is it right?
Comment: @henry "so degree is 1" -- why not $-1$? (And are you using that sphere is odd, not even dimensional?)
Comment: @ Grigory :Yes ,here I use this condition.


Repairing a boom lamp that keeps falling

Question: I have a boom lamp from CB2 that's about two years old in my living room. The angle between the arm and the stand is adjustable. Unfortunately, the mechanism that holds the lamp up (I'm afraid I don't know the correct term for it, but you can see it below) seems to have stopped working and now within a day or two of my adjusting it, it succumbs to gravity and the lamp head falls to the lowest possible setting. Is there anything I can do to keep the head of the lamp up short of epoxying it in place?

EDIT: at the risk of outing myself as a complete noob I have attached an image below with the component I plan to fit the washer to circled in red. The washer will go inside of the joint mechanism so that it's not visible when the lamp is fully assembled.
Comment: It looks like there are teeth that should prevent it from moving -- does the knob loosen and allow it to fall? How easy is it to move the arm by pulling on it (while it's tightened)? I notice you've tagged with "epoxy" -- is that an acceptable fix, that will not allow this to move anymore?
Comment: I'm unable to get the teeth tight enough that I can't change the angle manually. I suppose this means that the knob does not lead to loosen more than a little in order for the lamp to fall, but I will check on the state of the knob next time the lamp does fall. I would prefer to avoid epoxying the lamp in place and am hoping to find alternatives but would certainly prefer epoxying to throwing the lamp away.
Comment: If you are unable to get the teeth tight enough that you can't change the angle manually, it sounds like the screw is not properly engaging the threads, i.e, it's stripped. I assume you've tried pliers. You may be able to use a tap and die to re-thread both the screw and the nut. Or, you may be able to find replacement parts online.
Answer: It sounds as if the knurled knob loosens over time. There are a number of solutions.
The knurled knob seems to be either the head of a bolt or a specialized nut. In either case, a washer between the knurled head and the body of the lamp arm may help. A flat washer may be enough.

If not a lock washer should help.

Another approach is a locking fluid spread on the threads of the bolt that prevents loosening, such as this stuff.

There are different versions, depending on whether you want it to be removeable or permanent.
Comment: Another solution may be to use a rubber washer, even an o-ring. That will absorb the small vibrations that typically allow screws to loosen as well as provide better friction. Rubber, silicon, or felt should work.
Comment: @Jason Good point! (Although some felt is fairly slippery).
Answer: There is no way that the teeth of this mechanism is faulty, you can see they are quite sharp still.
So the failure is coming from one of the following:

You are not tightening the nut hard enough
The thread of the nut has stripped and comes loose automatically
The movement/weight of the load is loosening the bolt

possible solutions to the listed scenarios are as follows

rock the arm back and forward while tighten the nut with your other hand.
Go to the local hardware and buy a Wingnut to replace the current nut (to match the current bolt.
In this case, the proposed washer should work perfectly

I would recommend the use of the wingnut and washer.
Answer: Do not put the washer on the inside, that will either do nothing or make the situation worse. The washer idea would need to be of the outside so that the teeth still engage, the washer would just work to fill the gap between the screw/threaded rod and the nut allowing a more snug fit.
I have another idea though. Without seeing the rest of the inside it is impossible to tell but it looks like the threaded section is a threaded rod:

Why that is important is because it doesn't have a defined end on either side and can come loose. If my guess is right, there is a nut on the inside holding it in and most likely is a knurled furniture nut molded into the plastic (not important to fully understand). So, if I'm right with the outer nut removed (your knob) you should be able to turn the threaded section (this may be fairly difficult still). If you can, turn it in the same direction you would to tighten the knob on and keep turning in until you can't; then try the putting on the knob a securing it tight. You should notice a difference immediately, if you weren't able to turn the threaded rod then I probably just guessed wrong, sorry it happens.
Comment: Thanks for this detailed description, it helped me realize that a troublesome architect lamp had been poorly assembled by the factory.  Works fine now that the threaded parts are actually in the opposing nuts.
Answer: I have the same problem with my floor lamp that I bought from Wayfair (Made in China). In my opinion it is a design/manufacturing defect. When the teeth are very wide (not fine) this can happen. If you notice the teeth are quite wide. They need to be thinner. Other than this make sure that when you are tightening the knob the screw head on the other side is not moving.
I hope this helps.
Comment: Hello, and welcome to Home Improvement. Thanks for the answer; keep 'em coming. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to contribute here.


Is it legal to use different wire types for pig-tails?

Question: When wiring an indoor switch, receptacle or fixture that has NM-B run into the box, is it legal to use a different type of wire (for example THHN) of the appropriate gauge to make pig-tails?
I can't imagine that this would not be legal, since one would connect NM-B to THHN in a box when transitioning from an interior run in cable to an exterior run in conduit, but just wanted to be sure.
If so, is it critical that the colors match, since, for example, it would be obvious by tracing the wire within the box that a short piece of white sheathed "neutral" wire was connected between a black "hot" wire exiting the box and the terminal on a standard toggle switch. Would putting some appropriate colored electrical tape on the wire be sufficient to remark the wire to be of the appropriate color?
Comment: But why?  If I were the next person to work on the wiring, I'd be really pissed if you chose to use mis-colored pigtails.  Spend a couple bucks for "scrap" wire and keep the colors matched.  As you suggest,  the cladding/bundle type is irrelevant inside a box.
Comment: While the "why" wasn't explicitly stated, if one has run out of scraps of NM-B, then one may not have the correct color available in something else. However, the mismatched colors are confusing, hence the question about using tape.
Answer: Bats has it.
The wire types are not actually different wires - the copper is the same. The difference is insulation.
The wire nut engages to parts of the wire which have no insulation. Hence the insulation type is irrelevant to the wire-nut.
Wire-nuts don't even care about solid vs stranded wire (though other connection types might).
Solid THHN wire is just stupid-cheap by the foot, so having a couple of feet lying around of 2 colors is a good idea.  Remember THHN is almost always co-listed as THWN, which is allowed outside.
Comment: The home stores usually have scraps of THHN laying around in the wire bin that they'll  just about give you for nothing... +1
Comment: I was contemplating this today and almost went with a scrap of green THHN stranded wire for a ground pigtail, but then I noticed the instruction sheet for my devices only allowed "12 or 14 AWG wire" for ground.  Mine was 10 AWG and I realized running out of NM-B scraps was not a good excuse for improvising here.
Answer: It's OK to mix types of wire.
There are no exceptions to the color-coding or re-identifying rules for pigtails.  For example you could not use a green wire for pigtails with the hot or a black wire for a neutral pigtail.  What's clear to you today when you do it may not be clear to the next person looking at the wires folded up in the box.
If you were to re-identify a pigtail by taping the insulation end to end, it's pretty hard to imagine anyone complaining about that, even if it's not strictly compliant.


Comparing user input unicode strings in Python 2.7

Question: What is the best way to compare a string entered by the user with another string?
For example:
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

user_input = raw_input("Please, write árido: ").decode("utf8")
if u"árido" == user_input:
    print "OK"
else:
    print "FALSE"

EDIT:
This
# -*- coding: utf-8 -*-

from __future__ import unicode_literals
from unicodedata import normalize
import sys

uinput2 = "árbol"
uinput = raw_input("type árbol: ")

print "Encoding %s" % sys.stdout.encoding
print "User Input \t\tProgram Input"
print "-"*50
print "%s \t\t\t%s \t(raw value)" % (uinput, uinput2)
print "%s \t\t\t%s \t(unicode(value))" % (unicode(uinput), unicode(uinput2))
print "%s \t\t\t%s \t(value.decode('utf8'))" % (uinput.decode("utf-8"), uinput2.decode("utf-8"))
print "%s \t\t\t%s \t(normalize('NFC',value))" % (normalize("NFC",uinput.decode("utf-8")), normalize("NFC",uinput2.decode("utf-8")));
print "\n\nUser Input \t\tProgram Input (Repr)"
print "-"*50
print "%s \t%s" % (repr(uinput),repr(uinput2))
print "%s \t%s \t(unicode(value))" % (repr(unicode(uinput)), repr(uinput2))
print "%s \t%s \t(value.decode('utf8'))" % (repr(uinput.decode("utf-8")), repr(uinput2.decode("utf-8")))
print "%s \t%s \t(normalize('NFC',value)))" % (repr(normalize("NFC",uinput.decode("utf-8"))), repr(normalize("NFC",uinput2.decode("utf-8"))));

prints:
type árbol: árbol
Encoding utf-8
User Input      Program Input
--------------------------------------------------
árbol          árbol   (raw value)
árbol          árbol   (unicode(value))
árbol          árbol   (value.decode('utf8'))
árbol          árbol   (normalize('NFC',value))

User Input              Program Input (Repr)
--------------------------------------------------
'\xc3\x83\xc2\xa1rbol'  u'\xe1rbol'
u'\xc3\xa1rbol'         u'\xe1rbol'     (unicode(value))
u'\xc3\xa1rbol'         u'\xe1rbol'     (value.decode('utf8'))
u'\xc3\xa1rbol'         u'\xe1rbol'     (normalize('NFC',value)))

Any idea? I haven't problems when I work with other languages like Java. This only happens to me with python. I'm using Eclipse.
Thanks in advance :)
Comment: Please include the output of `print repr(u"árido")` and `print repr(user_input)`.
Comment: Best way? What are the problems with your way, and what do you want to improve?
Comment: The comparison always returns false :(
Comment: u'\xe1rido' and
'\xc3\x83\xc2\xa1rido'
Comment: I would definitely expect `user_input` to be a Unicode string if you have done `decode("utf8")` on the `raw_input`, is this from using the `raw_input` result without the decode?
Comment: Is there *any* chance that there is a typo in your actual code and it is using `encode("utf8")` instead of `decode`?  `'\xc3\x83\xc2\xa1rido'` looks a lot like doubly encoded utf-8.
Comment: It looks like your input is encoded as utf-8 *twice*: `u'\xe1'.encode("utf8").decode("latin1").encode("utf-8") == b'\xc3\x83\xc2\xa1'`
Comment: `inp = raw_input("Please, write árido: ")
    print repr(inp)
    print repr("árido")`
is

Please, write árido: árido
'\xc3\x83\xc2\xa1rido'
u'\xe1rido'
Comment: What happens if you run it in a terminal instead of Eclipse? How do you input `á` character? Do you use copy-paste?
Comment: I tried it in a terminal and something similar happens. The repr() function returns different results between the variable read with raw_input() and the variable that has been written in the code (using unicode text). I haven´t used copy / paste (nowhere).
Answer: Can you check the character encoding of your terminal,

import sys
sys.stdin.encoding

If it is UTF-8, then decode should be fine. Otherwise, you have to decode the raw_input with right encoding.
like, raw_input().decode(sys.stdin.encoding) to check whether it is proper along with Unicode Normalization, if needed.
Comment: `print sys.stdin.encoding` prints **utf-8**
Answer: Your current approach isn't bad, but you should probably use unicodedata.normalize() for the comparison.  The docs linked above explain why this is a good idea.  For example, try evaluating the following:
u'Ç' == u'Ç'

Spoiler alert, this will give you False because the left side is the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA), and the right side is the single character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA).
You can use unicodedata.normalize() to handle this properly by first converting the strings to a normalized form.  For example:
# -*- coding: utf-8 -*-
from unicodedata import normalize

from __future__ import unicode_literals

user_input = normalize('NFC', raw_input("Please, write árido: ").decode("utf8"))
if normalize('NFC', u"árido") == user_input:
    print "OK"
else:
    print "FALSE"

Comment: this does not work

`user_input = normalize('NFC',raw_input("Please, write árido: ").decode("utf8"))
if normalize('NFC', u"árido") == user_input:
    print "OK"
else:
    print "FALSE"`


Collapse table column while using min-width

Question: I have a table and a column in it which contains text, that should be readable
So I set css like min-width: 32em; max-width: 40em;. But overall table is very wide so I try to save as much space as I can, and I wanna to collapse column if text width is smaller than min-width
But min-width is minimum width, so even if all this column cells are empty, it occupies space
I also cannot disable wrapping
How can I achieve it?
Comment: Mayby not to specify `min-width` at all? Why do you need it?
Comment: You would still get some spacing if you dont call `padding = 0;` on your ``'s. You would get the best output using media queries
Answer: You can use this for example

@media screen and (min-width: 300px) {
#Table
{
 display: none;
}
}


How to delete an attribute when sending a partial object update to Algolia?

Question: I need to use partialUpdateObject from the Algolia Javascript SDK to delete an attribute from an object that is already in the index.
My scenario is that I have a description field on my object that is optional. If the user originally sets a description and then later deletes it, I want to remove the description altogether from the object.
I do not want to overwrite the whole object (without the description attribute) because I have some count attributes on the object that I do not want to have to recalculate.
As far as I can tell in the documentation there isn't a way to do it and my workaround is to set the description as an empty string. Is that the recommended approach?
Answer: You're right: you cannot totally remove the attribute from an object with a partialUpdateObject operation. As a work-around you can set it to null, maybe that's enough for your use-case?
Comment: Got it, thanks for your help! Is there a significant difference between empty string and `null` when it comes to indexing & querying?
Answer: If you really want to delete the field you can :

Get your object with the search function
Store all fields values
Update (not partial update) your object without passing the field you want to delete


Ionic - Problems displaying AdMob banner/interstitial (iOS)

Question: There are no issues what so ever showing both banner and interstitial ads on Android devices but on iOS devices they somehow don't show, only blank box in footer area and no popup appears - however works perfectly fine on the emulator, displaying test ads.
In AdMob - I have created only one app (iOS) and therefor only have two Ad Unit IDs(Banner and Interstitial) which I use, can that be the issue or ?
You can see my code below:
<code>import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { AdMobFree, AdMobFreeBannerConfig, AdMobFreeInterstitialConfig } from '@ionic-native/admob-free';

import { ProjectlistPage } from '../pages/projectlist/projectlist';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage:any = ProjectlistPage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private admobFree : AdMobFree) {
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();
      this.showAdmobBannerAds();
      this.showAdmobInterstitialAds();

    });
  }

  showAdmobBannerAds(){
    const bannerConfig: AdMobFreeBannerConfig = {
        id: 'ca-app-pub-xxxxxx',
        isTesting: false,
        autoShow: true,

      };
    this.admobFree.banner.config(bannerConfig);

    this.admobFree.banner.prepare()
    .then(() => {

        this.admobFree.banner.show();
    })
    .catch(e => console.log(e));
    }

    showAdmobInterstitialAds(){
      const interstitialConfig: AdMobFreeInterstitialConfig = {
          id: 'ca-app-pub-xxxxxx',
          isTesting: false,
          autoShow: true,

        };
        this.admobFree.interstitial.config(interstitialConfig);

        this.admobFree.interstitial.prepare()
        .then(() => {
            this.admobFree.interstitial.show();
        })
        .catch(e => console.log(e));
      }
}
</code>
Anyone have any suggestions ?
Thanks.
Answer: This issue got resolved by adjusting payment details within AdMob to reflect 100% my companies DUNS info.
https://github.com/ratson/cordova-plugin-admob-free/issues/157#issuecomment-374006844


LABiometryType in iOS11 always return None

Question:
No matter what settings is configured in Device's passcode and touchId settings , LAContext always returns none . It is just throwing me a warning not the exception.
Its only working in XCode 9.1 Beta in iOS11.1 beta as suggested :(
Comment: yeas both in iPhone 7 Plus running iOS 11 and iPad Pro 12.9 inch but with console log as "[LAClient] initWithExistingContext -> (null), Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.CoreAuthentication.daemon was invalidated from this process." UserInfo={NSDebugDescription=The connection to service named com.apple.CoreAuthentication.daemon was invalidated from this process.}"
Comment: Possible duplicate of [TouchID crash on some iPhone 5S devices](https://stackoverflow.com/questions/27522482/touchid-crash-on-some-iphone-5s-devices)
Comment: canEvaluatePolicy return True in iOS11 correctly as expected and evaluatePolicy is working good prompting touchId from user.  I'm receiving the warning not the exception NSCocoaErrorDomain
Answer: I just figured out the problem! You have to call canEvaluatePolicy for biometryType to be properly set.
Example:
func isFaceIdSupported() -> Bool {
    if #available(iOS 11.0, *){
        if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
            return context.biometryType == LABiometryType.typeFaceID
        }
    }

    return false
}

As per the Apple docs for biometryType:
"This property is only set when canEvaluatePolicy(_:error:) succeeds for a biometric policy. The default value is none."
Answer: Got the same issue here, fixed it with the following code. But it only works with the Xcode 9.1 Beta (and iOS 11.1 beta in the simulator).
if (laContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: nil)) {

            if #available(iOS 11.0, *) {
                if (laContext.biometryType == LABiometryType.faceID) {
                    print("FaceId support")
                } else if (laContext.biometryType == LABiometryType.touchID) {
                    print("TouchId support")
                } else {
                    print("No Biometric support")
                }
            } else {
                // Fallback on earlier versions
            }
}

Comment: It's not fair. Hope Apple to release the XCode9.1 before iPhone X launch.
Answer: If you use the code from @Ermish, isFaceIdSupported() will return false if there are no enrolled faces on the device.
As per my latest tests shows on iOS SDK 11.1, just call the laContext.canEvaluatePolicy function and do not care about the result, then check the content of laContext.biometryType.
If there are no enrolled faces, the canEvaluatePolicy will fail, but the device supports Face ID.
Comment: Yeah, the important thing is that you need to set `.biometryType` on the _instance_ of `laContext` with `.canEvaluatePolicy(parameters)`. I did the mistake of using a new instance LAContext() every time.
Answer: In Xamarin.iOS, you need evaluate the Policy Before:
   NSError error;
   bool success = context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out error);
   if (context.BiometryType == LABiometryType.TouchId)
   {
       //Do Something
   }


Which social login should I use, Google OAuth2 or Google+?

Question: Google supports 4 ways to "sign in with google"

OAuth
OAuth2
Google+
Google Apps

I want a generic "sign in with google", I'm not doing anything app-specific, so the last one is out.
Presumably OAuth2 is preferable to OAuth and maybe OAuth will become deprecated, so OAuth is out.
What's the difference in the user's experience or in API capability between OAuth2 and Google+?
Comment: You will likely find StackExchange a better place for this question.
Comment: @tim.baker do you mean Stack Overflow?
Comment: Yes I do :) Gets a little confusing sometimes
Answer: Assuming you're tying yourself into Google for a social login, you should use Google+.
OAuth and OAuth2 are deprecated and will no longer be supported in the future.  Google Apps basically uses Google+ sign in now as far as I'm aware, as every Google account can be used for Google+ sign in even if the user doesn't have a Google+ account.
Answer: Dont use OAuth , You can use google+ Sign in . http://janrain.com/product/social-login/  . Go through the URL .These guys provide the best service


How do I bind QuickLoad and QuickSave to a button on my Xbox controller in Skyrim?

Question: I'm playing the PC version with an XBox controller. The middle Xbox ring button would be ideal for quick save in this game! :)
Comment: I doubt you'll be able to bind the Xbox Button. That's kinda like the windows key on a computer. Its function is part of the console, not the game.
Answer: The "Xbox" button in the center of the Xbox 360 controller is sometimes a special button that is caught outside of the game, especially in games that use Games for Windows Live.  I haven't found any tutorials for remapping Xbox 360 controller buttons on the PC that were able to remap that particular button.  However, if there is a way to do it, it will likely be via AutoHotKey, which I've covered in a couple of other answers.
More than likely, it'll just be a matter of rebinding that button on the controller to whatever the "quicksave" key is in Skyrim.  (I believe it is F5 by default.)
Comment: My memory might be failling me, but I tried this 1 or 2 years ago and I *think* autohotkey can't rebind the middle button. I'll try to find that information.


Spark No space left on device

Question: I have an EMR job which reads around 1TB data, filters it and does repartition on it (there are some joins after repartition), however my job fails at repartition with error "No space left on device". I tired to change the "spark.local.dir" but its of no use. My job completes only on d2.4xlarge instance but it fails on r3.4xlarge which has similar core and ram. I couldn't find the root cause of this issue. Any help would be appreciated.
Thank you for your time.
Answer: I had the same issue on Spark 2.2 before.
I was able to change the directory by setting SPARK_LOCAL_DIRS=/path/to/other/tmp in $SPARK_HOME/conf/spark-env.sh
"spark.local.dir    /tmp
Directory to use for "scratch" space in Spark, including map output files and RDDs that get stored on disk. This should be on a fast, local disk in your system. It can also be a comma-separated list of multiple directories on different disks. NOTE: In Spark 1.0 and later this will be overridden by SPARK_LOCAL_DIRS (Standalone, Mesos) or LOCAL_DIRS (YARN) environment variables set by the cluster manager."
https://spark.apache.org/docs/latest/configuration.html
Comment: In my case this is overridden by Yarn. But Is there any cap on the size? Does it use all the disk space that the folder is mounted on or is there any limitation ?
Comment: based on the documentation I can't seem to see any configurable value to set the max size of tmp, it should be using the max size that is mounted to the tmp directory you are pointing to.  If yours is overridden by Yarn, why not try setting `LOCAL_DIRS`.

Spark No space left on device


extracting specific data from a table

Question: I have table which looks like this (tab separated):
Ron  Rob  rock bammy
m    f   m  f
florida  Atlanta  florida texas

This table is of order 5*512 and based on row 3 data, I want to extract the values in row1.
 for example: I want to have names of all person living in florida and texas, in a table of 2 columns and n number of rows.
Florida  Ron
Florida  Rock
Texas BAmmy

and so on.
any suggestions for a bash or PERL liners...
Thank you in advance.
Comment: Please post a bigger sample of your input file.
Comment: 5 row and 512 columns, I want to extract the data in first row based on the value of the data in row 3.
Comment: Are there really spaces on either side of the tabs?
Answer: awk 'NR==1{for(i=1;i<=NF;i++)n[i]=$i}; NR==3{for(i=1;i<=NF;i++){if($i~/florida|texas/)print $i"\t"n[i];}}' yourFile

see the test below:
kent$  echo "Ron Rob rock bammy
m f m f
florida Atlanta florida texas"|awk 'NR==1{for(i=1;i<=NF;i++)n[i]=$i}; NR==3{for(i=1;i<=NF;i++){if($i~/florida|texas/)print $i"\t"n[i];}}'

output
florida Ron
florida rock
texas   bammy

EDIT
kent$  echo "Ron  Rob  rock bammy
m    f   m  f
florida(8)  Atlanta  florida(8) texas(2;7)"|awk 'NR==1{for(i=1;i<=NF;i++)n[i]=$i}; NR==3{for(i=1;i<=NF;i++){if($i~/florida\(8\)|texas\(2;7\)/)print $i"\t"n[i];}}'

output:
florida(8)      Ron
florida(8)      rock
texas(2;7)      bammy

Comment: what if, I have to match something like florida(8) and texas(2;7). How  can I put this .... single quote or double .... nothing working
Answer: Yet another Perl solution:
perl -ane 'push@c,@F}{print grep{/^(florida|atlanta)\t/i}map{"$c[$_+$#c/3*2+1]\t$c[$_]\n"}0..$#c/3'

Or as a script
#!/usr/bin/perl

use strict;
use warnings;

my (@data, @rows);

push @data, split/\s+/ while (<>);

for (0 .. $#data/3) {
    my $name = $data[$_];
    my $location = $data[$_+$#data/3*2+1];
    push @rows, "$location\t$name\n" if $location =~ /^(florida|atlanta)$/i;
}

print join("", @rows);

with an if condition inside the loop instead of the separate grep.
My approach is to flatten all three lines into a single array and use for (0 .. $#data/3) to loop over the indexes corresponding to the names from the first line and get the location from the matching column with $data[$_+$#data/3*2+1].
Comment: A very nice solution, I like it.
Answer: Here's a Perl solution that works, but it's a bit more convoluted that I'd like. You'd probably be better off putting this data into a database.
#!/usr/bin/env perl

use strict;
use warnings;
use 5.010;

my %rows = (
  name => 1,
  location => 3,
);

my %location = map { $_ => 1 } qw[florida texas];

my @names;

while (<DATA>) {
  next unless grep { $_ == $. } values %rows;

  chomp;

  if ($. == $rows{name}) {
    @names = split;
  }

  if ($. == $rows{location}) {
    my @locs = split;

    for my $x (0 .. $#locs) {
      if ($location{lc $locs[$x]}) {
        say ucfirst $locs[$x]. "\t$names[$x]";
      }
    }
    last;
  }
}

__END__
Ron     Rob     rock    bammy
m       f       m       f
florida         Atlanta florida texas

Answer: #!/usr/bin/env perl
use strict;
use warnings;

my $pat = shift;

sub interleave($$){
    my ($foo,$bar) = @_;
    return map { ( $_ , shift @{$bar} ) } @{$foo};
}

my $n=0;
my(@p,%h);
while(<>){
    chomp;
    if($n%3==0){
            @p = split /\t/, $_;
    } elsif($n%3==2){
            my @l = split /\t/, $_;
            my %kv = interleave(\@p, \@l);
            foreach my $k (keys %kv){
                    push(@{$h{$kv{$k}}}, $k);
            }
    }
    $n++;
}

foreach my $loc (keys %h){
    if(!defined $pat || $loc =~ /$pat/i){
            foreach my $name (@{$h{$loc}}){
                    print ucfirst($loc), "\t", ucfirst($name), "\n";
            }
    }
}

And then call it
perl extract.pl 'texas|florida' < data

"Oneliner" form:
perl -ne 'BEGIN{$p=shift||"^";}chomp;if($n++%3!=1){unless(@p){@p=split/\t/,$_;next;}my %kv = map { ( $_ , shift @p ) } split(/\t/, $_);map { push(@{$h{$_}}, $kv{$_}); } keys %kv;}END{map{for my$nm(@{$h{$_}}){print ucfirst($_),"\t",ucfirst($nm),"\n";}}grep{/$p/i}keys%h;}' 'florida|texas' < data

Answer: Sounds to me like this is a job for Text::CSV_XS. It is not a good idea to split on whitespace, as many seem to be suggesting, as that will fail for anything but simplified data.
Code:
use strict;
use warnings;
use Text::CSV_XS;

my $csv = Text::CSV_XS->new( {
        sep_char    => "\t",
        binary      => 1,
    });

# get array refs to each row, with appropriate name
# For larger data sets, using an array to hold the array refs would be better
my $name       = $csv->getline(*DATA);
my $gender     = $csv->getline(*DATA);
my $city       = $csv->getline(*DATA);

for (keys @$city) {   # lists the column numbers
    if ($city->[$_] =~ /florida|texas/i) {
        print "$city->[$_]\t$name->[$_]\n";
    }
}

__DATA__
Ron Rob rock    bammy
m   f   m   f
florida Atlanta florida texas

Output:
florida Ron
florida rock
texas   bammy

extracting specific data from a table


not able to import dataframe from pandas while using google colab

Question: import pandas as pd
from pandas import dataframe
import datetime
import pandas.io.data
import matplotlib.pyplot as plt

ImportError: cannot import name 'dataframe'
Comment: Try this `from pandas import DataFrame`
Answer: Try import dataframe using this:
import pandas as pd
data_df = pd.DataFrame(data)


Why can we use $\frac{\partial}{\partial u} \frac{\partial f}{\partial y}$ in place of $\frac{\partial}{\partial y} \frac{\partial f}{\partial u}$

Question: So I was looking at this reply to a question that was asked, and I kind of skipped a bunch of multivariable calculus in classes due to a thing and essentially learned most of what I could on my own, but I don't understand why we can just do the thing that I've mentioned in the question statement. Is it just that we're treating the derivatives as fractions or is there a proper reasoning for this? Could someone please explain?
Comment: See e.g. https://math.stackexchange.com/questions/1169942/why-can-partial-derivatives-be-exchanged
Comment: Ahhh yesss okay, looking at both of these right now and these seem to be making sense. Thanks guys!
Answer: From what I understand, the general idea is that if a function is separable for its variables i.e.
$$f(x,y)=\sum_i g_i(x)h_i(y)$$
then the order of derivatives is interchangeable since:
$$\partial_x\partial_y(g_ih_i)=\partial_xg_i\partial_yh_i=\partial_y\partial_x(g_ih_i)$$
however I am still trying to find a reference for this
Comment: Why is a reference needed for this? All the steps are very straightforward.
Comment: Ahh yess I see. So I wanted to know the reasoning behind this, but this is helpful too, thank you!
Answer: This is actually not always the case.
There are various ways of formulating the constraint for this to be the case.
There's an article about it on Wikipedia here. https://en.wikipedia.org/wiki/Symmetry_of_second_derivatives
Comment: Why? It's an entire article about mixing partial derivatives.
Comment: The link to https://math.stackexchange.com/questions/1169942/why-can-partial-derivatives-be-exchanged actually refers to an answer that also has a blog post link for the same theorem, yet a little less complete than the above..
Comment: It is not good answer I think.
Comment: It is the content to be included in the comment, not the answer.
Comment: Thanks for this link as well, looking through it right now!


Type not being checked in custom response structure in Express

Question: I am starting of with typescript and have hit a roadblock where I can't figure out why types are not being validated.
Route
app.use((req: Request, res: Response) => {
  // here 404 is a string but should be a number according to type defined but no error is shown
  return res.error({ status: '404', message: 'The API route does not exist' })
})

Middleware
interface APIResponse {
  status: number,
  message?: string | null,
  data?: any
}

const responseHelper = (req: Request, res: Response, next: NextFunction) => {
  res.showDefaultErrorPage = (status: number = 500) => {
      //...
  }

  res.success = (options: APIResponse) => {
    const {
      status = 200,
      message = null,
      data
    } = options

    //...
  }

  res.error = (options: APIResponse) => {
    const {
      status = 500,
      message = null
    } = options

    //...
  }

  next()
}

export default responseHelper

Custom type definition for express response
/* eslint-disable no-unused-vars */
declare namespace Express {
  interface Response {
    showDefaultErrorPage?: any
    showErrorPage?: any
    success?: any
    error?: any
  }
}

Comment: Well it looks like you gave `error` the type `any`. So no validation takes place. Why don't you give it the correct type?
Comment: Am not sure what to set, as error is a function and that function and that function takes in an object as a parameter.
Answer: You could change your type definiton to this:
import express from "express"
const app = express()

interface APIResponse {
  status: number,
  message?: string | null,
  data?: any
}

// add "declare global" here
declare global {
  namespace Express {
    interface Response<
      ResBody = any,
      Locals extends Record<string, any> = Record<string, any>,
      StatusCode extends number = number
    > {
      showDefaultErrorPage?: any
      showErrorPage?: any
      success: (options: APIResponse) => Response<any, Record<string, any>, number>
      error: (options: APIResponse) => Response<any, Record<string, any>, number>
    }
  }
}

// Dont give explicit types here. Let TypeScript infer them
app.use((req, res, next) => {

  res.showDefaultErrorPage = (status: number = 500) => {
      //...
  }

  res.success = (options: APIResponse) => {
    const {
      status = 200,
      message = null,
      data
    } = options

    return res.status(0).json({})
  }

  res.error = (options: APIResponse) => {
    const {
      status = 500,
      message = null
    } = options

    return res.status(0).json({})
  }

  next()
})

// Dont give explicit types here
app.use((req, res) => {
  return res.error({ status: '404', message: 'The API route does not exist' })
  //                 ^^^^^^ Expected error
})

Comment: @Ayan - I just checked what type `res.status(status).json` returns as this is also the return type of your function if you just return its result.
Comment: Returning:
 return res.status(status).json({
      status,
      message: message || getStatusMessage(status) || 'Server error'
    })
Comment: So the ApiResponse interface must go in the custom type definiton file, and get removed from middleware file?
Comment: @Ayan - Well you are gonna need this interface in both files. So you may export it and import it in the other file.
Comment: Could you please help me understand why would I need in both places?
Comment: @Ayan - You need in the `declare namespace Express { ...` for the type of the argument in the function but also in the `responseHelper` because you are using it as the type of the argument of `res.success` too.
Comment: ooh! I understand. BTW, I get the following: `Cannot invoke an object which is possibly 'undefined'.ts(2722)` on res.error also on res.success
Comment: @Ayan - Yes, you specified that `success` and `error` are optional, so a `Response` might or might not have them. You would either need to check if they are defined before calling them, or remove the question mark.
Comment: Got it. Getting to understand how it works. One last thing, `Response, number>` does this mimic the ApiInterface once again?
Comment: The app crashes with the error: `TS2551: Property 'error' does not exist on type 'Response>'. Did you mean 'errored'?`

Is it because error function is being set in a middleware?
Comment: @Ayan - On which line does this error happen?
Comment: The error is thrown when I run the app. This error happens wherever I have used the custom functions `error`, `success` etc.
Comment: @Ayan - That does not look like a runtime error. That error is definitely produced by TypeScript during compile time. How are you compiling the app? Just `tsc` or something with `webpack`?
Comment: nodemon for the dev, tsc for build.

Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/247623/discussion-between-ayan-and-tobias-s).


Prove that a Lebesgue measurable function is almost everywhere equal to a Borel measurable function

Question: I know that the question has been asked before, but I'm asking if I'm on the right track with my work, and also some further guidance to what to do next.
My work
First, let's suppose $f: \mathbb{R} \rightarrow [0, \infty)$. That is, assume that $f$ is non-negative.
We know that we can choose a sequence of non-negative simple functions such that
-$s_n \rightarrow f$ pointwise
-$(s_n(x))_{n=1}^\infty$ is increasing for all $x \in \mathbb{R}$
Claim:
$$f(x) = \sum_{n=1}^\infty (s_{n+1} - s_n)(x) + s_1(x)$$
Note that
$$\sum_{n=1}^\infty (s_{n+1} - s_n)(x) = \lim_{n \to \infty} \sum^n_{i = 1} (s_{i+1}- s_{i}) = \lim_{n \to \infty} s_{n+1}(x) - s_1(x) = f(x) - s_1(x)$$, from which the claim follows.
Hence, $f$ is a countable sum of non-negative simple function, so it may be written as
$$f = \sum_{n = 1}^\infty a_n \chi_{A_n}$$
where $a_n \in [0, \infty)$ and $A_n$ is Lebesgue measurable, and $\chi$ denote the characteristic function.
Now, since $A_n$ is measurable, we may choose $F_\sigma$(and hence Borel measurable) set $D_n$ such that $D_n \subseteq A_n$ and $m(A_n \setminus D_n) = 0$.
Let
$$h = \sum_{n = 1}^\infty a_n \chi_{D_n}$$
$h$ is Borel measurable(this should be right?) so it suffices to show the below claim.
Claim: $h = f$ almost everywhere.
And I'm stuck here, as the claim seems intuitively right, but I do not see a way to proceed. It would be simple if each $A_n$ was disjoint, but of course we can't guarantee that.
Any help would be appreciated, thanks!
Answer: First, note that we can find Borel measurable set $D_n$ and $C_n$ such that $D_n \subseteq A_n \subseteq C_n$ and $m(C_n \setminus D_n) = 0$. Define $h$ as follows, and show that if
$x \in (\cup_{i=1}^\infty A_n \setminus D_n)^c$, then $f(x) = h(x)$.


Multipath Raid 6 - MDADM can't find superblocks - 18.04

Question: I am running a server that connects to a multi-drive disk array,  It is connected in a dual path configuration. Because of this, all of the drives show up twice.
I suffered a power outage and now the array is not assembling.  I do however have the original commands I use.  When I have attempted to assemble it says that there is no superblock.
mdadm: No super block found on /dev/mapper/35000c500415cbb87 (Expected magic a92b4efc, got 00000000)
mdadm: no RAID superblock on /dev/mapper/35000c500415cbb87

I have two questions:

Is it possible to reassemble the array at this point or is any data lost?
How should I do this properly to avoid this in the future.

Initial commands run:
-Attempted to setup array, realized that I had twice as many drives.
-Learned about multipath
-Built a config that included the excluded the non-multipath drivers (see below)
 - Created a Raid6 array using the /dev/mapper/drives.
Commands:
sudo mdadm --create --verbose /dev/md0 --level=6 --raid-devices=12 /dev/mapper/35000c500415cbb87 /dev/mapper/35000c500415cbbef /dev/mapper/35000c500415cfea3 /dev/mapper/35000c500415d0e3b /dev/mapper/35000c500415d6e3b /dev/mapper/35000c500415e456b /dev/mapper/35000c500415e4e5f /dev/mapper/35000c500415e8223 /dev/mapper/35000c500415ee867 /dev/mapper/35000c5004160b2df /dev/mapper/35000c5004160b6bb /dev/mapper/35000c50041611daf

sudo mdadm -A /dev/mapper/35000c500415cbb87 /dev/mapper/35000c500415cbbef /dev/mapper/35000c500415cfea3 /dev/mapper/35000c500415d0e3b /dev/mapper/35000c500415d6e3b /dev/mapper/35000c500415e456b /dev/mapper/35000c500415e4e5f /dev/mapper/35000c500415e8223 /dev/mapper/35000c500415ee867 /dev/mapper/35000c5004160b2df /dev/mapper/35000c5004160b6bb /dev/mapper/35000c50041611daf

sudo mkfs.ext4 -F /dev/md0
sudo mkdir -p /mnt/md0
sudo mount /dev/md0 /mnt/md0
sudo mdadm --detail --scan | sudo tee -a /etc/mdadm/mdadm.conf
sudo update-initramfs -u

At that point, I setup folders and started using the drive, until the power outage shut it down.  Upon restart, I cannot get it to reassemble.
/etc/multipath.conf
defaults {
        user_friendly_names no
}
blacklist {
    wwid "600508e000000000997d2e0655fb5108"
    wwid "5002538d408c9715"
    device {
        vendor "Dell    "
        product "Virtual Disk    "
    }
}

/etc/mdadm/mdadm.conf
# wildcards if desired.
#DEVICE partitions containers

DEVICE /dev/mapper/35000c500415cbb87
DEVICE /dev/mapper/35000c500415cbbef
DEVICE /dev/mapper/35000c500415cfea3
DEVICE /dev/mapper/35000c500415d0e3b
DEVICE /dev/mapper/35000c500415d6e3b
DEVICE /dev/mapper/35000c500415e456b
DEVICE /dev/mapper/35000c500415e4e5f
DEVICE /dev/mapper/35000c500415e8223
DEVICE /dev/mapper/35000c500415ee867
DEVICE /dev/mapper/35000c5004160b2df
DEVICE /dev/mapper/35000c5004160b6bb
DEVICE /dev/mapper/35000c50041611daf

# automatically tag new arrays as belonging to the local system
HOMEHOST <system>

# instruct the monitoring daemon where to send mail alerts
#MAILADDR root

# definitions of existing MD arrays

# This configuration was auto-generated on Wed, 25 Jul 2018 23:01:52 +0000 by mkconf
ARRAY /dev/md0 metadata=1.2 name=media:0 UUID=5cfbe80c:d11c6b57:4beaff64:ed3bc6dd

Answer: The problem was due to using the devices and not targeting partitions.
First step was to pre-partition each of the drives.
sudo mkfs.ext4 -F /dev/mapper/35000c500415cbb87
sudo mkfs.ext4 -F /dev/mapper/35000c500415cbbef
sudo mkfs.ext4 -F /dev/mapper/35000c500415cfea3
sudo mkfs.ext4 -F /dev/mapper/35000c500415d0e3b
sudo mkfs.ext4 -F /dev/mapper/35000c500415d6e3b
sudo mkfs.ext4 -F /dev/mapper/35000c500415e456b
sudo mkfs.ext4 -F /dev/mapper/35000c500415e4e5f
sudo mkfs.ext4 -F /dev/mapper/35000c500415e8223
sudo mkfs.ext4 -F /dev/mapper/35000c500415ee867
sudo mkfs.ext4 -F /dev/mapper/35000c5004160b2df
sudo mkfs.ext4 -F /dev/mapper/35000c5004160b6bb
sudo mkfs.ext4 -F /dev/mapper/35000c50041611daf

Then I was able to go through the same create process using the partitioned drives
sudo mdadm --create --verbose /dev/md0 --level=6 --raid-devices=12 /dev/dm-0 /dev/dm-1 /dev/dm-2 /dev/dm-3 /dev/dm-4 /dev/dm-5 /dev/dm-6 /dev/dm-7 /dev/dm-8 /dev/dm-9 /dev/dm-10 /dev/dm-11
sudo mkfs.ext4 -F /dev/md0
sudo mkdir -p /mnt/md0
sudo mount /dev/md0 /mnt/md0
sudo mdadm --detail --scan | sudo tee -a /etc/mdadm/mdadm.conf
sudo update-initramfs -u

Then I had to add to the /etc/mdadm/mdadm.conf instead of the /dev/mapper entries
DEVICE /dev/dm-0
DEVICE /dev/dm-1
DEVICE /dev/dm-2
DEVICE /dev/dm-3
DEVICE /dev/dm-4
DEVICE /dev/dm-5
DEVICE /dev/dm-6
DEVICE /dev/dm-7
DEVICE /dev/dm-8
DEVICE /dev/dm-9
DEVICE /dev/dm-10
DEVICE /dev/dm-11


$ \frac{\partial}{\partial x_i} \int_{\mathbb{R^d}} f(x_0,y)\, dy = \int_{\mathbb{R^d}} \frac{\partial}{\partial x_i} f(x_0,y)\, dy $

Question: Let $\Omega$ be an open set in $\mathbb{R^d}$ and $f:\Omega \times \mathbb{R^d} \to \mathbb{R}$ be an integrable function. Suppouse that  $f$ satisties the following conditions:
1) For all $x_0\in \Omega$, $f(x_0,y)\in L(\mathbb{R^d})$ [Lebesgue integrable in $\mathbb{R^d}$]
2) Given $x_0$, there exists $\varepsilon>0$ and $g\in L(\mathbb{R^d})$ such that $B_{\varepsilon}(x_0)\subset \Omega$ and
$$
\left| \frac{\partial}{\partial x_i}f(\gamma,y) \right| \leq g(y)
$$
for all $ \gamma \in B_{\varepsilon}(x_0),\, 1\leq i\leq d$.
I have to prove that
$$
\frac{\partial}{\partial x_i} \int_{\mathbb{R^d}} f(x_0,y)\, dy =
\int_{\mathbb{R^d}} \frac{\partial}{\partial x_i}  f(x_0,y)\, dy
$$
and conclude that if $f$ is infinitely differentiable then its integral is as well.
My attempt son far:
Let $x_n$ be a sequence sucha that $x_n\to x_0$. Let $\varepsilon>0$, and assume $x_n \in B_{\varepsilon}(x_0)$ for all $n\in \mathbb{N}$. Consider the sequence
$$
F_{n,i}(y) = \frac{\partial}{\partial x_i}  f(x_n,y)
$$
By hypothesis, for a fixed $i$, there exists a function $g$ such that
$$
|F_{n,i}(y)|\leq |g(y)|
$$
I have been trying to understand how to use dominated convergence but can't find out how. Any suggestions? And Also for the concluding part...
Comment: Hint --- dominated convergence is about when you can "commute limits and integrals".  Can you write $\frac{\partial}{\partial x_i}$ as a limit?
Answer: Hint: $\dfrac{1}{|h|}|f(x_{0}+he_{i},y)-f(x_{0},y)|=\left|\dfrac{\partial f}{\partial x_{i}}(\eta_{h},y)\right|\leq g(y)$ for sufficiently small $h$, here $\eta_{h}$ is chosen by Mean Value Theorem. Lebesgue Dominated Convergence Theorem will take place by this observation and note that the difference quotient converges to the partial derivative.
Comment: Thanks! this was helpful!


how to manage lock-write mechanism in django

Question: i've been searching for a while for a way to handle the lock-write mechanism in( whenever user is updating , the record should be locked for the others ) . and i've been told that the web-frame work is responsible for this.
check this out :
https://serverfault.com/questions/184666/how-to-configure-apache-server
my question is :
how do i do that with django , in other words . what title should i be searching under
this is an Emergence task . please help
thanks in advance
Answer: Locks on the Database are provided by your DBMS like MySql or MSSQL Server. Not your framework or webserver.
http://en.wikipedia.org/wiki/Lock_(database)
Comment: Not necessarily; if it's a long-term lock, eg. for a shared text editor that says "this document can't be edited because someone else is editing it already", you definitely do not want a database lock or transaction.  (The question is too vague to have any idea what he's actually asking, of course.)
Comment: True, but on his posting over at serverfault he talks about database entries.
Comment: Documents like that are still typically stored in a database.  Anyhow, throwing darts is all that can be done with a question like this...
Comment: glad that Henrik answered my question ( your the man with the most interesting topics in stackoverflow to me ) ^_^


Facebook comments - gender and location of users

Question: Is there a way to get additional data for users that commented on a post on Facebook? So far I'm getting the message, the id and name of the user with this:
GET https://graph.facebook.com/POST_ID/comments?fields=message,from.id,from.name

I would like to additionally fetch from.gender and from.location, but this does not seem to work. Is there any other way?
Answer: The from object for a given comment only contains id and name elements.
id in the from object pertains to the user who posted a given comment. Once you have id you can query the graph API again against that user for their user details. However, you may or may not be able to retrieve location for any given user: their privacy settings may or may not expose it, or you may not have adequate permissions to retrieve more than the most generic information for that user.
You should always be able to retrieve gender and locale from a given user's endpoint in the API, however. Not that I would rely on locale for location information per se, but it may be at least marginally useful depending on your needs.


Node JS, Static Function / Variable Best Practice

Question: I have a Java background, I am trying to build a Node JS lib.
I have a class in Java like this;
public class MyClass {
    static List<String> myList = initMyList();
    private String something;

    public MyClass(String something) {
        validate(something);
        this.something = something;
    }

    public static String doSomething(String something) {
        return doSomethingWithMyList(something);
    }

    public String doSomething() {
        return doSomething(something);
    }

    private static String doSomethingWithMyList (String something) {
        // do something with list ..
        return something
    }
}

As you can see, it has a static helper method static String doSomething takes String param and non static function String doSomething uses the instance variable, something.
So users can do either MyClass.doSomething(string) or MyClass m = new MyClass(sting); m.doSomething(). The former wouldn't do validation but the later will do the validation in the constructor.
I want to do this in Node JS. And I have this.
// construction function
function MyClass(something) {
  validate(something);
  this.something = something;
}

// static variable
MyClass.myList = someModule.getList();

// static function
MyClass.doSomething = function doSomething (something) {
  return something;
};

// private static
MyClass._doSeomthingWithMyList = function _doSeomthingWithMyList (something) {
  // do something wiht list
  return something;
};

MyClass.prototype.doSomething = function doSomething() {
  MyClass.doSomething(this.something);
};

module.export = MyClass;

As I am new to Node JS world, I want to make sure that this is right way to implement class with static and non static methods.
Comment: In a modern version of node.js, you can use the [`class keyword`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) to define the class.  You no longer have to directly manipulate the prototype.  And, you can use the [`static` keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static) to define a static method.
Answer:
As I am new to Node JS world, I want to make sure that this is right way to implement class with static and non static methods.

First of all, keep in mind that there are no classes in JavaScript - even in ES2015 (ES6) and beyond. JavaScript uses prototypal inheritance and the class keyword is just a syntax sugar for prototypes, not classes. There are also no private and public properties in the sense that Java implements them using a static type system.
In JavaScript to have a truly private variable you use closures like this:
let f = (x => () => x++)(0);

Here the f() function has a truly private variable that no one else has access to and it is shared among all invocations of f() so every time it is called it increments the counter but you have no way to access the counter in any other way than using the f() function.
Keeping in mind that there are no classes in JavaScript but a newer form of OO-inheritance called prototypes (which first appeared in the Self language), there is a misleadingly named class keyword that lets you define prototypes more easily using syntax like:
class Polygon {
  constructor(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  }
  static distance(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;

    return Math.sqrt(dx*dx + dy*dy);
  }
}

class Square extends Polygon {
  constructor(length) {
    super(length, length);
    this.name = 'Square';
  }
}

See:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/class
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

My advice would be to pretend that you don't know Java when you learn the object oriented nature of JavaScript because they may look similar but they are actually very different.
Actually JavaScript is more like Scheme with Java-like syntax, Self-style OOP plus event loop based asynchronous, nonblocking I/O. It's literally nothing like Java. And by the way, unlike Java it has real lambdas that implement lexical closures so you also need to keep that in mind.


Lowercase based on regex pattern in Django & Python

Question: The script I am using calls  s_lower method to transform all text to lowercase but there is a catch: if it is a link (there is a special regex), then it does not lowercase it. So, I would like to apply the same or similar logic with other regex.
RE_WEBURL_NC = (
    r"(?:(?:(?:(?:https?):)\/\/)(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1["
    r"6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?"
    r":[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9][a-z0-9_-]{0,62})?[a-z0-9]\.)+(?:[a-z]{2,}\.?))(?::\d{2,5})?)(?:"
    r"(?:[/?#](?:(?![\s\"<>{}|\\^~\[\]`])(?!<|>|"|').)*))?"
)

def s_lower(value):
    url_nc = re.compile(f"({RE_WEBURL_NC})")

    # Do not lowercase links
    if url_nc.search(value):
        substrings = url_nc.split(value)
        for idx, substr in enumerate(substrings):
            if not url_nc.match(substr):
                substrings[idx] = i18n_lower(substr)
        return "".join(substrings)

    return i18n_lower(value)

I want to lowercase all text other than text inside the special tags.
def s_lower(value):
    spec_nc = re.compile(r"\[spec .*\]") # this is for [spec some raNdoM cAsE text here]

    if spec_nc.search(value):
        substrings = spec_nc.split(value)
        for idx, substr in enumerate(substrings):
            if not spec_nc.match(substr):
                substrings[idx] = i18n_lower(substr)
        return "".join(substrings)

    return i18n_lower(value)

Comment: For your other question, if you don't have multiple levels of nested `[]` you could use `\[spec\s+(\[[^]]*\]|[^]]|\n)*\]\s?\n?` https://regex101.com/r/6OK8Gb/1
Answer: Was writing this as a comment, but it got too long...
You haven't actually said what your problem is, but it looks like you're missing the () around the regex (so that the split string ends up in substrings). It should be
spec_nc = re.compile(r"(\[spec .*\])")

Note:

you should use [^]]* instead of .* to ensure your match stays within a single set of [].
you don't really need to search, if the string is not present then split will simply return the original string in a single element list which you can still iterate
you don't need the call to match; the strings which match the split regex will always be in the odd indexes of the list so you can just lower case dependent on idx

So you can simplify your code to:
def s_lower(value):
    spec_nc = re.compile(r"(\[spec [^]]*\])") # this is for [spec some raNdoM cAsE text here]

    substrings = spec_nc.split(value)
    for idx, substr in enumerate(substrings):
        if idx % 2 == 0:
            substrings[idx] = i18n_lower(substr)
    return "".join(substrings)

Comment: #1: Putting `?` after `.*` will have the same effect as `[^]]*` but `[^]]*` is more efficient. #2: I'm not sure exactly what you mean?
Comment: See the step counts in https://regex101.com/r/1kNezi/1 and https://regex101.com/r/Zljff7/1
Comment: @TToprak1 can you give some sample data which shows a problem? Here's a demo of it working fine for me: https://ideone.com/WLkB91
Comment: I just double checked, it works but here are my questions: 1) What is the difference between putting `?` after `.*` like `.*?` and `[^]`. 2) How about if I still want to keep the links as they are + this special tag.
Comment: So, do not lowercase links (script's default logic that I want to keep) + do not lowercase the text that inside [spec] tag. So Assuming this solution only works for  [spec] tag.
Comment: It will work, you can just use `spec_nc = re.compile(r"((?:\[spec [^]]*\])|(?:RE_WEBURL_NC))")`
Comment: Now it doesn't work. Can you please double check `spec_nc = re.compile(r"((?:\[spec [^]]*\])|(?:RE_WEBURL_NC))")`, is it correct?
Comment: @TToprak1 that should work... can you give me some sample data?
Comment: [spec CAPITAL] returns as lowercase capital
Comment: @TToprak1 it works for me: https://ideone.com/fMWnSy
Comment: I think something else going on in the script, it's more complicated then I thought but thank you so much for the help, I'll try to figure it out.
Comment: You could always ask another question with all the code in it... Good luck!
Comment: I updated my question with a more complex tag. Should I ask a new question or can you edit your answer based on my updates?
Comment: @TToprak1 that sounds like you've got a different issue, so you really should ask another question. Please do include some sample data which demonstrates the problem


Redbean: How to use R::graph() with json decoded input

Question: I think I'm using Redbean 3.3.7 (the all-in-one download from the website), but I can't find a version number in the code.
I am receiving some json encoded data and want to process it with R::graph(), but I'm getting an error.
$json = '{"id": "","title": "Test Article","slug": "test-article","content": "
This is a test article
"}';

$decoded = json_decode($json, true);

This gives me an array
var_dump($decoded)

array(4) {
  ["id"]=>
  string(0) ""
  ["title"]=>
  string(12) "Test Article"
  ["slug"]=>
  string(12) "test-article"
  ["content"]=>
  string(29) "
This is a test article
"
}

Also
echo gettype($decoded);

returns "array".
But when I try this:
$bean = R::graph($decoded);

I get a RedBean_Exception_Security error with the message "Expected array but got :string";
rb.php line 9029
What am I doing wrong?
And more importantly, how do I fix it?
Thanks.
Comment: OK two seconds after I asked this question I found the answer. My rep is < 50 so I couldn't just add it as an answer. According to the documentation "An array has to contain a key named 'type' containing the type of bean it represents". So I just had to add   $decoded['type'] = 'articles' before calling R::graph().
Answer: According to the documentation "An array has to contain a key named 'type' containing the type of bean it represents". So I just had to add $decoded['type'] = 'table_name' before calling R::graph(). It also works if I add a hidden field named 'type' in the form I submit.
<input type="hidden" name="type" value="table_name" />


Playing a video file from a url in Swift 4/Xcode 9: AVF context unavailable for sharedAudioPresentationContext

Question: I am trying to implement an AVPlayer which loads and plays a video from a url. This is placed within a function that is called by a button. Here is my current code:
<code>import UIKit
import AVKit
import AVFoundation

class MovieDetailViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func playTrailer(_ sender: Any) {
        guard let videoURL = URL(string: "http://caribbeancinemas.com/img/trailers/6134.mp4") else {
            return
        }

        let player = AVPlayer(url: videoURL)
        let controller = AVPlayerViewController()
        controller.player = player

        present(controller, animated: true) {
            player.play()
        }
    }
}
</code>
When I run the app on the simulator the video actually plays but there are two issues happening:

I get the following error message in the console:

2018-03-31 16:49:53.389148-0400 MoviesApp[18928:3137301] [MediaRemote] [AVOutputContext] WARNING: AVF context unavailable for sharedAudioPresentationContext
  2018-03-31 16:49:53.497987-0400 MoviesApp[18928:3137301] [framework] CUICatalog: Invalid asset name supplied: '(null)'
  2018-03-31 16:49:53.498937-0400 MoviesApp[18928:3137301] [framework] CUICatalog: Invalid asset name supplied: '(null)'
  2018-03-31 16:49:53.857871-0400 MoviesApp[18928:3138058] Task <223C4724-B3B5-4EBE-9AE0-5BA3C30B37C6>.<2> finished with error - code: -999
  2018-03-31 16:49:55.365686-0400 MoviesApp[18928:3138196] Task <95E91605-9B52-4212-97B3-47E73CE21B8B>.<1> finished with error - code: -999

The video player doesn't starts playing the video right away (buffering) but it seems to wait until it downloads the entire video before playing.

I have looked here for a solution to this but haven't found one yet so any help is appreciated.
Thanks in advance!
Comment: Have you found a solution for this problem?  I'm getting the same error.
Comment: No, I still get the same error.
Answer: <code>@IBAction func playTrailer(_ sender: Any) {
        guard let videoURL = URL(string: "http://caribbeancinemas.com/img/trailers/6134.mp4") else {
            return
        }

        let videoAsset = AVURLAsset(url: videoURL! as URL)
        let item = AVPlayerItem(asset: videoAsset)
        let player = AVPlayer(playerItem: item)
        let controller = AVPlayerViewController()
        controller.player = player

        present(controller, animated: true) {
            player.play()
        }
    }
</code>
Comment: Hmm, I tried this but got the same results. It also told me to remove the force unwrap and cast "! as URL". Could you elaborate on your answer and why AVURLAsset and AVPlayerItem are needed? Thanks.
Comment: To avoid the issue: Invalid asset name supplied: '(null)'


How do we tap into hiding individual status bar items in our extension?

Question: According to https://code.visualstudio.com/updates/v1_36#_hide-individual-status-bar-items we can now enable users to turn status bar messages on/off, but it doesn't point to a particular API to handle that ourselves.
I have looked at https://github.com/Microsoft/vscode-extension-samples/tree/master/statusbar-sample but it doesn't seem to show a method of handling that.
Is there a good example somewhere we can refer to?
Answer: I have not tried this myself, but going by the API docs, when you use window.createStatusBarItem you get back a StatusBarItem, which has a "hide" method.  So calling that method seems like the first thing to try.
Comment: I forgot to update this question, but that's the route we took. We went with...

 `if (myStatusBarItem) {
  myStatusBarItem.hide();
 }`


How to find the value of $m$ which is a power of a polynomial, when divided by a linear polinomial gives some remainder?

Question:
Q) The value of $m$ if $2x^m+x^3-3x^2-26$ leaves remainder of 226 when divided by $x-2$.
(1) 0
(2) 7
(3) 10
(4) all of these

How i solved it
let $p(x)=2x^m+x^3-3x^2-26$ and $g(x)=x-2=0$
therefore $x=2$
substituting the value of $x$ in $p(x)$
then:
$2(2)^m+(2)^3-3(2)^2-26=226$
$= ((2)^2)^m+8-12-26=226$
$= ((2)^2)^m = 226+30$
$= ((2)^2)^m =(16)^2 => ((2)^2)^m=((2)^4)^2 $
so on comparing both sides, since the base are same on both sides, taking the exponents
therefore,   $ 2m=8 => m=4$!!
but there is not any option there....
so how to solve this?
thanks
Answer: It is $2\cdot 2^m=2^ {m+1}$ $(\ne (2^2)^m,$ which is the wrong point in your solution). So your equation should read
$$2^{m+1}=2^8$$ from where you get $m=7.$
Comment: but how, 2 is multiplying with m?
Comment: If you have in mind that $2^m$ means to multiply $2$ by $2$ $m$ times, when you multiply again by $2$ you are multiplying $2$ by $2$ $m+1$ times.


Prove formula for $n^{th}$ derivative

Question: I have this math question. That I am stuck on.

If $f$ is a function, let $Df$ be its derivative.  For $n\in
 \mathbb{Z}^+$ let $$ f^{(n)} = \underbrace{D \cdots D }_{n\mathrm{\
 times}} f $$ be the $n^\mathrm{th}$ derivative of $f$.  In this
   notation the usual product rule from calculus  says that   $$
 (fg)^{(1)} = fg^{(1)} + f^{(1)} g. $$ Using the product rule, prove
   the formula for the $n^\mathrm{th}$ derivative of a product  $$
 (fg)^{(n)} = \sum_{k=0}^n \binom{n}{k} f^{(n-k)} g^{(k)}. $$ (Hint:
   The proof in here is similar to the proof of the Binomial Theorem.)

I can see that for example is $n=2$ the equation becomes $\binom{2}{0}f^{2}+\binom{2}{1}f^{1}g^1+\binom{2}{2}g^2=f^2+2fg+g^2$. I'm not sure how to prove this though. Thanks.
Comment: You can prove it by induction.
Comment: Try a proof by induction. You already know it holds for $n=1,2$; now see if you can show that the statement is true for $n+1$, given that it holds for $n$.
Answer: Induction will come down to proving that ...
$$\sum_{k=0}^n \binom{n}{k}\left (  f^{(n-k+1)} g^{(k)} + f^{(n-k)} g^{(k+1)}   \right)= \sum_{k=0}^{n+1} \binom{n+1}{k} f^{(n+1-k)} g^{(k)}.$$
Comment: I get the assumption $(fg)^n=\sum_{k=0}^n\binom{n}{k}f^{n-k}g^k$... but how do you relate $(fg)^{n+1}=\sum_{k=0}^{n+1}\binom{n+1}{k}f^{n+1-k}g^k$ to it?
Comment: differentiate $(fg)^{(n)}$ to get the l.h.s. of the above equation
Comment: I'm still not understanding how differentiating it will get you $f^{(n-k+1)}g^{(k)}+f^{(n-k)}g^{(k+1)}$
Comment: use the product rule on $f^{(n-k)}g^{(k)}$
Comment: Doesn't it become $(n-k)f^{(n-k-1)}g^k+kg^{(k-1)}f^{(n-k)}$?
Comment: $f^{(n)}$ means the $n^{th}$ derivative , the $n$ is in no way an exponent and should always be written complete with brackets.
Comment: So, then why do you add 1 to the exponent? $f^{(n-k+1)}$?
Comment: it is not an exponent .  the superscript increases by one because $Df^{(n)} \equiv f^{(n+1)}$

Prove formula for $n^{th}$ derivative


How do I change the thing under the crosshair back to normal?

Question: So you know the thingy under the crosshair in Minecraft? My brothers' friend played on my PC and he changed the settings so the bar under the crosshair isn't there anymore but instead it isn't a bar and it is a sword that charges but it is next to my hotbar.
Answer:
Go to the menu Options → Video Settings.

There will be an option that currently says Attack Indicator: Hotbar.

Click it until it says Attack Indicator: Crosshair instead.


How to bind this pointer to static member function using thunk in c++

Question: I'm trying to create a thunk with C++ and Win32 API, that binds this pointer to static member function, so I can use that function as a callback.
Now, I have a working thunk for x64, it works by setting the value of r9 register (corresponds to 4th parameter of a function) to the address of this pointer.
But I'm having a problem with thunk for x86, I tried to setting the value of [esp+10h] (also corresponds to 4th parameter).
Here's the thunk:
#pragma pack(push, 1)
struct THUNK {
    DWORD mov;               // mov dword ptr[esp+10h], pThis
    DWORD pThis;
    BYTE  jmp;               // jmp relproc
    DWORD relproc;
}
#pragma pack(pop)

And here's the class that uses the thunk:
class foo {
    void callback_impl(int a, int b, int c) {
        ...
    }
    static void __stdcall callback(int a, int b, int c, foo *This) {
        This->callback_impl(a, b, c);
    }
public:
    THUNK *thunk;
    foo() {
        thunk = (THUNK*)VirtualAlloc(NULL, sizeof(THUNK), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
        thunk->mov = 0x102444C7;
        thunk->pThis = (DWORD)this;
        thunk->jmp = 0xe9;
        thunk->relproc = DWORD((INT_PTR)&foo::callback - ((INT_PTR)thunk + sizeof(THUNK)));
        FlushInstructionCache(GetCurrentProcess(), this, sizeof(THUNK));
    }
    ~foo() {
        VirtualFree(thunk, sizeof(THUNK), MEM_DECOMMIT);
    }
};

And here's the callback user:
void callback_user(void(__stdcall *callback)(int, int, int)) {
    ...
}

// foo f;
// callback_user((void(__stdcall*)(int, int, int))f.thunk);

However, when I ran the program, it gave me the failure:

Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call.  This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention.

How can I solve this problem?
Thanks.
Comment: Please provide a [mcve].
Answer: This failure is caused by stdcall convention. Caller expects callee to clean up 3 arguments worth of stack while callee (your callback) cleans up 4 arguments causing esp to go to wrong location. Also you cannot just write to esp+10h because caller might be using it.
Now here is alternative idea: can't you just set ecx to this and call member function directly (provided it uses stdcall convention)?
UPDATE: Or you can put This as a first argument to your static member function so it closest to a stack top; thunk then can modify stack to make it look like a stdcall function call with 4 arguments. It will look something like
pop eax
push This
push eax
jmp func

Comment: `stdcall` does not use registers, so no, you cannot put the `this` pointer in `ECX`, it needs to be passed on the stack as the first parameter. You are thinking of `thiscall` instead, which does put `this` in `ECX` (also, `thiscall` is not portable across compilers, but `stdcall` is)
Comment: Whole point of thunk/static member function combo here is to call non-static member function which uses `thiscall` convention - my suggestion was to try to call that non-static member function directly. Fair point on `thiscall` portability; my remark on `stdcall` was about that also. I realize now I didn't phraze it correctly; by `stdcall` I meant "`thiscall` which operates exactly like `stdcall` except for `this` in `ecx`. However that can be mitigated by using `__thiscall` which should force MSVC/gcc to do exactly that.
Comment: @AndreyTurkin I can't put This as a first argument because otherwise `callback_user` function would no longer works.
Comment: So you think it would work if you add 4-th argument but wouldn't if you add 1st argument? That's a strange logic. Anyway, it does work. I urge you to try it, and then to sit down with pen and paper and figure out why did it work and how stdcall calling conventions actually work.


canvas doesnt draw in loop

Question: Why arent rectangles being drawn in loop?
I just started making snake game n tried to draw body of snake via loop,but for some reason ctx doesnt draw in  loop.
if i write rect without loop it works.
var canv = document.getElementById('canv');
var ctx = canv.getContext("2d");

var snake = [];
snake[0] = {x:100, 100};
snake[1] = {x:90, 100};
snake[2] = {x:80, 100};

var i;

function draw() {
   for (i = 0; i > snake.length; i++) {
     ctx.fillStyle = "yellow";
     ctx.rect(snake[i].x, snake[i].y, 22, 300);
     ctx.fill();
 }

setInterval(draw,100);

Comment: You should learn how to debug your code; then you can check your draw implementation.
Answer: The for loop is wrong(you had an infinite loop and make it less than i < snake.length):
function draw() {
    for (i = 0; i < snake.length; i++) {
        ctx.fillStyle = "yellow";
        ctx.rect(snake[i].x, snake[i].y, 22, 300);
        ctx.fill();
    }
}

canvas doesnt draw in loop