How to get YouTube video aspect ratio

Question: I'd like to get the aspect ratio of a YouTube video, to resize the player accordingly. I'm programming the YT player using JavaScript.
Answer: I would suggest hitting the oembed url:
https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v={videoID}&format=json
This gives you the exact video dimensions for videos that are public. I'm not sure about private videos though. It will also return thumbnail dimensions, which seem to be different im some cases, so just be sure to not mix them up.
Comment: Thank you. I was looking for a way to check my YT videos' aspect ratio and your answer solved my problem.
Answer: The only place that exact video dimensions are exposed in a Data API call is when you make a videos.list(part=fileDetails, id=VIDEO_ID) call using the v3 API, while authenticated as the owner of the video. It's returned in the video.fileDetails.videoStreams[].aspectRatio property. This isn't particularly useful, since you need to be authenticated as the video's owner in order to get that info.
If you just have a webpage, and want to make a JSONP call to get a hint about whether a given video is 16:9 or 4:3, you can do that via something like
http://gdata.youtube.com/feeds/api/videos/VIDEO_ID?v=2&alt=jsonc&callback=myCallback
E.g.
http://gdata.youtube.com/feeds/api/videos/F1IVb2_FYxQ?v=2&alt=jsonc&callback=myCallback
has "aspectRatio":"widescreen" set in its response, which is a hint that the video is 16:9 (or close to 16:9).
http://gdata.youtube.com/feeds/api/videos/u1zgFlCw8Aw?v=2&alt=jsonc&callback=myCallback
does not have aspectRatio set at all, which means that the videos is 4:3 (or close to 4:3). It's not always the exact aspect ration, but it's close enough for the vast majority of videos to be useful.
Comment: The URLs in this answer now return "no longer available".
Comment: Not all videos are 16:9 or 4:3 so assuming a video is 4:3 unless you can tell it's about 16:9 doesn't work. What about videos shot in portrait mode on a phone?
Answer: Here is how I do it.  I get the aspect ratio from the youtube image.

I pull all the video information from the youtube api and then store all the video information in a database beforehand, so if you are doing this on the fly, you might have to hide the image on the page and then get the aspect ratio that way.
edit**   Another option, and probably the best, would be to use youtube's api.
Search for a video, and check if the data->items->aspectRatio is set.  I don't think it's set on 4:3 video, but on 16:9 it is set to widescreen.  Should be as simple as if (data->items->aspectRatio) {ratio= "16:9"} else {ratio="4:3"}
Comment: I tried the first idea in this answer, but try to look at this image http://i.ytimg.com/vi/9bZkp7q19f0/default.jpg and compare with this: http://i.ytimg.com/vi/nnS7G3Y-IDc/default.jpg. Those two pictures have the same dimensions even though their original ratios are different. This might not work at all - Youtube places black bars in top and bottom of the images as well as on embed `iframe` videos.
Comment: I don't think this is a good approach. Thumbnail images might be of an arbitrary dimension unrelated to the source video, as they sometimes have letter/pillar boxing.
Comment: Clever! I'll try it when I get the chance. Marking as resolved because this question has been open too long.
Answer: My goal was to get aspect ratio for any video, not only for those for which I'm owner.
Thus the trick is to use https://developers.google.com/youtube/v3/docs/videos/list with player provided in parts and then parsing width and height of returned embed html.
Comment: This is actually the way to do it if you want the aspect ratio of any video. Also, by providing a maxWidth query parameter, the player part contains the embedHeight, from which the aspect ratio can then be calculated. See https://developers.google.com/youtube/v3/docs/videos#player.embedHeight and https://developers.google.com/youtube/v3/docs/videos/list#maxWidth
Answer: Aspect ratio apparently depends on the quality level. Taken from the YouTube Docs:
Quality level small: Player height is 240px, and player dimensions are at least 320px by 240px for 4:3 aspect ratio.
Quality level medium: Player height is 360px, and player dimensions are 640px by 360px (for 16:9 aspect ratio) or 480px by 360px (for 4:3 aspect ratio).
Quality level large: Player height is 480px, and player dimensions are 853px by 480px (for 16:9 aspect ratio) or 640px by 480px (for 4:3 aspect ratio).
Quality level hd720: Player height is 720px, and player dimensions are 1280px by 720px (for 16:9 aspect ratio) or 960px by 720px (for 4:3 aspect ratio).
Quality level hd1080: Player height is 1080px, and player dimensions are 1920px by 1080px (for 16:9 aspect ratio) or 1440px by 1080px (for 4:3 aspect ratio).
Quality level highres: Player height is greater than 1080px, which means that the player's aspect ratio is greater than 1920px by 1080px.

Comment: This piece of doc says that each quality level can have 16:9 or 4:3 aspect ratio.
Comment: Except for the first and last. I couldn't find any other documentation for aspect ratio either. But take a look at the different width's and heights. Surely you could use that to determine the ratio?
Comment: It's my code that sets the player's width and height - doesn't make sense to use them to derive aspect ratio.
Answer: Maybe not a good answer, but there seems to be an assumption amongst other answers that YouTube videos are either 16:9 or 4:3.
But they can have a pretty much arbitrary aspect ratio, and with portrait phone videos having become quite common, it's becoming less of a rarity for a video on YouTube to be something different.
For these non-standard aspect ratios, as a quick manual fudge, I've resorted to playing them in full screen, doing a screen capture, and cropping the image down.
I've put a couple of examples of arbitrary aspect videos at http://youtube-aspect-ratios.xtra.ink.

How to get YouTube video aspect ratio


Cypress: Mocha Automation Framework: Custom Command : Custom Command not running not running in test

Question: I created a custom command that would automate the process of of adding an item to shopping cart.  I ran rand the code in the test PRIOR to add it to the custom command and it worked perfectly.  I add the code 'add to shopping cart' code and created the custom command called AddToCart.  I added the command to my test spec file and tried to run the test.
Although, the raw automation code is correct, because I created and ran it in the test successfully in the test spec file, it won't run it won't perform as a  custom command, so the test hangs and won't add the item to the shopping cart.   You can watch it here
I I've been looking at this code and I'm utterly confused what I might have gone wrong.  I'd love another pair of eyes to take a look at it.
thanks in advance.
I'm totally confused how this could happen
Test spec with custom command
> /// <reference types="Cypress" />
>
>      describe('My test feature',function() {
>
>     beforeEach(function(){
>        cy.fixture('example').then(function(data){
>
>              this.data=data
>
>             })
>
>     })
>
>
>
>     it('my first test scenario', function(){
>
>         cy.visit('https://rahulshettyacademy.com/angularpractice/')
>         cy.get('input[name="name"]:nth-child(2)').type(this.data.name)
>         cy.get('select').select(this.data.gender)
>
>         cy.get('input[name="name"]:nth-child(1)').should('have.value',this.data.name
> )
>         cy.get('input[name="name"]:nth-child(2)').should('have.attr', 'minlength','2')
>         cy.get('input[id=inlineRadio3]').should('be.disabled')
>
>         //custom command
>         cy.get('a[href="/angularpractice/shop"]').click()
>         cy.AddToCart('blackberry')
>
>
>
>      })//end of test case
>
>
>
>      })//end of describe

The custom Command
> // *********************************************** // This example
> commands.js shows you how to // create various custom commands and
> overwrite // existing commands. // // For more comprehensive examples
> of custom // commands please read more here: //
> https://on.cypress.io/custom-commands //
> *********************************************** // // // -- This is a parent command -- // Cypress.Commands.add('login', (email, password)
> => { ... }) //   Cypress.Commands.add("AddToCart", (productName) => {
>
>     cy.get('h4.card-title').each(($e1, index, $list) =>{//this go the the array of items for sale using an array
>
>         if($e1.text().includes(productName))//find the product in the script
>
>         {
>               cy.get('button.btn.btn-info').eq(index).click()//when you have found the product 'add to cart' button
>
>         }
>     })   })
>     // // -- This is a child command -- // Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject,
> options) => { ... }) // // // -- This is a dual command -- //
> Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject,
> options) => { ... }) // // // -- This will overwrite an existing
> command -- // Cypress.Commands.overwrite('visit', (originalFn, url,
> options) => { ... })

Answer: How about this condition: if($e1.text().includes(productName)) inside your custom command? I mean I can see "Blackberry" in the video but "blackberry" is your parameter:

cy.AddToCart('blackberry')

Case matters, so typing cy.AddToCart('Blackberry') might solve your problem.
Comment: @fypnlp: that was only your interpretation of the written text. "might" was simply used in its most common meaning, that is injecting some uncertainty into the sentence, which was my intention to say it like that since I don't really sit at your laptop and there could be another problem that I'm not aware of.
Comment: Thank you for your response. I don't think this was your intention but '...might solve your problem'  initially came across as abrupt. However, its possible to misinterpret something in written form as there is no vocal pitch and tonality.   Still I really appreciate you taking the time to help solve this problem.  Something I will be aware of from this point on.
Comment: You have one perspective and I have another.   We can agree to disagree on a subjective interpretation - it's not that deep.  Have a great day.
Answer: You can use create a case-insensitive search with a regex. The easiest way is with a .contains() command.
Also, target the whole card instead of the heading, .contains() will find text in all children of the card. Then the button is easier to find.
it('adds an item to the cart', () => {

  Cypress.Commands.add("AddToCart", (productName) => {

    cy.contains('div.card', new RegExp(productName, 'i'))
      .each($card => {
        cy.wrap($card)
          .find('button').contains('Add')
          .click()
      })
  })

  cy.viewport(1200,1200)
  cy.visit("https://rahulshettyacademy.com/angularpractice/shop");

  const productName = "blackberry";

  cy.get('a').contains('Checkout ( 0 )')
  cy.AddToCart(productName)
  cy.get('a').contains('Checkout ( 1 )')

});

Comment: that's fantastic I will definitely add that modification to my code. It makes perfect sense.  I'm going to refer to this layout of the code as it's better than the one in my training material.  Thank you so much


Parsing the 'q' in drupal to get the current URL

Question: So I am attempting to parse out the URL, so that I can get a specific page template to be used for a specific URL; if the URL is example.com/team, then use page-team.tpl.php.
However, when I do this, the URL I am getting (via $_GET['q']) always seems to be the URL from where I was, not the one where I am currently at. If I directly navigate to example.com/team/surf, it gives me "team/surf"; if I go to example.com/team it gives
"team/surf." If I refresh the page, it will then give me the desired one.
I dropped this code into my template.php file.
function theme_preprocess(&$vars, $hook) {
  switch ($hook) {
    case 'page':
      $normal_path = trim($_GET['q'], '/');
      $path_alias = drupal_get_path_alias($normal_path);
      $alias_parts = explode('/', $path_alias);

      if (($alias_parts[0] === 'team') && (count($alias_parts)) == 1) {
       $vars['template_file'] = 'page-team';
      }
      break;
    }

Do you have any idea on what is going on here?
Comment: Consider posting your solution as an answer and marking it as accepted so that others can easily find a solution
Comment: yup. didn't realize that. i'll have to update the answer in 4hrs.
Comment: It seems a localized situation; `$_GET['q']` is normally updated with the current value get from the page request. I have never seen that value being not correct. There could be code that alters that value, but from what being reported is not possible to know that.
Answer: I'm not sure why your code happens to fail in some cases, and in some cases not. But what I would try is replacing that code with the provided by Drupal arg function.
On "team/surf", arg(0) will return "team", and arg(1) "surf". This is what I use myself, and hopefully that will solve the problem for you.
Comment: `THEME_preprocess_page()` is called after the messages HTML has been produced. So, when `drupal_set_message()` or anything that ends calling it is called from `THEME_preprocess_page()`, the message will only be displayed on the next page request. It explain why `dsm($_GET['q'])` prints the previous URL. Also, note the `dpm()` should be used instead of `dsm()`.
Comment: interestingly it came down to `dsm()`. So i wanted to check some variables before i moved forward. i was simply dumping them into `dsm()` just to see what my results were looking like. at the time, just seemed like a good idea. so `dsm($_GET['q'])` would output the previous url and not the current url. when i did a `print $_GET['q']` it would show me the current url as expected.

as for arg(). good call on that one. i have seriously forgotten all about that one. thanks for the help.
Comment: @austin That is what happens sometimes with `dsm()`.
Comment: @Letharion - Pure `arg()` doesn't work with aliases. You have to add `drupal_get_path_alias()` as an argument of `arg()` like so: `arg(1, drupal_get_path_alias())`. Otherwise `arg(1)` will always return the node id.
Answer: There is no need to parse the $_GET['q'] yourself.


What kind of lute is this, which strings does it use and to which notes are they tuned?

Question: Okay, that's actually 3 questions, but I would love to play this instrument.
I acquired this lute (see images). It has 10 strings (5 currently missing). I want to replace them, and tune the lute.
But I don't know which strings to use or how to tune it.
Can anyone help me out?
Comment: What a gorgeous instrument! How lucky are you!
Comment: There is a very useful mail list about lutes of all types, which you can see here: http://www.cs.dartmouth.edu/~wbc/lute-admin/index.html I have been using this list for some years and there are some really helpful and very knowledgeable contributors. If you join the Lute List, you could then post there and ask them for more detailed advice about strings.
Comment: @Tim, yes I am very gracious, although it need some polishing, I can't wait to fiddle with it :-)
Answer: Looks like a Swedish Lute to me.
Comment: I am not sure if your instrument should be strung with steel strings or with ball-end folk nylon strings. You should be careful about this. If it was designed for nylon strings, you should not put steel strings on it; they will damage the instrument.
Comment: That's the one! I can now search for the string and tuning.
Comment: Essentially it is a guitar with four extra bass strings. I believe the top six strings are standard guitar strings tuned to standard pitch. There is a Swedish-language website with a wealth of information here: http://www.svenskalutan.se


If $\| \alpha(s) \| \leq \| \alpha(s_0) \| = R$, then the curvature $k(s_0)$ is greater than $1/R$

Question: This question is in Ted Shifrin's A first course in curves and surfaces, page 18, exercise 7:

Suppose $\alpha$ is an arclength-parametrized space curve with the property that $\| \alpha(s) \| \leq \| \alpha(s_0) \| = R$ for  all $s$ sufficiently close to $s_0$ . Prove that $k(s_0) \geq 1/R$. (Hint: Consider the function $f(s)=\| \alpha(s)\|^2$. What do you know about $f''(s_0)$?)

Here's what I have tried:
$$f(s) = \| \alpha(s)\|^2 =  \langle \alpha(s), \alpha(s) \rangle \implies f'(s) = 2 \langle T(s), \alpha(s) \rangle $$
And using the Cauchy-Schwartz inequality :
$$f'(s_0) = 2 \langle T(s_0), \alpha(s_0) \rangle \leq 2 \|T(s_0)\|\|\alpha(s_0)\|=2R \implies \langle T(s_0), \alpha(s_0) \rangle \leq R$$
Now we find $f''(s)$:
$$f''(s) = 2 \langle k(s)N(s), \alpha(s) \rangle  + 2 (\langle T(s), \langle T(s \rangle )=  2 k(s) \langle N(s), \alpha(s) \rangle  + 2$$
And because $s_0$ is maximum of $\| \alpha(s)\|$:
$$2 k(s_0) \langle N(s_0), \alpha(s_0) \rangle  + 2 \leq 0 \implies -1/k(s_0) \geq \langle N(s_0), \alpha(s_0) \rangle$$
I don't know how to continue from here.
Answer: This question is a classic from curve and surface geometry.  Good to run into it here, like an old friend one hasn't see in awhile.
These things being said:
We note the hypothesis that
$\Vert \alpha(s) \Vert \le \Vert \alpha(s_0) \Vert \tag 1$
essentially tells us that $s_0$ is a local maximum of the function $\Vert \alpha(s_0) \Vert$; since the real function $w \to w^2$ is strictly monotonically increasing for $w \ge 0$, $s_0$ will also be a local maximum for $\Vert \alpha(s) \Vert^2$; we shall work with this function in lieu of $\Vert \alpha(s) \Vert$.
We set
$f(s) = \Vert \alpha(s) \Vert^2 = \langle \alpha(s), \alpha(s) \rangle; \tag 2$
then
$f'(s) = 2\langle \alpha'(s), \alpha(s) \rangle = 2\langle T(s),  \alpha(s) \rangle, \tag 3$
where
$T(s) =\alpha'(s) \tag 4$
is the unit tangent vector field to the curve $\alpha(s)$; we further have
$f''(s) = 2\langle T'(s), \alpha(s) \rangle + 2\langle T(s), T(s) \rangle; \tag{5}$
we may take this equation a step further by recalling that $T(s)$ is a unit vector and
$T'(s) = \kappa(s) N(s), \tag 6$
where $N(s)$ is the unit normal field to, and $\kappa(s) > 0$ is the curvature of, $\alpha(s)$.  Thus,
$f''(s) = 2\kappa(s) \langle N(s), \alpha(s) \rangle + 2; \tag 7$
since $s_0$ is a local maximum of $f(s)$, we must have
$f''(s) \le 0; \tag 8$
thus,
$\kappa(s_0) \langle N(s_0), \alpha(s_0) \rangle + 1 \le 0, \tag 9$
or
$\kappa(s_0)\langle N(s_0), \alpha(s_0) \rangle \le -1; \tag{10}$
taking absolute values of both sides, we find
$\kappa(s_0)\vert \langle N(s_0), \alpha(s_0) \rangle \vert \ge 1; \tag{11}$
by Cauchy-Schwarz,
$\vert \langle N(s_0), \alpha(s_0) \rangle \vert \le \Vert N(s_0) \Vert \Vert \alpha(s_0) \Vert = \Vert \alpha(s_0) \Vert \tag{12}$
since
$\Vert N(s_0) \Vert = 1; \tag{13}$
combining (11) and (12), we obtain
$\kappa(s_0) R \ge 1, \tag{14}$
whence
$\kappa(s_0) \ge \dfrac{1}{R}. \tag{15}$
Comment: You too are free to not give textbook problems as **graded** homework. With the rise of the internet (and Yahoo Answers being a much worse culprit than Math SE), the only way to prevent student cheating is to use proctored assessment. Attempting to impose rules on online communities would be like a Whack-A-Mole game that never actually works. Maybe sad, but that's the way it is...
Comment: @TedShifrin: with all due respect, and I *do* admire your book and your work,  have I done so before?  If so, can you cite links to such answers?  Also, most of my post re-iterated what the OP already had stated; in light of that, I merely added a few notes to the end of his attempt.  "Ruin my textbook", which I said I admired, seems pretty strong.  Best Regards.
Comment: @TedShifrin Respectfully, this answer at most ruins your graded homework, if anything, not your book. Secondly, students that receive graded homework have hundreds of ways to cheat. They can, for example, copy the solutions from each other. They can pay someone to do it (I have seen this happen several times unfortunately). A  well written answer on Math.SE should be the least of your concerns. Congratulations on giving graded homework assignments, that is I great thing in my opinion, but respectfully I think your reaction doesn't make sense.
Comment: Robert: Please don't ruin my textbook by posting complete solutions to the homeworks. You realize you're likely doing lots of students' homework this way. (This person is asking for guidance, not a professional solution.)
Comment: @TedShifrin:  It seems to me a legitimate question as to how is myself or any other user of this site to know if the poster is taking a class using your book or just reading it?  I don't think I'm wrong in asserting that many questions posted on this site occur in textbooks, whether they are quoted as such or not.  Also, if you look carefully at the last line in the question, you will see that the poster was right on top of the answer, he just didn't get how to use Cauchy-Schwarz in this context.  I did, and so posted.  By the way, am I wrong in assuming that you downvoted my answer?
Comment: For those of us who assign graded homework (and, in particular, this problem), it renders it far too easy for students not to learn and just turn in your work as their own. This is, admittedly, what I detest about this site. When a student asks for a hint, suggestion, or guidance, why must people (yes, you, included) indulge themselves by writing a polished, complete solution? (This I have witnessed numerous times.) You did not merely add a few notes ...
Comment: @TedShifrin: I am very much against cheating, including gaining unfair advantage over other students. However, I also think that you should not impose on others concerning questions taken from your textbook unless it is according to the site guidelines. We do already have a contest policy for publicly available contests, but it is already nearly impossible to enforce, as you surely know. While you could ask people here nicely to not provide full polished solutions, they are free to do otherwise within site guidelines, and that in no way "ruins your textbook".
Comment: Dear all: there is now a [meta thread](https://math.meta.stackexchange.com/questions/29122/i-dont-know-how-to-proceed-in-this-situation) regarding this - FYI.
Answer: First of all, what is $f'(s_0)$, precisely? No inequalities here. You should be thinking about Cauchy-Schwarz in the analysis of the second derivative. Several warnings: First, $s_0$ is a maximum, not a minimum; but $f''(s_0)\le 0$  (not strict inequality). Second, think about the sign of $\langle N(s_0),\alpha(s_0)\rangle$. Last, don't divide by $k(s_0)$ if you want to solve for $k(s_0)$ :)
Comment: Incomplete "hint answers" like this do not help anyone who wants the actual answer. As someone with a very poor understanding of differential geometry, this answer is useless to me. Stack Exchange is about curating knowledge, not about helping the person who asked the question and them alone.
Comment: @forest if you have a very poor understanding of differential geometry, then you should start with easier problems. SE is not an encyclopedia, it is not a list of solved questions that your textbook is "missing." Curating knowledge in mathematics involves providing insight, and Professor Shifrin does this by offering a thought process that would lead OP to the answer. That is probably how you curate knowledge. Have you taught a class? Do you have a degree in math education? Have you taught any classes? Why would you claim to know more about curating knowledge  than a lifelong professor. Sheesh
Comment: @forest  We'll have to agree to disagree. Witness the huge number of duplicates and near duplicates.
Comment: That is a thought-terminating cliché. Referring to duplicates may be valid (I have not seen any), but does not change my opinion that _this_ answer to _this_ question is incomplete.
Comment: @TedShifrin +1 by the way. Sorry for the rant on what I thought was a nice answer, that helped me answer the question (with some work), which I stumbled upon.
Comment: @AndresMejia, thanks for your support in these contentious times. :) If you haven't already done so, check out my text. :)
Comment: @TedShifrin I definitely will, I'm excited to take a first course in differential geometry next semester. I have on the other hand used your videos to learn about differential forms. Those were great! thanks for sharing your knowledge :)
Comment: @Andres Great. Keep me posted!!
Comment: @AndresMejia When did I say anything about knowing more about curating knowledge than a professor? I said that Stack Exchange is supposed to be a collection of information. It explicitly compares itself to Wikipedia (to differentiate itself from a forum). If you want half-completed answers that you have to finish yourself, that's what a textbook is for. If you have a question and want an answer, that's what SE is for.


Give a direct proof that, $n^3 > n^2 − 6n + 4$ for all $n ∈ {\mathbb N}$ with $n ≥ 2$ .

Question: I have proved this by induction but with direct proof, I'm not really sure where to start. Thank you.
Give a direct proof that, $n^3 > n^2 − 6n + 4$ for all $n ∈ {\mathbb N}$ with $n ≥ 2$ .
Comment: There is always induction under the rug.. at least for proving the basic facts used in any proof (e.g. $n^2 \ge 0$)
Comment: Try completing the cube.
Comment: @J.D., there is no induction in my answer, as it is shown for all real numbers $x\geq 1$, and not just for the natural numbers.
Answer: $n^3-n^2+6n-4=(n^3-n^2+6n-6)+2=(n-1)(n^2+6)+2>0$ for $n>1$.
Comment: That was it! ---
Answer: For $n \geq 1$
$$n^3 \geq n^2$$
$$6n > 4$$
add them together.
Comment: Very efficient!
Answer: Since $n\geq 2$ we can say that $n^3 \geq 2n^2=n^2+n^2\geq n^2+4 >n^2-6n+4$. So $n^3>n^2-6n+4$
Comment: That comes from the formula. Since $n\geq 2$  long story short, multiply both sides of the equation by $n^2$ and you have $n^3\geq 2n^2$. the second inequality comes form the fact that $n\geq 2 \implies n^2 \geq 4$ so that's the replacement that happens there. And the final is just because we subtracted something.
Comment: Do you know where I can find a list of these common inequalities which I should know as a mathematics student. I am referring to $n^{3}\ge2n^{2}$. Regards.
Answer: Let $f(x)=x^3-(x^2-6x+4)=x^3-x^2+6x-4$. This is a polynomial, therefore a differentiable function on $\mathbb{R}$. Its derivative is given by
$$f'(x)=3x^2-2x+6.$$
The discriminant of the quadratic polynomial is $4-4\cdot 18<0$, thus its roots are imaginary. In particular, since $f'(0)=6$, the derivative $f'(x)>0$ for all $x\in\mathbb{R}$. This implies that $f(x)$ is a strictly increasing function for all $x\in\mathbb{R}$. Since $f(1)=2$, we must have that $f(x)\geq 2>0$ for all $x\geq 1$. In particular, $f(x)>0$ for all $x\geq 1$, and $x^3>x^2-6x+4$ for all $x \geq 1$.
Answer: For what is worth:
$$n^3-n^2+6n-4>0$$
$$n^3-3n^2+3n-1+2n^2+3n-3>0$$
$$(n-1)^3+2n^2+3(n-1)>0$$
Comment: There are implied *iff* between these.
Comment: @lhf Just add them if you want.


Show accounts with the taxonomy term used from a node

Question: A default user can create a project (a content type with custom fields) with skills he is searching for his project (taxonomy).
There are users (with the Crew role) who have the asked skills (taxonomy again).
I want to create a view that displays users (crew) who have one or many of the skills asked for the project.
Is it possible?
Comment: Yes it is possible. But I doubt that is what you want to know :)
Comment: Yes ^^, I was more searching for a procedure  to make it work
Answer: Normally we do not do tutorials here, but I like EVA a lot, so here you go. :)
It can be achieved quite easy if you have some skills with views and EVA: Entity Views Attachment.
I assume you already set up the fields on the content type and user, and they are referring to the same taxonomy.
Now create a new view that lists 'user', do not add a page or block. In the top bar (below 'Displays' and next to master) add an 'EVA' display instead. In the middle column you limit this to content of you type. Leave the 'id' setting and optionally show the title:

Now to the right pane. Add a relationship from the user to your taxonomy. It will be called something like Taxonomy term referenced from field_skill. Then add a second relationship Content using field_skills. Finally, add a contextual filter for Content: ID and configure it like this:

To customize the display, add some user fields you want to display, or output rendered entities instead. You can control the display order of the EVA field on the Manage display tab of your content type.
How does this work?
It actually works in the reverse way we have configured it. EVA provides our view with the content ID we are looking at. This is provided as the first argument for the contextual filter.
By linking all users to nodes via the taxonomy and bv finally limiting that to only the node we are looking at via the contextual filter, we end up with all users that have one or more of the skills on the displayed node.
Good luck!


Python Module xattr has no attribute list

Question: I wrote a script which sets extended attributes on some files, with the module xattr. I successfully tested it in Ubuntu in python3, but it won't work on my RasperryPi.
I had to change a dozens of little errors, mostly like xattr not knowing its methods.
For example the xattr.set(...) has to be changed to xattr.setattr(...). But I failed at listing them. So I tried the just the basics and get the error:
import xattr
xattr.list('files.py')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'xattr' has no attribute 'list'

I had the idea that maybe python is using the wrong module (for python 2.7 instead of 3?). So I tried to uninstall the 2.7 module but got this:
...$ pip uninstall xattr
Traceback (most recent call last):
File "/usr/local/bin/pip", line 7, in <module>
from pip._internal import main
ImportError: No module named _internal

But I could successfully uninstall the python3 package. After that the "import xattr" still worked even in python3?
Comment: What do you get if you type `dir(xattr)` after importing? And `xattr.__file__`? It sounds like you might have a file names `xattr.py` in your current path and it's importing that instead.
Comment: For dir(xattr) i get a list (of methods?):  [... '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_fgetxattr', '_flistxattr', '_fremovexattr', '_fsetxattr', '_getxattr', '_lib', '_listxattr', '_removexattr', '_setxattr', 'compat', 'getxattr', 'integer_types', 'lib', 'listxattr', 'removexattr', 'setxattr', 'xattr'], wich seems like the old version of the module.  But how can I force python to use the new one, if I cant delete the old one (see error above)?
Comment: What do you get for `xattr.__file__`? That will tell you where it is importing it from.
Comment: '/home/pi/.local/lib/python3.5/site-packages/xattr/__init__.py'
Answer: Its 3am, listening to the glitch mob and since I went down this rabbit hole due to my curiosity...  I wanted to give you my example of code to use the python's built xattr module.
Create a file called xattr_example.py and put this code into it then run the file.
File:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
"""The Following Is An Example for xattr."""
# =============================================================================

import xattr

print("{}".format(xattr.__file__))
# '/usr/local/lib/python3.7/site-packages/xattr/__init__.py'

def showww_me_the_meta(file_name):
    """Using Python's XATTR to list Key Meta Names for File."""
    print("Showing Initial Names & Values.")
    attrz = xattr.listxattr(file_name)
    result = ("A. Info Showcased Init: {}".format(attrz))
    print("{}".format(result))
    return result

def update_the_meta(file_name):
    """Using Python's XATTR to Update Key Meta Names for File."""
    xattr.setxattr(file_name, 'custom.comment',
                   'I tawt I taw a puddy tat!.'.encode('utf-8'))
    xattr.setxattr(file_name, 'Music.Artist',
                   'I did! '
                   'I did taw a puddy tat!'.encode('utf-8'))
    get_the_meta_values(file_name)
    return

def get_the_meta_values(file_name):
    """Example."""
    print("B. Listing Meta for: {}".format(file_name))
    attrz = xattr.listxattr(file_name)
    print("")
    for i in reversed(attrz):
        abc = xattr.getxattr(file_name, i)
        result = ("{} : {}".format(i, abc))
        print("   {}".format(result))
    print("")
    return

def remove_the_meta(file_name):
    """Example."""
    xattr.removexattr(file_name, 'custom.comment')
    xattr.removexattr(file_name, 'Music.Artist')
    attrz = xattr.listxattr(file_name)
    result = ("C. Info Removed Meta: {}".format(attrz))
    print("{}".format(result))
    return result

if __name__ == '__main__':
    showww_me_the_meta('xattr_example.py')
    update_the_meta('xattr_example.py')
    remove_the_meta('xattr_example.py')

Result of running the file is:
$ python3 xattr_example.py
/usr/local/lib/python3.7/site-packages/xattr/__init__.py
Showing Initial Names & Values.
A. Info Showcased Init: ()
B. Listing Meta for: xattr_example.py

   custom.comment : b'I tawt I taw a puddy tat!.'
   Music.Artist : b'I did! I did taw a puddy tat!'

C. Info Removed Meta: ()

Lastly
As far as "import xattr" still worked even in python3?  Please note that python can be installed for both versions but have different paths.
python -V
# Python 2.7.16
which python
# /usr/local/bin/python

and
python3 -V
Python 3.7.4
which python3
/usr/local/bin/python3

You must use python or python3 respectively when calling python if you have more than one version listed.   I am working on a Mac OSX so I have both, but this script is was written in python3.
References:

Manual Pages
Using the xattr functions to get extended attributes.  <-- Found link from SO answer.
Limitations
Only usage examples that I could find.

Hope that helps!  Have a great one!
Comment: I also, added this to my Github repo https://github.com/JayRizzo/Random_Scripts/blob/master/xattr_example.py


How to store user location

Question: I use Smart IP module to track user location with option IPInfoDB.com. But as I understand Smart IP does not store by default user location in database. Is there any option to configure this or I need to make own module? Ultimately I need to show user who is in the same city or region.
Answer: No. Smart IP is solely for IP geolocation, it doesn't not touch storage of user location addresses.
Depending on your needs, Location (with the User Location submodule) or a combination of GeoField/Address Field on your a profile (you might want to guess the location while letting the user determine what his address) will get your location storage needs.
None of those modules have Smart IP integration so you'll have to build some custom code to add IP geolocation to either of those storage options.

How to store user location


How to kill threads in Julia?

Question: I am running three processes simultaneously by executing them through an Ipython notebook. I want to know what is the best way to kill any or all of the threads whenever I want.  I see that interrupting kernal in the notebook stops just the process 1.
Answer: From the Julia documentation:
interrupt([pids...])
Interrupt the current executing task on the specified workers. This is equivalent to pressing Ctrl-C on the local machine. If no arguments are given, all workers are interrupted.
Comment: And for the sake of completeness, `[pids]` is the vector being returned by `addprocs()`, e.g. when doing `addprocs(7)`, you should get back a `Vector{Any}` of length 7 with the ids of each remote process (2,3,...,8).

How to kill threads in Julia?


How to display an Angular Material mat-form-field as disabled with label and value

Question: I want to display a mat-form-field as disabled with label at the top and the value at the bottom in the input field. I tried <mat-hint> but it displays at the bottom.
What should I do to have the label at the top and input control at the bottom.

<mat-form-field appearance="outline">
    <mat-label>First Name</mat-label>
    <input matInput disabled placeholder="FirstName">
</mat-form-field>

Answer: in your component.ts import and add this providers
import { MAT_FORM_FIELD_DEFAULT_OPTIONS } from '@angular/material/form-field';

in your @Component({}) of your component.ts
providers: [{provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: {floatLabel: 'always'}}]

Your @Component({}) should look like this:
@Component({
  selector: 'mat-group-overview-example',
  templateUrl: 'mat-group-overview-example.html',
  styleUrls: ['mat-group-overview-example.css'],
  providers: [{provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: {floatLabel: 'always'}}]
})

you will achieve this <mat-form-field>


Proof that an infinite set stays infinite after subtraction of one element (under Dedekind's infinity defintion)

Question: After Dedekind, M is an infinite set if N $\subset$ M and f: M $\to$ N bijective. How do you prove that M - {b} (= taking one element b away from M) is infinite as well, just using this definition and functions? Is it possible? (Please make it as simple & step-by-step as you can since I am not a pro.)
Answer: Just to clarify, $M$ is Dedekind infinite if there exist a proper subset $N$ of $M$ such that there is a bijection $f:M\to N$.
Claim 1: Any superset of a Dedekind infinite set is also Dedekind infinite.
Say $A$ is Dedekind infinite and $B$ a superset of $A$. Let $C$ be a proper subset of $A$ and $f:A\to C$ a bijection. Then, $f$ extends to a bijection $g:B\to C\cup (B\backslash A)$ which is the identity on $B\backslash A$ and $f$ on $A$. Hence $B$ is Dedekind infinite.
Claim 2: Dedekind infiniteness is preserved by bijection i.e. if there is a bijection between sets $A$ and $B$ and $A$ is Dedekind infintie then so is $B$.
Suppose $M$ is Dedekind infinite, $N$ a proper subset of $M$ and $f :M\to N$ is a bijection. By Claim 2, $N$ is Dedekind infinite.
As $N$ is a proper subset of $M$, $N$ is a subset of $M\backslash\{m\}$ for some $m\in M$.  By Claim 1, as $M\backslash \{m\}$ is a superset of $N$, $M\backslash \{m\}$ is also Dedekind infinite. Finally, for any $b\in M$ there is a clear choice bijection from $M\backslash \{m\}$ to $M\backslash \{b\}$ and so $M\backslash \{b\}$ is Dedekind infinite as desired.
Comment: I can edit to prove either claim if needed.
Comment: Can u prove it without your two claims too?
Comment: I would guess any reasonable step by step solution would need these claims implicitly at least.
Comment: Ok, could u prove claim 1?
Comment: See the edits above.
Comment: I have problems with your proof - using claim 1 - that a set stays infinite even if you take away one element. Claim 1 - and I proved that meanwhile for myself - says that any superset of a dedekind-infinite set is also dedekind-infinite. But in your proof M\{m} is just a superset of N and N is not necessarily dedekind-infinite. Only M was assumed dedekind-infinite. Can u somehow rescue the proof?
Comment: $N$ is dedekind infinite as it is in bijection with $M$. Claim 2 is used for this. To be explicit $f(N)$ is the proper subset of $N$ that $N$ is in bijection with.


Get calendarweek of an NSDate according ISO 8601

Question: is there a way to get calendarweek of an NSDate according ISO 8601.
I think:
<code>Datecomponents *dateComponents = [cal components:(NSWeekOfYearCalendarUnit ) fromDate: testDate ];
int calandarWeek =  [dateComponents weekOfYear];
</code>
uses a different algorithm.
ISO definition: CW1 is the first week in the year containing 4 day, CW start on Mondays
Answer: I found out.
It´s possible to configure the NSCalender:
<code>[cal setFirstWeekday:2];            //week starts on Monday
[cal setMinimumDaysInFirstWeek:4];  //first week in the year containing 4 day
</code>


Is it safe to boot a linux server from a USB drive?

Question: I have an HP DL360 G7 server I plan to install KVM and ZFS on. The purpose is going to be a lab in a box. I have the 8 drive bays in the front loaded with 4 drives and an SSD (for the ZFS ZIL cache). My goal was to keep the disk array away from the actual OS disk. What I am wonder is weather or not it is safe to boot a Linux server installation from a USB drive for "production" use. The server has an embedded USB / SD card reader on the motherboard for VMware and other embedded solutions. This raises a question to me because once VMware is loaded it stay in memory. On the other hand a Linux install does not (atleast not 100%). I am concerned if I load the OS on a USB drive (or SD card) I will burn the SD card out.
Can anyone please give me some insight on this? I am wondering what my options are. The way I see it my options currently are make Linux boot from the ZFS array or use a USB drive. The first option would be okay if I could make grub play nice with ZFS root booting. Which to my knowledge is broken or at least needs some nasty hack to pull it off.
Like I said any help you could provide would be great.
Answer: You can, but you probably shouldn't.
The DL360 G7 doesn't present disks in a JBOD fashion. If you're using the onboard HP Smart Array controller, this won't work the way you expect.
Depending on the OS you use, there are swap and other I/O activity considerations.
Why go through all of this? If you want ZFS, just use it on the server in a baremetal OS installation. ZFS root is not great... however, you have an HP controller that's capable of multiple logical drives and better reporting/monitoring than you'd get otherwise. The ZIL SSD is probably not even necessary.
See: ZFS best practices with hardware RAID
Can you give a better idea of why you wanted to keep the OS and data drives separate?
Comment: I actually swapped out the controller for an lsi 9211-8i.
Comment: My take... just use hardware RAID with ZFS atop. Otherwise, you have to deal with wasted disk capacity, finding a place to house the OS, needing a ZIL device and less monitoring. If not, just install Linux using the LSI controller and ZFS software RAID. I would not use USB boot unless you are willing to deal with a failure of the boot device. You could also partition the SSD for boot/ZIL duties.
Comment: well I originally wanted to keep it separated for format reasons. if I install Linux on an ext4 partition then I can't dedicate the drive to zfs.
Comment: yeah I think I will just install everything on the raid. do you know if modern grub2 packages support zfs root?
Comment: I don't deal with or recommend ZFS root. But the [ZFS mailing list](http://list.zfsonlinux.org/mailman/listinfo/zfs-discuss) may be able to help.
Comment: I don't recommend putting ZFS on top of hardware RAID, and I'm not the only one. You lose almost all the data integrity benefits of ZFS if you put it on top of hardware RAID. Far better to have a separate OS disk on USB.
Comment: @qasdfdsaq ZFS isn't just about data integrity. It's an excellent volume manager. And in cases where boot, hardware support and other considerations are factors, you can't make a blanket statement like that.
Comment: @ewwhite: I can exactly make a blanket statement like that because it is 100% correct.
Answer:
Is it safe to boot Linux from a USB drive?

Yes, why not? I do it regularly.  But having said that, it's not entirely trivial to do it well.  If you just straight install Linux to a USB disk it's usually really slow and doesn't really work that great.
However, if you use a tool like unetbootin it'll create a more optimal installation with which you can also install some configuration.
FreeNAS actually is designed to run this way, so that you have all of your HDD's and SSD's available for storage and the OS is booted off flash onto a RAM disk.  Although FreeNAS is not Linux based, I mention it here to tell you this is not an unusual solution and is used in production.
When/if you do get it to work, make sure you back up your USB stick every time you make changes to it's stored configuration.
Comment: (This isn't FreeNAS)
Comment: @ewwhite - Obviously! at least to you and I. It's also FreeBSD based. I mentioned it here, because flash booting is a practical thing to do in a production environment and widely done.
Comment: I don't think it's that practical anymore. Again, I'm coming from the VMware world, but I've seen tremendous failure counts at scale with ESXi [(_which is optimized for USB/SD_)](http://serverfault.com/questions/549253/what-happens-when-the-usb-key-or-sd-card-ive-installed-vmware-esxi-on-fails/550282#550282), so the novelty of flash boot isn't worth the time for me.
Comment: Sounds like despite the claim, ESXi is just not optimized for USB/SD.  It should boot to RAM disk and only store config data on the USB/SD.  If it's not doing that, then it's going to wear out the USB stick very quickly.
Comment: He mentions ESXi, but it sounds like that's not the scenario he is planning to use it in anyway.
Answer: Define "safe". As in:

Does the system boot from USB? Yes
Data integrity? No
Fault tolerance? No

I would not trust a file server to be booted from a single USB pen, unless it's a server just for testing/lab etc. We use USB drives (expensive ones) in our vSphere Cluster, and I've encountered failures many times.
You've indicated that you have replaced the built-in smartarray controller with a LSI HBA card. If I were you I'd dedicate two drives (2x200GB MLC SATA SSD or similar) for the operating system + swapfile, and create some sort of mirror on them. I have no idea if Linux can boot from ZFS in a stable manner, so you should consider using the operating systems native software raid with a common, trusted filesystem on top (ext3, ext4, xfs).
Comment: Yeah, the OP sounds like they do not have enough resources to do this with the right number of disks, but this is the answer. Definitely use a pair of OS drives.


How to calculate arc start position

Question: I'm working on an interactive pH spectrum in JavaScript! Here is an image of what I have so far EXAMPLE!
What I want to calculate is the startPos and endPos (with offset) of each pH level (the text 0,1,2,...)!
At the moment if you look on the image provided I added the levels customly by giving hard values! However I want to provide a formula that would allow my program to calculate this automatically!
FYI I'm working with a half circle and the starting position is 180 and ends at 360 degrees! That's how JavaScript works!
The values I know:

The center of the circle!
The degree of each arc (12.9)
The startPos and endPos of each arc (eg. x:180, y:192.9)

I want to calculate the X Y position of the black dots in the image!

UPDATE:
My program works as expected but I'm not sure if the math matches.
function draw_preferred_ph(minValue, maxValue){
  //Font Settings
  stroke(0);
  strokeWeight(1);

  //Original value of theta = 12.9
  //FORMULA : input * (theta -1) + 180 + trunc(input)
  var startDeg = minValue*11.9+180+Math.trunc(minValue);
  var endDeg = maxValue*11.9+180+Math.trunc(maxValue);

  //Draw arc representing minimum and maximum pH levels!
  squareColor = color(100, 50, 100);
  squareColor.setAlpha(100);
  fill(squareColor);

  //PARAMS: startX,startY, W, H, startDegree, FinishDegree, TYPE:PIE
  arc(0,0,r*2,r*2,startDeg,endDeg,PIE);

  ///DRAW LABELS OF MIN AND MAX VALUES
  noStroke();
  fill(0, 102, 153);

  text("MIN pH:  " + minValue, -340,-320)
  text("MAX pH:  " + maxValue, 160, -320);
}

WORKING EXAMPLE
Comment: This is straightforward trigonometry, which javascript knows.https://www.youtube.com/watch?v=3hPn8YMAhFk
Answer: As Ethan Bolker suggested, this can be done with help of trigonometric functions. Let $\{c_h,c_v\}$ denote be the coordinates of the center and $r$ the radius of the circle. As you need to place $15$ dots, the angular distance between them is $12$, and the position of the $n^{th}$ dot should be $$\{x,y\}=\{c_h+r\cos (180+12 n),c_h+r\sin (180+12 n)\}$$
Comment: I have updated my question. The formula I'm using is the following `FORMULA : input * (theta -1) + 180 + trunc(input)`! Please remember that I'm using `theta-1` I don't know why but it works. And that I working with half a sphere!

How to calculate arc start position


How to prove that $\lim_{x\to\infty }\sum_{n=0}^\infty \frac{x^{2n+1}( -1)^n}{n!(2n+1)2^n}$ = $\frac{\sqrt {2π}}{2} $

Question: We are learning at the moment the Gauss curve in math class and my teacher told me that the area under the graph is 1. When I asked for its proof, she said that it requires some crazy application of integral-techniques which wouldn't be obvious to come up with, which I accepted at that time, but it bothered me at home and I gave it a try to prove it but by using the Taylor series. I'll spare you the calculation, but I have proven(using the ratio test) that it's possible that the following power series for any real value x(including $+\infty$) will converge: $\sum_{n=0}^\infty  \frac{x^{2n+1}( -1)^n}{n!(2n+1)2^n}$ I have put this into my calculator and found that it would be equal to $\frac{\sqrt {2π}}{2} $ , which if proven, would immediately imply that the area is indeed 1. But this is easier said then done, so could you help me with proving that this power series will equal to $\frac{\sqrt {2π} }{2}$ for x going to $+\infty$? I would highly appreciate it.
Comment: You've been here long enough to realize that it's customary to use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to format math on this site. To begin with, enclose all math expressions (including numbers) in `$` signs. For example, `$x_1^2$` will give you $x_1^2$. You'll get a much better response if your posts are easy to read.
Comment: The way it's normally shown is by taking the integral squared,  using powerful math to say that you can convert that into a double integral,  then convert it into polar coordinates which makes the integration trivial, fyi
Comment: It should be readable by now.
Answer: Verify that the radius of convergence of this series is $\infty$. We therefore have the function
$$f(x)=\sum_{n=0}^\infty \frac{x^{2n+1}( -1)^n}{n!(2n+1)2^n}\qquad(-\infty<x<\infty)\ .$$
It follows that
$$f'(x)=\sum_{n=0}^\infty{(-x^2/2)^n\over n!}=e^{-x^2/2}\ .$$
As $f(0)=0$ we therefore obtain
$$f(x)=\int_0^x f'(t)\>dt=\int_0^xe^{-t^2/2}\>dt\to{\sqrt{2\pi}\over2}\qquad(x\to\infty)\ .$$
Answer: Let $J=\int_{-\infty}^{+\infty}e^{-x^2}dx.$ Then $$J^2=\int_{-\infty}^{+\infty}e^{-x^2}dx \cdot\int_{-\infty}^{+\infty}e^{-y^2}dy=$$ $$=\int\int_{(x,y)\in \Bbb R^2}e^{-x^2-y^2}dxdy.$$ Converting to polar co-ordinates,i.e. $x=r\cos t,\,y=r\sin t$ with $r\in [0,\infty)$ and $t\in [0,2\pi),$ we must replace $dxdy$ with $rdrdt,$ and we also have $x^2+y^2=r^2 ,$ so $$J^2=\int_{t=0}^{2\pi}\left(\int_{r=0}^{+\infty}re^{-r^2}dr\,\right)dt=\int_{t=0}^{2\pi}(1 /2)dt=\pi.$$
[ If  $u=r^2$ then $\int re^{-r^2}dr=\int e^{-r^2}d(r^2)/2=\int e^{-u}du/2=-e^{-u}/2=-e^{-r^2}/2. ]$
More cautiously, for $A>0$ let $$S(A)=\int_{|x|\le A}\int_{|y|\le A}e^{-x^2-y^2}dxdy$$ and let $$C(A)=\int\int_{x^2+y^2\le A^2}e^{-x^2-y^2}dxdy=\int_{t=0}^{2\pi}\int_{r=0}^Are^{-r^2}drdt=2\pi\frac {1-e^{-A^2}}{2}.$$  We have $C(A)<S(A)<C(A\sqrt 2),$ while $S(A)\to J^2$ and $C(A)\to\pi$ as $A\to\infty.$


How many ways are there to distribute three different pens and nineteen identical pencils...?

Question: How many ways are there to distribute three different pens
and nineteen identical pencils to five people, if no person gets more than
two pens, and such that everyone gets at least one pen or pencil?
Attempt 1:
There's C(14 + 5 - 1, 5-1) = C(18, 4) = 3060 ways to distribute 19 pencils to 5 students if each receives at least one pencil.
Do I multiply this result with the result of finding how many ways to distribute the pens? I think I may have misinterpreted the question because the part about everyone getting at least one pen or pencil really confuses me.
Attempt 2:
Case 1: One student gets 2 pens. Choosing the 2 pens is C(3, 2) = 3. Then, 3*5 because there are 5 possible students who can get 2 pens. Now there's only 1 pen to distribute and there's 4 ways of doing that. Next, we have to take away 3 pencils leaving us with 16 pencils to distribute to 5 students.
Let x = pen and y = pencil
2x|x|y|y|y
So there's C(20, 4) = 4845 ways of distributing the pencils. The total for case 1 is 3*5*4*4845 (not sure if we multiply or add the 4845)
Case 2: 3 students receive 1 pen. 3! = 6 ways of distributing the pens. Now we distribute 17 pencils, so C(21, 4) = 5985. The total for case 2 is 6*5985
The overall total is the sum of the two cases, so 326610.
Comment: Is it given that all of the pens and pencils must be used? If not, the question is quite different.
Comment: I'm pretty sure that all pens and pencils are supposed to be used.
Comment: OK. Since it seems that one person can have a pen, but not a pencil, I think that the best way to do this problem is to not account for pens and pencils, find the number of ways to distribute them, and then use combinations to find how the number of ways is changed by the fact that we need to account for pens and pencils.
Comment: Hmmm, I don't know if it reads as one person with a pen cannot have a pencil.
Comment: No, but there are cases where we need to account for people having pens but not pencils which somewhat complicates things. This will make more sense if you read my solution below.
Comment: Your second attempt is nearly correct.  Since there are five students, you should have $P(5, 3) = 5 \cdot 4 \cdot 3 = 60$ ways of distributing the pens in case 2.
Answer: We distribute the pens first.
There are two cases:

The three pens are distributed to three people of the five people.

This can be done in $5 \cdot 4 \cdot 3$ ways since there are five ways of choosing the recipient of the first pen, four ways of choosing the recipient of the second pen, and three ways of choosing the recipient of the third pen.
That leaves two people who have not received a pen.  Since each person receives at least one pen or pencil, we give each of those two people one of the $19$ identical pencils.  There are now $17$ identical pencils to distribute to $5$ people.  Let $x_k$ be the number of remaining pencils distributed to the $k$th person.  Then
$$x_1 + x_2 + x_3 + x_4 + x_5 = 17 \tag{1}$$
This is an equation in the non-negative integers.  The number of solutions of equation 1 is the number of ways four addition signs can be inserted into a row of $17$ ones, which is
$$\binom{17 + 4}{4} = \binom{21}{4}$$
since we must choose which four of the $21$ symbols (four addition signs and seventeen ones) will be addition signs.  In this case, the number of ways of distributing three different pens and $19$ identical pencils to five people so that each person receives at least one pen or pencil is
$$5 \cdot 4 \cdot 3 \cdot \binom{21}{4}$$

The three pens are distributed to two of the five people.

There are five ways of selecting one person to receive two of the three pens.  There are $\binom{3}{2}$ ways of selecting which two of the three pens that person receives.  There are four ways of selecting the person who receives the third pen.  Hence, the number of ways of distributing the pens to two of the five people is
$$5 \cdot \binom{3}{2} \cdot 4$$
That leaves three people who have not received a pen.  Since each person receives at least one pen or pencil, we give each of those three people one of the $19$ identical pencils.  That leaves $16$ pencils to distribute to $5$ people.  Let $x_k$ be the number of pencils distributed to the $k$th person.  Then
$$x_1 + x_2 + x_3 + x_4 + x_5 = 16 \tag{2}$$
Equation 2 is an equation in the non-negative integers with
$$\binom{16 + 4}{4} = \binom{20}{4}$$
solutions.  In this case, the number of ways of distributing the pens and pencils to the five people so that each person receives at least one pen or pencil is
$$5 \cdot \binom{3}{2} \cdot 4 \cdot \binom{20}{4}$$
In total, the number of ways of distributing three different pens and five identical pencils to five people so that no person receives more than two pens and so that each person receives at least one pen or pencil is
$$5 \cdot 4 \cdot 3 \cdot \binom{21}{4} + 5 \cdot \binom{3}{2} \cdot 4 \cdot \binom{20}{4} = 60\left[\binom{21}{4} + \binom{20}{4}\right]$$
Comment: @user84413  Thanks for the compliment.
Answer: I am going to split this problem into three parts:

Find the number of ways we can distribute $3$ pens and $19$ pencils to $5$ people so that each person has either one pen or one pencil.
Find the number of ways we can distribute $3$ pens and $19$ pencils to $5$ people so that each person has either one pen or one pencil and one person has all $3$ pens.
Subtract the former by the latter to get our answer where no one has more than $2$ pens.

Part 1:
First, let's forget about pens and pencils. We have $22$ writing utensils in all and we need to distribute them to $5$ different people. By stars and bars, there are ${22-1 \choose 5-1}=5985$ ways to distribute these writing utensils.
Now, let's account for pens and pencils. There are $22!$ different possible ways we can order the pens and pencils so different people get different writing utensils. However, if we switch two pencils, then nothing will change, so we need to divide this by $19!$. Thus, we get $\frac{22!}{19!}=9240$ as the number of different ways we can order the pens and pencils. If we multiply this by the number of ways to distribute $22$ writing utensils, we get $9240*5985=55301400$, which is our answer for Part 1.
Part 2:
There are two cases for this part: The case where everyone has at least one pencil (Case 1) or the case where everyone except one person has pencils and the one person without pencils has all of the pens (Case 2). Our answer for Part 2 will be the sum of the answers for these cases.
Case 1:
The number of ways to give $5$ people $19$ pencils so that every person has at least one pencil is, as you said, $3060$. We need to multiply this by the number of ways we can distribute all of the pens. Since one person must have all of the pens and there are $5$ people, there are $5$ ways to distribute all of the pens. Therefore, our answer to Part 2 is simply the product of these two numbers, or $3060*5=15300$.
Case 2:
If all but one person has pencils, then we need to distribute $19$ pencils to $4$ people. By stars and bars, this is ${19-1 \choose 4-1}=816$. Now, we need to distribute all of the pens to the last person. There is only one way to do this. However, since there are $5$ people, there are $5$ different ways to choose this last person, so we need to multiply the number of ways we can distribute the pencils by $5$. This gives us $816*5=4080$.
By adding our answers from both cases, we find that our answer to Part 2 is $15300+4080=19380$.
Part 3:
By subtracting our answer from Part 1 by our answer from Part 2, we get $55301400-19380=55282020$, which is the number of ways $3$ pens and $19$ pencils can be distributed to $5$ people so that each person has either one pen or one pencil and no person has more than $2$ pens. Thus, we have solved the problem.
Comment: The 3 pens are actually different from one another. Does that change anything? I think part 1 should be 9240*5985 if that is the case. Not sure if it will change anything in part 2.
Comment: @helpme You're right, if the $3$ pens are different, then Part 1 becomes $9240*5985$ and nothing changes for Part 2. I've edited the answer accordingly.


How to sample uniformly from ten urns with ten balls each

Question: I have ten numbered urns with numbered 10 balls in each. I want to draw $n<100$ balls in a uniform distribution from all $100$ balls (the urns and all balls are distinct.) My procedure: I roll a 10-sided die to decide on the urn and then another one to decide on the ball in it. For the first draw, every ball has $p=0.01$.) But for the second draw it could happen with the same $p$ that my dice indicate the same ball as before that has been removed. Should I now:

repeat the process of throwing both dice so many times that I get
a ball that hasn't been drawn?
just repeat the second die roll
and stay in the same urn?

Both seemed biased. In 1. the result would be that I might do more than $n$ iterations and in 2. it seems that the probability for a ball in an urn that has been chosen before goes up (resulting in a nonuniform distribution.)
What procedure needs to be done to result in a uniform distribution?
Comment: The problem with your method is:  once you draw a ball you have to reduce the probability that you repeat the same urn (else the other balls in that urn have a greater chance of being picked next).  Hard to implement with dice.  Your first method works but, as you say, it is inefficient.
Answer: Your first approach will give a uniform distribution.  Even after you have removed $k$ balls, each of the remaining $100-k$ balls has $0.01$ chance to be picked on one roll.  The downside is you have to roll a lot of times-when you get to $2$ balls you expect to need $50$ rolls to pick one of them.  This is the coupon collector's problem but you don't need to pick the last coupon because presumably when you have picked $99$ balls you can just pick the last without rolling.  Your expected total number of rolls is $100H_{100}-100\approx 418$ rolls.
Your second approach is biased.  If the first five balls come out of the same urn, the remaining balls have chance $0.02$ to be picked while all the other balls still have chance $0.01$ to be picked.
An improvement is to recognize that you have essentially numbered the balls $00$ through $99$.  You can keep track of the order of the remaining balls, so when you roll $26$ you pick the $26^{th}$ ball of the remaining set instead of ball $6$ from urn $2$.  The advantage comes when you have removed $50$ balls.  Now you can assign two numbers to each ball and increase the odds the number is small enough to find a ball.  Once you have removed $67$ balls you can give each ball $3$ numbers and so on.
More efficient yet is to note that $100! \approx 9.3\cdot 10^{157}$  You can roll $158$ numbers from $00$ through $99$ and use them to pick a specific permutation of the balls.  You have only about a $7\%$ chance of getting too high a number to use.  You can start over, or use the number you have and roll a time or two more.  The last will take some thought how to make it work.


Matlab ODE45. How to change a function inside it while calling it?

Question: The functions w_d(Y,T) and q(tg,tm) are being used in a function called by the ODE solver described below:
function dPdh=gasstep1(~,P)
global rho_solid W_B S e height_dryer c_a c_b tm_o

dPdh=zeros(size(P));
Y=P(1);tg=P(2);

% Mass Balance
dPdh(1)=rho_solid*(1-e)*S*height_dryer/W_B*w_d(Y,tg);
% Enthalpy balance
dPdh(2)=-rho_solid*(1-e)*S*height_dryer/W_B*(1/(c_b+c_a*Y))...
         *(q(tg,tm_o)+(c_a*(tg-tm_o)*w_d(Y,tg)));

dPdh=[dPdh(1)
      dPdh(2)];

end

The ODE solver is called in the following manner:
tspan=linspace(0,height_dryer,100);
format long
[h,P]=ode45(@(h,P)gasstep1(h,P),tspan,[Y_o tg_o]);

The values from the generated arrays and P are used in a for loop to compute variables:
X1=zeros(1,Nh);Tm=zeros(1,Nh);
X1(1,1)=X_o;Tm(1,1)=tm_o;

for i=1:Nh-1
    % Mass balance
    X1(1,i+1)=X1(1,i)-dt*((P(i+1,1)-P(i,1))/(h(i+1)-h(i)))*(W_B/S)*(1/(rho_solid*(1-e)));
    % Enthalpy balance
    Tm(1,i+1)=Tm(1,i)+dt*(1/(c_s+c_al*X1(1,i)))*(q(((P(i+1,2)+P(i,2))/2),Tm(1,i))-...
              ((c_a-c_al)*(Tm(1,i))+hv(Tm(1,i)))*w_d((P(i+1,1)-P(i,1)),     ((P(i+1,2)+P(i,2))/2)));
end

The doubt I have is whether the variables in the function w_d and q also change when I call the ODE solver in a loop. I found a method to implement the ODE solver in a loop on the mathworks website (link). I have found help provided when ODE parameters need to be changed (link).
I think my final code should look something like:
for j=2:Nt
    for i=1:Nh-1
        % compute X1 & Tm
    end
    % change variables in function w_d and q
    % [call the ODE]
end

Could anyone please give me an idea on how to start the loop which would help me to complete the code.
Comment: I'm not sure what your question is. I don't know what you mean by "an idea on how to start the loop." You've posted a lot of specific code that may matter to you, but just ends up confusing and cluttering your fundamental question. I can only suggest that you learn about [function handles](http://mathworks.com/help/matlab/function-handles.html) and in particular [parametrizing functions](http://www.mathworks.com/help/matlab/math/parameterizing-functions.html). You can start by [not using global variables](http://math.stackexchange.com/a/572169/80812) inside of your integration function.
Answer: The links you pointed to should answer your question: you could make w_d and q parameters of the gasstep function, and use the function parameterization as in the second link you posted.
From the code you posteed, I understand that you want w_d and q to be dependent on X1 and Tm, right? I'm going to assume that's the case. If they depend on other parameters, just use those instead of X1 and Tm in my explanation:
make gasstep1 dependent on X1 and Tm and pass them along to w_d and q: your gasstep1 function now has 4 arguments: gasstep1(h, P, X1, Tm), and w_d and q also (w_d(Y, tg, X1, Tm) for instance). Then you only need to create gasstep2 as such:
gasstep2 = @(h,P) gasstep1(h,P,X1,Tm)

and you can call ode45 on gasstep2!
Be careful that in your final code, if you write it like you presented above, X1 and Tm are going to depend on P, which needs to be initialized!
Comment: Thank you for your answer/help and I did end up finding the answer to my question in one of the links that I posted.
Comment: @winoi Happy to help, and welcome to Stack Overflow. If this answer helped solving your issue, please mark it as accepted! Happy coding!
Comment: Hi @Etienne Pellegrini, if I do this, I dont need to use "interpolation" in ODE45, right?


UITapGestureRecognizer with exact number of taps

Question: I would like to respond to multiple taps on a UIView. For example, I should be able to tap the view five times for one action, and ten times for another action. But - each action should not be triggered by any number of taps other than it's prescribed count. I.e. the five-tap action should not fire after six taps or ten taps, and the ten-tap action should not fire after eleven taps.
Is this possible with a UITapGestureRecognizer?
Answer: Yes it is possible,
but you must measure out the numberOfTapsRequired and requireGestureRecognizerToFail usage.
You can discard the taps that you won't use and trigger what you want in the method only on the number of taps that you want.
You can see an example of the usage here.
Comment: Do you mean I should add a gesture recognizer for every integer between five and ten, and require my actual gestures to fail for each one? What about 11+?


Problema para mudar classe no React que possui Menu responsivo Bootstrap

Question: Estou fazendo um site com Bootstrap e ReatJs e nesse site tem um menu responsivo. Este menu assemelha-se a isso (exemplo):

Dashboard
Cadastro

Usuário
Administrador

Cada vez que eu clico em um dos itens do menu é colocado pelo NavLink um active no className para mudar a cor do item do menu, até aí está funcionando tudo normalmente, o problema é que eu quero que mude a cor do menu, mas quando for um submenu quero que mude por exemplo a cor do menu "Usuário" e também do "Cadastro", pois a página "usuário" está dentro de "cadastro". Tenho tentado fazer isso mas ainda não consegui. O Código para isso é este:
Tenho o Menu que vai chamando para montar o menu que eu quero: Menu.jsx
<MenuItem path='/' label='Dashboard' exact={ true } icon='home' />
<MenuTree label='Cadastro' icon='contacts' id='cadastro'>
    <MenuTreeItem path='/user' label='Usuário' />
    <MenuTreeItem path='/admin' label='Administrador' />
</MenuTree>

O MenuItem funciona normalmente, pois não tenho esse submenu. Para o MenuTree o código é esse e aqui que está o problema.
MenuTree
import React from 'react'

class MenuTree extends React.Component {

hasActiveLink = () => {
    return (document.querySelectorAll(`#ul_${ this.props.id } a.active`).length === 0) ? "" : "active";
}

render() {
    this.classActive = this.hasActiveLink();

    return (

            <a className={`nav-link ${ this.classActive }`} data-toggle="collapse" href={ `#${ this.props.id }` } aria-expanded="false" aria-controls={ this.props.id }>
                { this.props.label }

                <i className={`mdi mdi-${ this.props.icon } menu-icon`}>

                <ul className="nav flex-column sub-menu" id={ `ul_${ this.props.id }` }>
                    { this.props.children }

        )
    }
}

export default (MenuTree)

Tenho o MenuTreeItem
import React from 'react'
import { NavLink } from 'react-router-dom'

export default props => (

    <NavLink className="nav-link" to={props.path} exact={props.exact} activeClassName="active">{props.label}</NavLink>

)

Como pode ser verificado, no caso de eu clicar em um MenuTreeItem, ele é alterado e inserido o active no class e assim funciona, porém não muda o MenuTree que é o parent, então eu fiz a função "hasActiveLink" que verifica se tem algum link dentro dessa tree com o active na class, mas isso funciona com erro, pois só aparece o active no meu menu principal, no caso o "Cadastro" quando eu clico pela segunda vez, pois pelo que percebi ele verifica o estado sempre anterior ao do clique, pois só é acionado depois da renderização, assim só na próxima vez é alterado a classe do meu menu principal. O que eu posso fazer para pegar essa informação do child e colocar o active no parent?
Obs.: Já tentei colocar também em todas as funções do próprio react, como por exemplo "componentDidUpdate".
Answer: Consegui resolver da maneira descrita abaixo. Não sei se é a melhor alternativa, mas agora está funcionando perfeitamente.
import React from 'react'
import { withRouter } from "react-router-dom"

class MenuTree extends React.Component {

    constructor(props) {
        super(props);
        this.classNameNoActive = ""
        this.classNameActive = "active"
        this.classActive = this.classNameNoActive;
    }

    getActiveChild = () => {

        const { match, location } = this.props
        var activeChild = false;
        var arrayChildren = this.props.children

        if (arrayChildren.length === undefined) {

            if (location.pathname === arrayChildren.props.path)
                    return true
        } else {
            for(var i = 0; i < arrayChildren.length; i++) {

                if (location.pathname === arrayChildren[i].props.path)
                    return true
            }
        }

        return activeChild
    }

    render() {
        this.classActive = (this.getActiveChild()) ? this.classNameActive : this.classNameNoActive
        return (

                <a className={`nav-link ${ this.classActive }`} data-toggle="collapse" href={ `#${ this.props.id }` } aria-expanded="false" aria-controls={ this.props.id }>
                    { this.props.label }

                    <i className={`mdi mdi-${ this.props.icon } menu-icon`}>

                    <ul className="nav flex-column sub-menu" id={ `ul_${ this.props.id }` }>
                        { this.props.children }

        )
    }
}

export default withRouter(MenuTree)


Room Flow Always returns kotlinx.coroutines.flow.SafeFlow@c8abe2e

Question: Initially i am getting list data from network and store it in room db.
It is One to Many Relationship. For that i have created Two Tables and One Relationship data class
Product Table :
@Entity(tableName = "Product")
data class Products (

    @PrimaryKey(autoGenerate = false)
    @ColumnInfo(name = "id")
    var id : Int = 0,

    @ColumnInfo(name = "name")
    var name  : String? = null,

    @ColumnInfo(name = "category_id")
    var category_id : String? = null,

    @ColumnInfo(name = "subcategory_id")
    var subcategory_id : String? = null,

    @ColumnInfo(name = "variants")
    var variants : List<Variants> = listOf()
)

Variant Table :
@Entity(tableName = "Variant")
data class Variants (

    @PrimaryKey(autoGenerate = false)
    @ColumnInfo(name = "id")
    var id : Int  = 0,

    @ColumnInfo(name = "product_id", index = true)
    var product_id : Int?  = null,

    @ColumnInfo(name = "measurement")
    var measurement : String?  = null,

    @ColumnInfo(name = "price")
    var price : String?  = null
)

Product With Variants ( Relationship between Two Tables )
  data class ProductWithVariants(
    @Embedded val product: Products,
    @Relation(
        parentColumn = "id",
        entityColumn = "product_id"
    )
    val variants: MutableList<Variants>
)

Dao : I get the ProductsWithVariants data using query and also filter by subcategory_id
@Transaction
@Query("SELECT * FROM Product WHERE subcategory_id=:subcat")
fun getProductWithVariants(subcat:Int): Flow<MutableList<ProductWithVariants>>

ViewModel :
var productListN: Flow<MutableList<ProductWithVariants>> = flowOf(mutableListOf())

fun networkproductlist() = viewModelScope.launch(Dispatchers.IO) {
    productist.collectLatest {
        when (it) {
            Resource.Empty -> {
                Log.e("product", "" + "empty")
            }
            is Resource.Failure -> {
                Log.e("product", "" + "failure")
            }
            Resource.Loading -> {

            }
            is Resource.Success -> {
                val response = it.value
                for (i in 0 until response.data.size) {
                    val product: Products = response.data.get(i)
                    for (j in 0 until product.variants.size) {
                        variants = product.variants.get(j)
                    }
                }
                productsDao.deleteAllProducts()
                productsDao.insertProducts(response.data)
                productsDao.insertVariants(variants!!)
                val subcategoryid = SubCategoryList(response.data[0].subcategory_id!!.toInt())
                productsDao.insertSubCat(subcategoryid)
                productListN = productsDao.getProductWithVariants(response.data[0].subcategory_id!!.toInt())
                Log.e("product","product in room viewmodel : $productListN")
            }
        }
    }
}

As I said earlier , got the network response in success resource and insert products and variants in respective tables after that i insert the product subcategory in my database and get the list of  ProductWithVariants by hit the getProductWithVariants() on the next line ..
The Problem here is now - i always get kotlinx.coroutines.flow.SafeFlow@f06e8a9 as a response of productlistN
Main Activity :
lifecycleScope.launch(Dispatchers.Main) {
    proadapter = ProductAdapter()
    binding.ProductRecyclerView.apply {
       adapter = proadapter
    }
}

lifecycleScope.launch(Dispatchers.Main) {
    viewModel.productListN.collect {
        println("Received UserInfo List $it")
        proadapter.setMutableArraylist(it)
        proadapter.notifyDataSetChanged()
    }
}

Comment: What is the problem with getting `kotlinx.coroutines.flow.SafeFlow@f06e8a9` as a response? Doesn't it work as intended? It seems it's how the Dao code is generated.
Comment: my flow collect not collect any data in main activity @Sergio and also i updated my Main Activity Collect Code Please see...why my data is not displayed in ui
Comment: please try to initialize `proadapter` and `binding.ProductRecyclerView` outside of `launch` function, and for collecting `Flow` data just use `lifecycleScope.launch { ... }`.
Comment: still i cannot get data in main activity itself from viewmodel @Sergio
Answer: I found a couple of issues in your code:

In ViewModel you use var productListN = ... and then reinitialize it with a new object productListN = productsDao.getProductWithVariants(response.data[0].subcategory_id!!.toInt()). You shouldn't reinitialize it, you must use the same object. You can try to use StateFlow or SharedFlow to emit data:

val productListN: Flow<MutableList<ProductWithVariants>> = StateFlow(mutableListOf())
...
productListN.value = ...

In Activity initialize proadapter and binding.ProductRecyclerView outside of launch function, and for collecting Flow data just use lifecycleScope.launch { ... }:

proadapter = ProductAdapter()
binding.ProductRecyclerView.apply {
    adapter = proadapter
}

lifecycleScope.launch {
    viewModel.productListN.collect {
        println("Received UserInfo List $it")
        proadapter.setMutableArraylist(it)
        proadapter.notifyDataSetChanged()
    }
}


CodeTemplate em .net core [scaffolding]

Question: Como em .net core 2.0 faço para criar os templates custom do scaffolding?
No sistema antigo .net 4.6 copiava a pasta CodeTemplates para o projeto.
No .net core < 2 instavala o
Microsoft.VisualStudio.Web.CodeGenerators.Mvc

Depois acessava a pasta:
C:\Users\{User}\.nuget\packages\Microsoft.VisualStudio.Web.CodeGenerators.Mvc\1.0.0-preview2-final\Templates

Copiava a pasta para o projeto e funcionava.

Mas e agora com o .net 2.0? ao instalar o
Microsoft.VisualStudio.Web.CodeGenerators.Mvc 2.0 e
Microsoft.VisualStudio.Web.CodeGeneration.Tools 2.0 nada acontece.
Answer: Eu realizei o download manual do pacote através do link.:
NuGet Gallery - Microsoft.VisualStudio.Web.CodeGenerators.Mvc
Ao extrair o conteúdo do pacote, verifiquei que a pasta Templates estava lá com os seus respectivos arquivos.
Comment: executei via console foi, depois testei via visual studio foi, ou o console 'desentupiu' ou o nuget estava com problema desde domingo para esse pacote e agora voltou a funcionar

CodeTemplate em .net core [scaffolding]


Child divs inside parent div are not vertically aligning

Question: I'm trying to get the white child divs to align vertically in the centre of the red parent div (while ensuring the red div stays aligned in the centre of the grandparent pink div).
I've tried displaying the red parent div to be a table cell but this shifted the red div to the left of the grandparent pink div and didn't align the vertically divs anyway. Also tried different types of positioning.
Is there an easier way of achieving this without the use of flex boxes? Thanks for any assistance.

.sections-stretched {
    width: 100%;
    height: auto;
    background: #f0f;
    margin: 0 auto 50px auto;
    overflow: auto;
    padding: 50px 0;
}

.stretched-container {
    max-width: 960px;
    height: auto;
    background: #f00;
    margin: 0 auto;
    text-align: center;
}

.home-summary {
    width: 26%;
    height: auto;
    background: #fff;
    margin-right: 11%;
    display: inline-block;
    float: left;
}

.no-padding-or-margin {
    margin: 0;
    padding: 0;
}

.clear{ clear: both; }

eirh erergerge ergergiuerhgier

ergergerg erg ergerg ergergergegeg erg ergerg ergergergegeg, etc

                text here lorem imsup cla bla bla bla bla bla bla blal bla blw bowrnbuehrbuehr beurohertext here lorem imsup cla bla bla bla bla bla bla blal bla blw bowrnbuehrbuehr beuroher

                text here lorem imsup cla bla

Comment: remove float wich kills display, then vertical-align will be avalaible for your inline-block elements. Else give a try to flex :)
Comment: Is there a reason to avoid flex? I'm guessing some sort of outdated browser support?
Comment: thanks all. Didn't realise it was as simple as replacing the float with vertical align and then ensuring no white space between the elements. Preferred to see an alternative to flexboxes as I'm not too familiar with them
Answer: You may remove float and use vertical-align. (float override inline-block display)
eventually text-align-last to justify the boxes

.sections-stretched {
  width: 100%;
  height: auto;
  background: #f0f;
  margin: 0 auto 50px auto;
  overflow: auto;
  padding: 50px 0;
}

.stretched-container {
  max-width: 960px;
  height: auto;
  padding: 0 5%;
  background: #f00;
  margin: 0 auto;
  text-align: center;
  text-align-last: justify;
}

.home-summary {
  display: inline-block;
  vertical-align: middle;
  width: 26%;
  background: #fff;
}

.no-padding-or-margin {
  margin: 0;
  padding: 0;
}

.clear {
  clear: both;
}

eirh erergerge ergergiuerhgier

ergergerg erg ergerg ergergergegeg erg ergerg ergergergegeg, etc

      text here lorem imsup cla bla bla bla bla bla bla blal bla blw bowrnbuehrbuehr beurohertext here lorem imsup cla bla bla bla bla bla bla blal bla blw bowrnbuehrbuehr beuroher

      text here lorem imsup cla bla

flex can also make this easier to manage :   https://css-tricks.com/snippets/css/a-guide-to-flexbox/

.sections-stretched {
  width: 100%;
  height: auto;
  background: #f0f;
  margin: 0 auto 50px auto;
  overflow: auto;
  padding: 50px 0;
}

.stretched-container {
  max-width: 960px;
  height: auto;
  background: #f00;
  margin: 0 auto;
  text-align: center;
  /* added flex */
  display:flex;
  align-items:center;
  justify-content:space-around
}

.home-summary {
/* reduced  to minimal */
  width: 26%;
  background: #fff;
}

.no-padding-or-margin {
  margin: 0;
  padding: 0;
}

.clear {
  display:none; /* or remove from html when using flex */;
}

eirh erergerge ergergiuerhgier

ergergerg erg ergerg ergergergegeg erg ergerg ergergergegeg, etc

      text here lorem imsup cla bla bla bla bla bla bla blal bla blw bowrnbuehrbuehr beurohertext here lorem imsup cla bla bla bla bla bla bla blal bla blw bowrnbuehrbuehr beuroher

      text here lorem imsup cla bla

If it is to center content inside the white boxes, flex can be inbricated :

.sections-stretched {
  width: 100%;
  height: auto;
  background: #f0f;
  margin: 0 auto 50px auto;
  overflow: auto;
  padding: 50px 0;
}

.stretched-container {
  max-width: 960px;
  height: auto;
  background: #f00;
  margin: 0 auto;
  text-align: center;
  /* added flex */
  display: flex;
  justify-content: space-around
}

.home-summary {
  /* reduced  to minimal */
  width: 26%;
  background: #fff;
  display: flex;
  justify-content: center;
  flex-flow: column
}

.no-padding-or-margin {
  margin: 0;
  padding: 0;
}

.clear {
  display: none;
}

eirh erergerge ergergiuerhgier

ergergerg erg ergerg ergergergegeg erg ergerg ergergergegeg, etc

      text here lorem imsup cla bla bla bla bla bla bla blal bla blw bowrnbuehrbuehr beurohertext here lorem imsup cla bla bla bla bla bla bla blal bla blw bowrnbuehrbuehr beuroher

      text here lorem imsup cla bla

Comment: thanks. I'll definitely have a more thorough look into flex boxes sometime!
Answer: Remove the float and white-space between the elements so that width: 26%; margin-right: 11% will consume 100% of the parent, and use vertical-align: middle;

.sections-stretched {
    width: 100%;
    height: auto;
    background: #f0f;
    margin: 0 auto 50px auto;
    overflow: auto;
    padding: 50px 0;
}

.stretched-container {
    max-width: 960px;
    height: auto;
    background: #f00;
    margin: 0 auto;
    text-align: center;
}

.home-summary {
    width: 26%;
    height: auto;
    background: #fff;
    margin-right: 11%;
    display: inline-block;
    vertical-align: middle;
}

.no-padding-or-margin {
    margin: 0;
    padding: 0;
}

.clear{ clear: both; }

eirh erergerge ergergiuerhgier

ergergerg erg ergerg ergergergegeg erg ergerg ergergergegeg, etc

                text here lorem imsup cla bla bla bla bla bla bla blal bla blw bowrnbuehrbuehr beurohertext here lorem imsup cla bla bla bla bla bla bla blal bla blw bowrnbuehrbuehr beuroher

                text here lorem imsup cla bla


Program that converts from roman numerals to arabic numerals to roman sometimes gives wrong result

Question: I have this program that tries to convert from arabic to roman numbers to arabic numbers and it compiles without problems, but for certain values it gives the correct answer but for other cases it does not. For example:
11 is wrong (an X remains to the left of the Xs)
12 is wrong (an X remains to the left of the Xs)
20 is good
22 is wrong (2 X left over)
30 is good
32 is wrong (2 X left over)
40 is good
45 is bad (there is an XL left)
48 is wrong (an X remains before the second L)
50 is good
51 gives bad (left over an L)
58 is bad (left over an L)
60 is good
char *a2roman (int valor, char *c1, char *c2, char *c3);

int main (void)
{
    int ArabicNumber = 1;
    int result;
    char roman[15] = "";

    do
    {
        printf ("Enter an integer in the range 1 to 3000: \n\t");

        scanf ("%d", &ArabicNumber);
    }
    while ((ArabicNumber < 1) || (ArabicNumber > 3000));

    if ((ArabicNumber <= 3000) && (ArabicNumber >= 1000))
    {
        result = ArabicNumber / 1000;
        strcat (roman, a2roman(result, "M", " ", " "));
        ArabicNumber -= (result * 1000);
    }

    if ((ArabicNumber < 1000) && (ArabicNumber >= 100))
    {
        result = ArabicNumber / 100;
        strcat (roman, a2roman(result, "C", "D", "M"));
        ArabicNumber -= (result * 100);
    }

    if ((ArabicNumber < 100) && (ArabicNumber >= 10))
    {
        result = ArabicNumber / 10;
        strcat (roman, a2roman(result, "X", "L", "C"));
        ArabicNumber -= (result * 10);
    }

    if ((ArabicNumber < 10) && (ArabicNumber >= 1))
    {
        strcat (roman, a2roman(ArabicNumber, "I", "V", "X"));
    }

    printf ("The Roman numeral is: \n\t%s\n\n", roman);
    printf ("\t\t...Press any key to finish.");
    getch();

    return 0;
}

char *a2roman (int value, char *c1, char *c2, char *c3)
{
    int i;
    static char rRoman[15] = "";

    /* Si "valor" = 1, 2, 3 */
    if ((value >= 1) && (value <= 3))
    {
        for (i = 0; i < value; i++)
            strcat (rRoman, c1);
    }

    /* Si "valor" = 5, 6, 7, 8 */
    if ((value >= 5) && (value <= 8))
    {
        strcat (rRoman, c2);

        for (i = 0; i < (value - 5); i++)
            strcat (rRoman, c1);
    }

    /* Si "valor" = 4 */
    if (value == 4)
    {
        strcat (rRoman, c1);
        strcat (rRoman, c2);
    }

    /* Si "valor" = 9 */
    if (value == 9)
    {
        strcat (rRoman, c1);
        strcat (rRoman, c3);
    }

    return (rRoman);
}

Comment: The problem is you're using a static buffer in `a2roman`. As an example for 22. First call to `a2roman` adds `XX` to `rRoman` and that is added to `roman` in `main`. The second call to `a2roman` adds `II` to the end of the buffer that still contains `XX`, so at the end of that call it contains `XXII` then that is added to `roman` in `main` resulting in `XXXXII`. You might consider passing the buffer into the function instead. Stepping through the code in a debugger to watch how it happens would also be a good idea.
Comment: Would I have to use a dynamic buffer? How do you do that?
Answer: The static buffer inside a2roman builds up the complete result but each time it is called from main the partial result is also concatenated to the buffer that is printed out so you get duplicates if a2roman is called more than once.
One solution would be to use the return value from a2roman directly after the full result has been constructed by making roman a pointer and assigning the return value from a2roman to it each time a2roman is called like:
char* roman = NULL;
...
roman = a2roman(result, "M", " ", " ");
...
roman = a2roman(result, "C", "D", "M");
...
printf ("The Roman numeral is: \n\t%s\n\n", roman);

But if you ever wanted to convert more than one number you'd still have a problem because of the static buffer. You could clear it between numbers if you had a pointer to it, like *roman = 0; but that still feels messy to me.
A different solution is to pass in the buffer you want the number to be constructed in.
The following example shows how you could do that and also cleans up a little bit of the logic used to break the number into digits. What you had works but I figured I might as well show an alternate method and save a few lines.
#include <stdio.h>
#include <string.h>

void addDigit(char* out, int digit, const char* c1, const char* c2, const char* c3)
{
    if ((digit >= 1) && (digit <= 3))
    {
        for (int i = 0; i < digit; i++)
        {
            strcat(out, c1);
        }
    }

    if ((digit >= 5) && (digit <= 8))
    {
        strcat(out, c2);

        for (int i = 0; i < (digit - 5); i++)
        {
            strcat(out, c1);
        }
    }

    if (digit == 4)
    {
        strcat(out, c1);
        strcat(out, c2);
    }

    if (digit == 9)
    {
        strcat(out, c1);
        strcat(out, c3);
    }
}

void convertNumber(char* out, int num)
{
    if ((num <= 3000) && (num >= 1000))
    {
        addDigit(out, num / 1000, "M", " ", " ");
        num %= 1000;
    }

    if ((num < 1000) && (num >= 100))
    {
        addDigit(out, num / 100, "C", "D", "M");
        num %= 100;
    }

    if ((num < 100) && (num >= 10))
    {
        addDigit(out, num / 10, "X", "L", "C");
        num %= 10;
    }

    if ((num < 10) && (num >= 1))
    {
        addDigit(out, num, "I", "V", "X");
    }
}

int main(void)
{
    for (int i = 1; i < 100; i += 3)
    {
        char buf[32] = { 0 };
        convertNumber(buf, i);
        printf("%4d = %s\n", i, buf);

    }
    for (int i = 101; i < 3000; i += 101)
    {
        char buf[32] = { 0 };
        convertNumber(buf, i);
        printf("%4d = %s\n", i, buf);
    }
    return 0;
}

Online Example
Output:
   1 = I
   4 = IV
   7 = VII
  10 = X
  13 = XIII
  16 = XVI
  19 = XIX
  22 = XXII
  25 = XXV
  28 = XXVIII
  31 = XXXI
  34 = XXXIV
  37 = XXXVII
  40 = XL
  43 = XLIII
  46 = XLVI
  49 = XLIX
  52 = LII
  55 = LV
  58 = LVIII
  61 = LXI
  64 = LXIV
  67 = LXVII
  70 = LXX
  73 = LXXIII
  76 = LXXVI
  79 = LXXIX
  82 = LXXXII
  85 = LXXXV
  88 = LXXXVIII
  91 = XCI
  94 = XCIV
  97 = XCVII
 101 = CI
 202 = CCII
 303 = CCCIII
 404 = CDIV
 505 = DV
 606 = DCVI
 707 = DCCVII
 808 = DCCCVIII
 909 = CMIX
1010 = MX
1111 = MCXI
1212 = MCCXII
1313 = MCCCXIII
1414 = MCDXIV
1515 = MDXV
1616 = MDCXVI
1717 = MDCCXVII
1818 = MDCCCXVIII
1919 = MCMXIX
2020 = MMXX
2121 = MMCXXI
2222 = MMCCXXII
2323 = MMCCCXXIII
2424 = MMCDXXIV
2525 = MMDXXV
2626 = MMDCXXVI
2727 = MMDCCXXVII
2828 = MMDCCCXXVIII
2929 = MMCMXXIX


How to make alignment for label text on left AND right to have same alignment?

Question: I work on template using html and CSS . I face issue  I can't do alignment label text on left and right to be same .
as example
submit Date and Employee id not start from same point on left so I need all text on left  have same alignment .
also on right also text not start from same point as رقم الهاتف and اسم الموظف
so I need all text on right have same alignment .
full html and CSS what I try as below :

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

      نموذج تسجيل استقاله
 Resignation Submission Form

        To be filled by the Employee

يتم ملئها من الموظف

      <form>

            Emp. ID:
            -------------------

            :رقم الموظف

            Emp Name:
            -----------------------------------

            :اسم الموظف

            Dept./Branch:
            -------------------

            :الفرع/لاداره

            Designation:
            -----------------------------------

            :المسمى الوظيفى

            Submittion Date:
            -------------------

            :تاريخ تقديم الاستقاله

            Mobile No:
            -----------------------------------

            :رقم الهاتف

            Last Working Date:
            -------------------

            :اخر يوم عمل

            Employee Signature:
            -----------------------------------

            :توقيع الموظف

            Reason:
            -------------------

            -------------------
            :سبب الاستقاله

            -------------------------------------------------------

            -------------------------------------------------------------

      </form>

expected result as below :

update post
so How to use Table to solve my issue alignment please
update post
i try as below :
 .employee-info {
    display: flex;
    justify-content: space-around;
    margin-inline: auto;
    max-width: 1000px;
}

        .id_container {
            display: flex;
            gap: 10px;
            flex: 1;

        }

        .name_container {
            display: flex;
            gap: 10px;
            flex: 1;

        }

but alignment issue from left and right not solved
Comment: Just use ``
Comment: can you show me please if possible which place  will modify by code details
Comment: Please don't share your "*full HTML and CSS*," instead only share the (relevant) "*[mcve]*" code necessary to reproduce the problem you're trying to solve. So far as I can tell, that's only the "employee details," (the HTML and relevant CSS, obviously) and nothing else.
Answer: Give both columns the same size with flex: 1; and center the parent element with marginand max-width.
.employee-info {
    margin-inline: auto;
    max-width: 1000px;
}

.id_container,
.name_container {
    flex: 1;
}

Comment: i updated original post what i try but still alignment issue not solved


Is there a way to delete/purge all generated image style images without re-generating them?

Question: I'd like to delete all generated image style images without re-generating them immediately.  I want to do this in order to remove them from my backups, because as the number of files on the site increases, it's taking up an exceedingly large amount of space.
I also have the option of making the backup script more complicated and not backing up those directories, but I was wondering if there is a quick way just to remove the generated files only.
Answer: You just have to do drush image-flush --all. Source : http://www.drushcommands.com/drush-6x/image/image-flush
Examples of using the drush image-flush command:

drush image-flush - Pick an image style and then delete its images.
drush image-flush thumbnail - 'Delete all thumbnail images.
drush image-flush --all - 'Flush all derived images. They will be regenerated on the fly.'


Cisco 2801 as a fail over?

Question: I have recently acquired a Cisco 2801 unit and I want to know if it is capable of acting as a fail over for a network. It currently has an ADSL WIC installed.
We currently run 6 Windows servers (4x Win2008, 2x Win2000) with TS access for our users. This runs over a cable modem connection. We also have an ADSL connection which we want to use as a failover should the cable connection go down.
My question is this: Can the 2801 we have be used to do what I require? If so, would it be difficult to set up, and are there any known complications with this kind of failover?
If not, can anybody suggest an alternative?
Thanks
Comment: *Citrix* 2801?!  Cisco, surely...
Comment: I think I'm going to give up on the Cisco for now. I don't know anything about them, it was just a box I acquired and thought it might be good to try it.

Thanks for all your answers.
Answer: I'm going to assume that you mean a Cisco 2801 unit.
Unfortunately we've insufficient information to go on:

What physical interfaces apart from the ADSL WIC does the 2801 have?
What physical interface does the cable connection have?
Do you have NAT on either of the connections?
Do you have static IP(s) on either of the connections?

EDIT - based on your additional comments.
I recommend you:

Make sure you can get a static IP block on the ADSL line
Install a firewall capable of dual WAN line operation (I've had good results with  Stonegate units - that link goes to their primary UK supplier and integrator)
Give your users the secondary IP addresses from the ADSL line to use as necessary

Handling the inbound connections is actually slightly tricky, because if a user connects on the DSL line you have to ensure that the outgoing response packets go out via the same link.  The firewall should be able to handle that for you.
Comment: so, do all of the servers have a direct connection (albeit through a switch) to the cable modem, or is there (hopefully!) a firewall between them?
Comment: The 2801 has 1 USB port and 4 ethernet links (FE 0/1, FE0/0, CONSOLE and AUX) Of the 4 expansion ports, only SLOT 2 is populated with the ADSL WIC.

Cable connection is a simple ethernet output from the cable modem.

All of our servers are currently running with static, public IP's. Our internal network is running on DHCP through the cable connection.

The ADSL connection is currently not being used, but is tested often and is still live.
Comment: oh dear...  The CONSOLE and AUX ports aren't ethernet, even though they might look like it.
Answer: The answer is a qualified 'yes'.  Since this would be an active/backup situation, you should be able to do what you want with floating static routes.  The challenge will be with your users connecting to the servers when you fail-over to the backup link.  The IP address will change and unless you use some type of DNS updating service, they will need to change their shortcuts or have two icons on their desktop.
You will need to connect ISP1 and ISP2 to the 2801 and it then to your switch.  Next setup a static route on the 2801 to point to ISP1 and a second static route to ISP2 with a high administrative cost.
By the way as Alnitak said, you should know that the 'CON' and 'AUX' ports are not Ethernet.  They do use CAT5 cabling, but are not network ports. This may leave you short of the necessary three for this solution to work.
Also based on your comments, it sounds like you may not have a firewall?  If this the case RUN, do not walk, and get one immediately.  It would also probably be a good idea to change your servers to private addressing and then do NATs on the firewalls.
Answer: assuming you can do tracking routes you certainly can we use something like this
ip route 0.0.0.0 0.0.0.0 ip.to.gateway1 track 100
ip route 0.0.0.0 0.0.0.0 ip.to.gateway2 2

then you can create your tracking like so
track 100 rtr 1 reachability
delay down 30

in reference to something like this
ip sla monitor 1
type echo protocol ipIcmpEcho ip.to.next.hop
frequency 10

you would set ip.to.next.hop to a next hop address ... find it using tracert if that goes down your ip route will be removed and it will fall back on your default route.
Comment: note this will only give you access out ... if your servers as serving a website etc etc you will need to do something with dns to make connections come in to the right place
Comment: Don't floating static routes accomplish the same thing without the extra complexity of the route tracking?
Answer: I came across the following linux distro that may do what you are looking for:
[In particular the WAN fail-over.]
While not a direct answer to you, I hope this answers the intent if not the specifics of your question.
http://www.untangle.com/

Active Directory Connector
Attack Blocker
Branding Manager
Commtouch Spam Booster
eSoft Web Filter
Firewall
Intrusion Prevention
Kaspersky Virus Blocker
OpenVPN
PC Remote
Phish Blocker
Policy Manager
Protocol Control
Remote Access Portal
Reports
Routing & QoS
Spam Blocker
Spyware Blocker
Virus Blocker
WAN Balancer
WAN Failover
Web Filtering

Cisco 2801 as a fail over?