text:
Q: What is the difference between Sprint and Iteration in Scrum and length of each Sprint?
*

*Is there a difference between Sprint and an Iteration or one can have Iterations within a Sprint or Sprint is just the terminology used instead of Iteration in Scrum? It will be helpful if someone can throw some light on this.

*Suppose there are 4 sprints and you have decided the first sprint will go up to 10 days is it required that other 3 sprints should have the same length of the 1st decided sprint's length??.

A: All sprints are iterations but not all iterations are sprints. Iteration is a common term in iterative and incremental development (IID). Scrum is one specialized flavor of IID so it makes sense to specialize the terminology as well. It also helps brand the methodology different from other IID methodologies :)
As to the sprint length: anything goes as long as the sprint is timeboxed i.e. it is finished on the planned date and not "when it's ready". (Or alternatively, in rare occasions, the sprint is terminated prematurely to start a new sprint in case some essential boundary conditions are changed.)
It does help to have the sprints of similar durations. There's less to remember about the sprint schedule and your planning gets more accurate. I like to keep mine at 2 calendar weeks, which will resolve into 8..10 business days outside holiday seasons.

A: The important thing about a sprint is that: within a sprint the functionality that is to be delivered is fixed.
A sprint is normally an iteration. But you can for example have a 4 week sprint, but have 4 one week "internal" iterations within that sprint.
There is a lot of discussion about the length of sprints. I think that if you do it according to the book they should all be the same length.
We have found that a short first sprint to get the development environment up and running, followed by longer basic functionality sprints, then short sprints towards the end of the project, has worked for us.

A: "___ is largely an organizational issue caused by long hours, little down time, and continual peer, customer, and superior surveillance"
No this is not the definition of scrum, it is the wikipedia excerpt on the definition of burnout.
Dont do too many short 10 days sprints. You will burnout your team eventually. Use short sprints where you really need them, and don't do too many in a row. Think long-term. A distance runner always paces themselves for the full race and does sprints in short distances only where it matters.
If you burnout your team you can toss out all them fancy scrum charts, they won't do a thing for your team's plummeting productivity.

A: Iteration is synonymous with sprint, sprint is just the Scrum terminology.
On the question about sprint length, the only caution I would note is that in Scrum you are using the past sprints to gain a level of predictability on your teams ability to deliver on their commitments for the sprint.  They do this by developing a velocity over a number of sprints.  A change in the team members or the length of the sprint are factors that will affect the velocity for a sprint, over past sprints.
Just as background, velocity is the sum of estimation points assigned to the backlog items, or stories, that were completely finished during that sprint.  Most Agile proponents (Mike Cohn, Ken Schwaber and Jeff Sutherland for instance), recommend that teams use "the recent weather" to base their future estimations on how much they think they can commit to in a sprint.  This means using the average from the last few sprints as the basis for an estimate in the upcoming sprint planning session.
Once again, varying the sprint length reduces your teams ability to provide that velocity statistic which the team uses for sprint planning, and the product owner uses for release planning (i.e. predicting when the project will end or what will be in the project at the end).
I recommend Mike Cohn's book on Agile Estimating and Planning to provide an overview of the way sprints, estimation and planning all can fit together.

A: *

*Where I work we have 2 Sprints to an Iteration.  The Iteration demo is before the business stakeholders that don't want to meet after every Sprint, but that is our interpretation of the terminology.  Some places may have the terms having equally meaning, I'm just pointing out that where I work they aren't the same thing.

*No, sprints can have varying lengths.  Where I work we had a half a Sprint to align our Sprints with the Iterations that others in the project from another department were using.

A: Sprint == Iteration.
The lengths can vary, but it's a bad planning precedent to let them vary too much.
Keep them consistent in duration and you will get better at planning and delivering.  Everything will be measured by how many 10-day sprints it takes to finish a series of use cases.
Keep them consistent in length and you can plan your deliveries, end-user testing, etc., with more accuracy.
The point is to release on time at a consistent pace.  A regular schedule makes management slightly simpler and more predictable.

A: *

*Sprint is just the term for an iteration.

*You can change the Sprint length to be anything you want, but likely you'll want to try to find an amount of time that "works well" (which may mean any number of things for your team) and end up sticking with it over time.

A: According to my experience

*

*Sprint is a kind of Iteration and one can have many Iterations within a
single Sprint (e.g. one shall startover or iterate a task if it's
failed and still having extra estimated time) or across many Sprints
(such as performing ongoing tasks).

*Normally, the duration for a Sprint can be one or two weeks, It
depends on the time required and the priority of tasks (which could
be defined by Product Owner or Scrum Master or the team) from the Product
Backlog.

ref: https://en.wikipedia.org/wiki/Scrum_(software_development)

A: Sprint as defined in pure Scrum has the duration 30 calendar days. However Iteration length could be anything as defined by the team.


text:
Q: Purpose of PHP use keyword in array_map() function? I've the following code of lines in my application.
Can anybody please tell me what is the purpose of use keyword in the following array_map() function?
array_map( function($record) use ($edit_form, $otherfields, $otherfields_keys)
{
    User::parseData($record, $edit_form['metadata']);

    if (isset($otherfields[$record['user_id']])) {
        return $record + $otherfields[$record['user_id']];
    }

    return $record + $otherfields_keys;

}, $records);

Thanks in advance.

A: The callback passed to array_map() doesn't have access to outside variables so they must be passed using use.
You can read more about anonymous functions in the PHP documentation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: (Exterior Algebra) Relation between positive oriented space and $r$-forms space.
Let $S$ a oriented vector space of dimension $m$ and equipped with a inner product. Given $v \in S$, let $\omega = \phi(v) \in \mathcal{A}_{m-1}(S)$ defined by
  $$\omega(v_{1},...,v_{m-1}) = \langle v, v_{1},...,v_{m-1} \rangle.$$
  Show that the aplication $\phi: S \to \mathcal{A}_{m-1}(S)$ is an isomorphism. If $v \in S$ is the first element of a orthonormal positive basis such that the dual is $\{ e_{1},...,e_{m} \}$ then $\phi(v) = e_{2} \wedge \dots \wedge e_{m}$. Conclude that if $\dim S = m$ then every $\omega \in \mathcal{A}_{r}(S)$ is decomposable.

Notation. $\mathcal{A}_{r}(S)$ denotes the vector space of $r$-linear forms over $S$.
Idea. First, $\dim \mathcal{A}_{m-1}(S) = \binom{m}{m-1} = m$ and, since $\phi$ is linear, we need to show that $\ker \phi = \{ 0 \}$. Note that
$$\phi(v) = 0 \Longleftrightarrow \omega = 0 \Longleftrightarrow \langle v, v_{1},...v_{m-1} \rangle = 0 \Longleftrightarrow v = 0.$$
Is this right?
I couldn't prove the second part. I would like help. I didn't try to make the conclusion yet, so I wanted help only in the second part.

A: Your idea is indeed a correct proof; maybe in the third equivalent statement in the highlighted row one could insert "for all $v_1, \ldots, v_{m-1}$".
For the second statement, it suffices to show that the two $m-1$-forms coincide on the given orthonormal positive basis, which we denote by $v = b_1, b_2, \ldots, b_n$; but indeed,
$$
\phi(v)(b_1, \ldots, \hat{b_k}, \ldots, b_n) = \langle b_1, b_1, \ldots, \hat{b_k}, \ldots, b_n \rangle = \begin{cases}
+1 & k=1 \\
0 & \text{else},
\end{cases}
$$
the same as $e_2 \wedge \cdots \wedge e_n$. Finally, let $\omega \in A_{m-1}(S)$ be arbitrary. By surjectivity of $\phi$, we find $v \in S$ so that $\phi(v) = \omega$. Then $\phi(cv) = c\omega$, where $c$ is a constant such that $\|cv\| = 1$. Then extend $v$ to an orthonormal basis by basis extension and Gram‒Schmidt and apply the second point to get that $c\omega$ is decomposable. Hence $\omega$ is decomposable by sliding in the $c$ into one of the wedge factors by multilinearity.


text:
Q: How to make mobile devices not load an external JS I have a website  I've taken over which is nearing launch. The website has a script which loads each page ajax style and updates the URL which enables a continuously playing music player. It all works fantastic on desktop browsers. However, this same feature is crashing Safari on the iPhone and iPad.
How exactly could I write a bit of Javascript to load an external JS file if it is NOT mobile or a tablet? Namely, iPhone and iPad. I'm aware of the resource at http://detectmobilebrowsers.com/, though my knowledge of Javascript is just short of utilizing this script to meet my needs.
Whatever I can do to make iPhones and iPads not load a specific JS file would (for now) fix this issue. Any ideas? Unfortunately, server side solutions are just not possible.
Here is what I got to simply detect Mobile with jquery:
/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 *
 * jQuery.browser.mobile will be true if the browser is a mobile device
 *
 **/
(function(a){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

A: Why is a backend solution not applicable?
Anyway, make sure you include jQuery and the Detect Mobile (jQuery):
<head>
    <script src="jquery.js"></script>
    <script src="detectmobilebrowser.js"></script>
</head>

Now to detect if it's NOT a mobile:
if ( !jQuery.browser.mobile ) {
    // create the script element
}

How do you create the script element?
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://URLTOSCRIPT';

$('body').append(script);


text:
Q: How do I calculate overlapping date ranges duration (more than 2) with PostgreSQL? I am trying to calculate the global duration of many date ranges.
In my DB I have candidates and experiences.
A candidate may have many experiences, and an experience has a start date and may have a end_date or not.
Experiences date ranges can overlap, here I am stuck, how to calculate the duration ?
This is how I join my models:

I want to retrieve a list of candidates by querying the experiences and skills:
I have 2 inputs, the range and the skill name. For example, I want all the candidates having the skill 'Ruby' through experiences and experiences_skills with experience global duration of 5 years.
EDIT
Current solution:
      SELECT * FROM (
            WITH cte AS (
                SELECT
                  experiences.candidate_id AS candidate_id,
                  experiences.id AS e_id,
                  experiences.start_at AS start_at,
                  experiences.end_at AS end_at,
                  LAG(experiences.start_at, 1, start_at)
                  OVER (PARTITION BY experiences.candidate_id ORDER BY experiences.start_at) AS prev_start_at,
                  LAG(experiences.end_at, 1, start_at)
                  OVER (PARTITION BY experiences.candidate_id ORDER BY experiences.start_at) AS prev_end_at,
                  LEAD(experiences.start_at)
                  OVER (PARTITION BY experiences.candidate_id ORDER BY experiences.start_at) AS next_start_at,
                  LEAD(experiences.end_at, 1, current_date)
                  OVER (PARTITION BY experiences.candidate_id ORDER BY experiences.start_at) AS next_end_at
                FROM experiences
                  INNER JOIN experiences_skills ON experiences_skills.experience_id = experiences.id
                  INNER JOIN skills ON skills.id = experiences_skills.skill_id
                WHERE skills.name = 'Ruby'
            )
            SELECT
              SUM(CASE
                  WHEN (cte.prev_end_at > cte.end_at AND cte.prev_end_at < cte.next_start_at)
                    THEN cte.prev_end_at
                  WHEN (cte.prev_end_at > cte.end_at AND cte.prev_end_at > cte.next_start_at)
                    THEN cte.next_start_at
                  WHEN cte.end_at > cte.next_start_at
                    THEN cte.next_start_at
                  ELSE cte.end_at
                  END
                  -
                  cte.start_at
              ) AS duration_day,
              candidates.*
            FROM cte
              INNER JOIN candidates ON candidates.id = cte.candidate_id
            GROUP BY candidates.id
          ) AS candidates
      WHERE duration_day > 0 AND duration_day < 1000';

A: I don't think you can solve this without defining your own aggregate, like:
CREATE OR REPLACE FUNCTION range_array_merge(s anyarray, v anynonarray)
    RETURNS anyarray
    LANGUAGE SQL
    IMMUTABLE
AS $func$
  WITH RECURSIVE arrays(r) AS (
      SELECT s || v
    UNION ALL
      SELECT array_agg(DISTINCT u)
      FROM   (SELECT a + b u
              FROM   arrays,
                     unnest(r) a
              JOIN   unnest(r) b ON a <> b AND a && b) u
      HAVING COUNT(u) > 0
  ),
  ranges(r) AS (
      SELECT unnest(r)
      FROM   arrays
  )
  SELECT    array_agg(DISTINCT r.r)
  FROM      ranges r
  LEFT JOIN ranges c ON c.r <> r.r AND c.r @> r.r
  WHERE     c.r IS NULL
$func$;

CREATE AGGREGATE range_array_merge_agg(anynonarray) (
  STYPE    = anyarray,
  SFUNC    = range_array_merge(anyarray, anynonarray),
  INITCOND = '{}'
);

This can collect any type of ranges & will accumulate them into a single array, which will have only separate ranges (overlapping ranges are union-ed together).
With this, your query is as "simple" as:
SELECT   e.candidate_id,
         SUM(upper(r.r) - lower(r.r) + 1) total_days
FROM     (SELECT   e.candidate_id,
                   range_array_merge_agg(daterange(e.start_at, COALESCE(e.end_at, current_date))) r
          FROM     experiences e
          JOIN     experiences_skills es ON es.experience_id = e.id
          WHERE    es.skill_id = 42 --> search for a specific skill
          GROUP BY e.candidate_id) e,
         unnest(e.r) r
GROUP BY e.candidate_id;

Assuming start_at and end_at has type of date. With the timestamp [with time zone] type, things will get messy, but I doubt that you would ever need that precision.
You could filter the query above with simply HAVING SUM(upper(r.r) - lower(r.r) + 1) > 1000.
http://rextester.com/DNSWS30622
Edit: to search for complete candidate rows:
SELECT   c.*
FROM     (SELECT   e.candidate_id,
                   range_array_merge_agg(daterange(e.start_at, COALESCE(e.end_at, current_date))) r
          FROM     experiences e
          JOIN     experiences_skills es ON es.experience_id = e.id
          WHERE    es.skill_id = 42 --> search for a specific skill
          GROUP BY e.candidate_id) e,
         unnest(e.r) r
JOIN     candidates c ON e.candidate_id = c.id
GROUP BY c.id
HAVING   SUM(upper(r.r) - lower(r.r) + 1) > 1000; --> search for minimum number of total days

Note: if you ever wonder why is a + 1 in the sum, the reason is simple. date '2017-01-01' - date '2017-01-01' is 0 (zero). While I consider this as 1 day of experience (that day would be exactly 2017-01-01). So that's why the sum needs + 1. You can also express this in the daterange constructor, like: daterange(e.start_at, COALESCE(e.end_at, current_date)), '[]'). But because of date is discrete, a [2017-01-01,2017-01-02] range will be canonicalized to the [2017-01-01,2017-01-03) form. That way there would be no need to add 1 to the sum, because canonicalization already "extends" its upper() bound.

A: I cant find the primary key of your experiences_skills table because experience_id and skill_id both are FK.
To avoid this problem you can remove experiences_skills table and add PK of candidates table into experiences_skills and skills table as FK, and try below query:
select * from candidates c, exp e, skills s where c.candid = e.candid and c.candid = s.candid and (datediff(year,e.sdate, e.edate) = 1) and s.name = 'test'

Now below is the image of table structures:


text:
Q: In the Node js How to Users should be restricted to a defined number of login attempts per unit of time Users should be restricted to a defined number of login attempts per unit of time,
After the n number of unsuccesfull  login attemots user can be lock, this is for avoiding Brute Force Attack

A: you can use express-rate-limit npm package.
import rateLimit from 'express-rate-limit';
import express from 'express';

const app = express();
const limiter = rateLimit({
            windowMs: 15 * 60 * 1000, // 15 minutes
            max: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes)
            standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
            legacyHeaders: false, // Disable the `X-RateLimit-*` headers
            message: "You exceeded 100 requests in 15 minutes limit!",
        });

 // Apply the rate limiting middleware to all requests
 app.use(limiter);

you can also use rate-limiter-flexible package with Redis..

also you can find it here


text:
Q: Make PayPal button permanently disappear on click I always find an answer to my questions on stackoverflow when searching the website. This time however it came to the point where I need to ask a question.
Below is a HTML code for a PayPal 'Buy now' button. Pretty basic stuff. Here comes the catch. I want to make it disappear on click for every user (so not just the one who clicked it on his device). Is it possible to do something like this?
Thank you in advance.
edit: There's one more scenario that is more complicated. It is about making the button disappear for everyone once it was not just clicked but after paid for the item this button is linked to. Is PayPal API capable of something like this?


text:
Q: Google app engine and JPA with Eclipse plug-in I created an application with JSF ( Primefaces) and JPA and I m trying  to deploy it on GAE. First I m trying with the local app engine sdk. I have a problem when trying to use JPA with CloudSQL. I m following the instructions on how to do it using Eclipse here:
https://developers.google.com/eclipse/docs/cloudsql-jpatools
However I get the following error:
Caused by: javax.persistence.PersistenceException: Provider error. Provider: org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider
    at javax.persistence.Persistence.createFactory(Persistence.java:176)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:112)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:66)
    at org.Handlers.EMFService.<clinit>(EMFService.java:8)
    ... 51 more
Caused by: java.lang.NullPointerException
    at org.datanucleus.jpa.EntityManagerFactoryImpl.initialisePMF(EntityManagerFactoryImpl.java:452)
    at org.datanucleus.jpa.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:355)
    at org.datanucleus.store.appengine.jpa.DatastoreEntityManagerFactory.<init>(DatastoreEntityManagerFactory.java:63)
    at org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider.createEntityManagerFactory(DatastorePersistenceProvider.java:35)
    at javax.persistence.Persistence.createFactory(Persistence.java:172)
    ... 54 more

What s more is that I think that datanucleus is used to access the App engine Datastore. However I m trying to connect to the relational  cloud sql database  ( it s up and running). So i dont understand what the datanucleus has to do with that.
I m using Eclipselink for implementing the JPA spec as proposed by the following guide by GAE:
https://developers.google.com/eclipse/docs/cloudsql-jpatools
Below you can also see the persistence.xml:
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="googleeclipselink"
        transaction-type="RESOURCE_LOCAL">

        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

        <class>org.entities.Department</class>
        <class>org.entities.Employee</class>
        <class>org.entities.Partner</class>
        <class>org.entities.Project</class>
        <class>org.entities.User</class>

        <properties>
            <!-- <property name="datanucleus.NontransactionalRead" value="true" />
                <property name="datanucleus.NontransactionalWrite" value="true" /> <property
                name="datanucleus.ConnectionURL" value="appengine" /> -->
            <property name="javax.persistence.jdbc.driver"
                value="com.google.appengine.api.rdbms.AppEngineDriver" />
            <property name="javax.persistence.jdbc.url"
                value="jdbc:google:rdbms://fotisgonidisseerc:googlecloudsql/researchprojects" />
            <property name="javax.persistence.jdbc.user" value="" />
            <property name="javax.persistence.jdbc.password" value="" />
        </properties>
    </persistence-unit>
</persistence>

Anybody could give me a hint of how to solve it?

A: After spending some time on the issue I figured out that I had to remove the DataNucleus libs from the WEB-INF/lib. I also needed to add the EclipseLink lib in my classpath.
This is because I m using EclipseLink as JPA implemetation.Therefore DataNucleus were causing a conflict and thus needs to be removed.
I guess that Google Plug-in for Eclipse does this automatically but apparently sometimes it fails.


text:
Q: How to validate a IPv6 address format with shell? In my shell, I need check if a string is a valid IPv6 address.
I find two ways, neither of them is ideal enough to me.
One is http://twobit.us/2011/07/validating-ip-addresses/, while I wonder if it must be such complex for such a common requirement.
The other is expand ipv6 address in shell script, this is simple, but for major distribution of Linux, sipcalc isn't a common default utility.
So my question, is there a simple way or utility to validate a IPv6 address with shell?
Thanks in advance.

A: The code in the first link isn't particularly elegant, but modulo stylistic fixes, I don't think you can simplify much beyond that (and as indicated in a comment, it may already be too simple).  The spec is complex and mandates a number of optional features, which is nice for the end user, but cumbersome for the implementor.
You could probably find a library for a common scripting language which properly encapsulates this logic in a library.  My thoughts would go to Python, where indeed Python 3.3 includes a standard module called ipaddress; for older versions, try something like
#!/usr/bin/env python
import socket
import sys
try:
    socket.inet_pton(socket.AF_INET6, sys.argv[1])
    result=0
except socket.error:
    result=1
sys.exit(result)

See also Checking for IP addresses

A: Here is a solution in POSIX compatible shell script that handles IPv4 and IPv6 addresses with an optional subnet mask. To test an IP that should not have a subnet mask just pass it a dummy one when performing the test. It seems like a lot of code but it should be significantly faster than using external programs like grep or scripts that are likely to fork.
Single IPv6 zero groups compressed to :: will be treated as invalid. The use of such representation is strongly discouraged, but technically correct. There is a note in the code explaining how to alter this behaivour if you wish to allow such addresses.
#!/bin/sh
set -e

# return nonzero unless $1 contains only digits, leading zeroes not allowed
is_numeric() {
    case "$1" in
        "" | *[![:digit:]]* | 0[[:digit:]]* ) return 1;;
    esac
}

# return nonzero unless $1 contains only hexadecimal digits
is_hex() {
    case "$1" in
        "" | *[![:xdigit:]]* ) return 1;;
    esac
}

# return nonzero unless $1 is a valid IPv4 address with optional trailing subnet mask in the format /<bits>
is_ip4() {

    # fail if $1 is not set, move it into a variable so we can mangle it
    [ -n "$1" ] || return
    IP4_ADDR="$1"

    # handle subnet mask for any address containing a /
    case "$IP4_ADDR" in
        *"/"* ) # set $IP4_GROUP to the number of bits (the characters after the last /)
                IP4_GROUP="${IP4_ADDR##*"/"}"

                # return failure unless $IP4_GROUP is a positive integer less than or equal to 32
                is_numeric "$IP4_GROUP" && [ "$IP4_GROUP" -le 32 ] || return

                # remove the subnet mask from the address
                IP4_ADDR="${IP4_ADDR%"/$IP4_GROUP"}";;
    esac

    # backup current $IFS, set $IFS to . as that's what separates digit groups (octets)
    IP4_IFS="$IFS"; IFS="."

    # initialize count
    IP4_COUNT=0

    # loop over digit groups
    for IP4_GROUP in $IP4_ADDR ;do
        # return failure if group is not numeric or if it is greater than 255
        ! is_numeric "$IP4_GROUP" || [ "$IP4_GROUP" -gt 255 ] && IFS="$IP4_IFS" && return 1

        # increment count
        IP4_COUNT=$(( IP4_COUNT + 1 ))

        # the following line will prevent the loop continuing to run for invalid addresses with many occurrences of .
        # this makes no difference to the result, but may improve performance when validating many such invalid strings
        [ "$IP4_COUNT" -le 4 ] || break
    done

    # restore $IFS
    IFS="$IP4_IFS"

    # return success if there are 4 digit groups, otherwise return failure
    [ "$IP4_COUNT" -eq 4 ]
}

# return nonzero unless $1 is a valid IPv6 address with optional trailing subnet mask in the format /<bits>
is_ip6() {
    # fail if $1 is not set, move it into a variable so we can mangle it
    [ -n "$1" ] || return
    IP6_ADDR="$1"

    # handle subnet mask for any address containing a /
    case "$IP6_ADDR" in
        *"/"* ) # set $IP6_GROUP to the number of bits (the characters after the last /)
                IP6_GROUP="${IP6_ADDR##*"/"}"

                # return failure unless $IP6_GROUP is a positive integer less than or equal to 128
                is_numeric "$IP6_GROUP" && [ "$IP6_GROUP" -le 128 ] || return

                # remove the subnet mask from the address
                IP6_ADDR="${IP6_ADDR%"/$IP6_GROUP"}";;
    esac

    # perform some preliminary tests and check for the presence of ::
    case "$IP6_ADDR" in
        # failure cases
        # *"::"*"::"*  matches multiple occurrences of ::
        # *":::"*      matches three or more consecutive occurrences of :
        # *[^:]":"     matches trailing single :
        # *"."*":"*    matches : after .
        *"::"*"::"* | *":::"* | *[^:]":" | *"."*":"* ) return 1;;

        *"::"* ) # set flag $IP6_EXPANDED to true, to allow for a variable number of digit groups
                 IP6_EXPANDED=0

                 # because :: should not be used for remove a single zero group we start the group count at 1 when :: exists
                 # NOTE This is a strict interpretation of the standard, applications should not generate such IP addresses but (I think)
                 #      they are in fact technically valid. To allow addresses with single zero groups replaced by :: set $IP6_COUNT to
                 #      zero after this case statement instead
                 IP6_COUNT=1;;

        *      ) # set flag $IP6_EXPANDED to false, to forbid a variable number of digit groups
                 IP6_EXPANDED=""

                 # initialize count
                 IP6_COUNT=0;;
    esac
    # backup current $IFS, set $IFS to : to delimit digit groups
    IP6_IFS="$IFS"; IFS=":"

    # loop over digit groups
    for IP6_GROUP in $IP6_ADDR ;do
        # if this is an empty group then increment count and process next group
        [ -z "$IP6_GROUP" ] && IP6_COUNT=$(( IP6_COUNT + 1 )) && continue

        # handle dotted quad notation groups
        case "$IP6_GROUP" in
            *"."* ) # return failure if group is not a valid IPv4 address
                    # NOTE a subnet mask is added to the group to ensure we are matching addresses only, not ranges
                    ! is_ip4 "$IP6_GROUP/1" && IFS="$IP6_IFS" && return 1

                    # a dotted quad refers to 32 bits, the same as two 16 bit digit groups, so we increment the count by 2
                    IP6_COUNT=$(( IP6_COUNT + 2 ))

                    # we can stop processing groups now as we can be certain this is the last group, : after . was caught as a failure case earlier
                    break;;
        esac

        # if there are more than 4 characters or any character is not a hex digit then return failure
        [ "${#IP6_GROUP}" -gt 4 ] || ! is_hex "$IP6_GROUP" && IFS="$IP6_IFS" && return 1

        # increment count
        IP6_COUNT=$(( IP6_COUNT + 1 ))

        # the following line will prevent the loop continuing to run for invalid addresses with many occurrences of a single :
        # this makes no difference to the result, but may improve performance when validating many such invalid strings
        [ "$IP6_COUNT" -le 8 ] || break
    done

    # restore $IFS
    IFS="$IP6_IFS"

    # if this address contained a :: and it has less than or equal to 8 groups then return success
    [ "$IP6_EXPANDED" = "0" ] && [ "$IP6_COUNT" -le 8 ] && return

    # if this address contained exactly 8 groups then return success, otherwise return failure
    [ "$IP6_COUNT" -eq 8 ]
}

Here are some tests.
# tests
TEST_PASSES=0
TEST_FAILURES=0
for TEST_IP in 0.0.0.0 255.255.255.255 1.2.3.4/1 1.2.3.4/32 12.12.12.12 123.123.123.123 101.201.201.109 ;do
    ! is_ip4 "$TEST_IP" && printf "IP4 test failed, test case '%s' returned invalid\n" "$TEST_IP" && TEST_FAILURES=$(( TEST_FAILURES + 1 )) || TEST_PASSES=$(( TEST_PASSES + 1 ))
done
for TEST_IP in ::1 ::1/128 ::1/0 ::1234 ::bad ::12 1:2:3:4:5:6:7:8 1234:5678:90ab:cdef:1234:5678:90ab:cdef \
               1234:5678:90ab:cdef:1234:5678:90ab:cdef/127 1234:5678:90ab::5678:90ab:cdef/64 f:1234:c:ba:240::1 \
               1:2:3:4:5:6:1.2.3.4 ::1.2.3.4 ::1.2.3.4/0 ::ffff:1.2.3.4 ;do
    ! is_ip6 "$TEST_IP" && printf "IP6 test failed, test case '%s' returned invalid\n" "$TEST_IP" && TEST_FAILURES=$(( TEST_FAILURES + 1 )) || TEST_PASSES=$(( TEST_PASSES + 1 ))
done
for TEST_IP in junk . / 0 -1.0.0.0 1.2.c.0 a.0.0.0 " 1.2.3.4" "1.2.3.4 " " " 01.0.0.0 09.0.0.0 0.0.0.01 \
               0.0.0.09 0.09.0.0.0 0.01.0.0 0.0.01.0 0.0.0.a 0.0.0 .0.0.0.0 256.0.0.0 0.0.0.256 "" 0 1 12 \
               123 1.2.3.4/s 1.2.3.4/33 1.2.3.4/1/1 ;do
    is_ip4 "$TEST_IP" && printf "IP4 test failed, test case '%s' returned valid\n" "$TEST_IP" && TEST_FAILURES=$(( TEST_FAILURES + 1 )) || TEST_PASSES=$(( TEST_PASSES + 1 ))
done
for TEST_IP in junk "" : / :1 ::1/ ::1/1/1 :::1 ::1/129 ::12345 ::bog ::1234:345.234.0.0 ::sdf.d ::1g2 \
               1:2:3:44444:5:6:7:8 1:2:3:4:5:6:7 1:2:3:4:5:6:7:8/1c1 1234:5678:90ab:cdef:1234:5678:90ab:cdef:1234/64 \
               1234:5678:90ab:cdef:1234:5678::cdef/64  ::1.2.3.4:1 1.2.3.4:: ::1.2.3.4j ::1.2.3.4/ ::1.2.3.4:junk ::1.2.3.4.junk ;do
    is_ip6 "$TEST_IP" && printf "IP6 test failed, test case '%s' returned valid\n" "$TEST_IP" && TEST_FAILURES=$(( TEST_FAILURES + 1 )) || TEST_PASSES=$(( TEST_PASSES + 1 ))
done
printf "test complete, %s passes and %s failures\n" "$TEST_PASSES" "$TEST_FAILURES"

A: Most distros come with package iproute2 (name may vary) preinstalled. So you can rely on the command ip for querying the routing table:
ip -6 route get <probe_addr>/128 >/dev/null 2>&1

Even on a machine without appropriate route this delivers rc=0 when the probe is in valid v6-syntax.

A:  valid_ip(){
 ip -6 route get "$1"/128 >/dev/null 2>&1
 case "$?" in
  0|2) return 0
  1) return 1
 esac
 }

i took sgundlach's answer, but needed it on a machine which did not have ip6 connectivity so through testing and reading the manpage I found that I can trust exit code 1 to mean the syntax is invalid, meanwhile 0 is success and 2 is valid syntax but kernel error reported.
from the man page:

   Exit status is 0 if command was successful, and 1 if there is a syntax error.  If an error was reported by the kernel exit status is 2.


text:
Q: Restart later but when? Ubuntu Software Updater post update installation shows option below

I wonder what does Restart Later means for Ubuntu.
Windows lets us choose to be reminded in 10 minutes, 1 Hour or 4 Hours

So does Macintosh

After I click on Restart Later at times I see this couple of times in a day and sometimes I see it next day. Ubuntu Wiki doesn't describe this option very well either.

A: Whenever you feel like it. Its worth considering a few things when saying this.
The underlying package manager does not force you to reboot - though /var/run/reboot-required will tell you if its needed.
Linux will hold on to the old version of the file till nothing is using it , so typically a restart is for kernel upgrades, and maybe drivers/modules.
Finally there's a philosophical difference between linux (designed for powerusers, and folks who boast about uptime and reliability) and a desktop oriented OS - windows server probably wouldn't force a reboot either.
As such, in linux these reboot warnings are considered recommended not essential and its informational. There's nothing stopping someone from writing something that ran sudo reboot for you though.

A: IMHO "Restart later" means simply as it is that the user (you) will reboot the system sometime later, that's all!


text:
Q: Darken When Hover For Button in React I have a problem on darkening the button when hovering in my React app. The problem is that I'm using linear-gradient for its background color. The darken from polished (https://www.npmjs.com/package/polished) npm package works if I'm not declaring the background as linear-gradient
Pls see my code here
const AddButton= styled.button`
  width: 100%;
  background: linear-gradient(
    ${(props) => props.theme.colors.secondary},
    ${(props) => props.theme.colors.primary}
  );
 :hover, :active {
    background-color: ${(props) =>  props.theme.colors && darken(0.1, props.theme.colors.primary)};
  }
`;

A: You're darkening a colour and setting it as the background colour but it is covered up by the background image you are setting.
Create a new background image to replace the one you have instead.
:hover, :active {
    background-image: linear-gradient(
        ${(props) => darken(0.1, props.theme.colors.secondary)},
        ${(props) => darken(0.1, props.theme.colors.primary)}
    );
}


text:
Q: yum: enable a disabled repository I've found out I can use yum --enablerepo= to temporarily enable a disabled Yum repository, but I want to permanently enable a repository.
Is there a preferred Yum command to enable a disabled repository, or should I edit the .repo file under /etc/yum.repos.d?
Using RHEL 5.5.

A: If you're using PackageKit on top of yum, you can do it with pkcon:
% pkcon repo-disable myrepo
Enabling repository           [=========================]
Waiting in queue              [=========================]
Waiting for authentication    [=========================]
Waiting in queue              [=========================]
Starting                      [=========================]
Getting information           [=========================]
% pkcon repo-enable myrepo
Enabling repository           [=========================]
Waiting in queue              [=========================]
Waiting for authentication    [=========================]
Waiting in queue              [=========================]
Starting                      [=========================]
Getting information           [=========================]
Downloading repository information[=========================]

Note that, as the output indicates, running the command as a regular user typically means you'll be prompted for authentication before it'll complete.

A: No: the configuration files must be edited with a text editor. Yum does not have commands or options to edit the configuration.


text:
Q: Google Pie Chart is not displaying at all in IE9 I have a simple Pie Chart that displays fine in FireFox or Chrome but doesn't display in IE9. I just get a white screen, nothing else in IE9. Can someone help me figure out what is wrong and help me fix this? Thanks a lot.

A: Shouldn't the hashtags in your array be quoted, or perhaps they are unreplaced placeholders in your back-end script. Very likely IE breaks on this.


text:
Q: How many dismentals of set A exists?
Let A be a set, let n be a natural number and let $\langle B_0,B_1,...,B_{n-1} \rangle$ series with $n$ length of subsets of set A.
  We say $\langle B_0,B_1,...,B_{n-1} \rangle$ is dismental of set A if satisfies the following conditions:

*

*$\bigcup \{B_i:i\in \Bbb{N}^{<n}\}=A$

*$\forall{i,j} \in \Bbb{N}^{<n}$ if $i\neq j$ then $B_i \cap B_j = \emptyset$

The question:

Let $n,k$ be natural numbers and let $A$ be a set with $k$ elements.
  How many $n$-dismentals of $A$ exists? prove your answer.

EDITED: It is not forbidden to use $\emptyset$ than once, for example:
$\langle \{2 \},\{1,3\} \rangle$ ,
$\langle \{1,3 \},\{2\} \rangle$ and
$\langle \{1,2,3 \}, \emptyset \rangle$ are three examples of 2-dismentals of $A=\{1,2,3\}$.
One more example, $\langle \{4 \},\emptyset,\{5\} \rangle$ and $\langle \emptyset,\emptyset,\{4,5\} \rangle$ are two examples of 3-dismentals of $A=\{4,5\}$
According to drhab solution,
We will prove using induction that $n^k$ is the answer.

Claim: For all k and for all n exists $n^k$ dismentals of set A.

Proof: We will prove by induction method on number of the elements in A. i.e $|A|=k$.
Let k is a natural number.

*

*Base case k=0:

Let n a natural number, then exists $n^0=1$ dismentals of A.
so A is an emptyset then we could have in a series just an emptyset in each dismentals. each element will be an emptyset for n-dismentals.

*

*Induction step:

We assume our claim is correct for |A|=k and will prove it for |A|=k+1. let n be a natural number. if n<=k then we mark set $Z=A - \{n\}$. According to our assumption exists $n^k$ dismentals of A and $A=Z\cup \{n\}$ so for since $\{n\}$ we got this is true for $n^{k+1}$.
My questions is:

*

*In case n>k, how can we end the proof?

*Is it correct to formulate the claim as I wrote? i.e for all k, for all n.....

A: My first thinking:
Let $p_{n,k}$ denote the number of $n$-dismentals of set $A$ that has $k$ elements.
Then evidently: $$p_{1,k}=1\tag1$$
Next to that we have:$$p_{n+1,k}=\sum_{i=0}^k\binom{k}{i}p_{n,k-i}\tag2$$
To understand: if $B_n$ is taken to be a set that has $i$ elements then here are $\binom{k}{i}$ choices for $B_n$ and $\langle B_0,\dots,B_{n-1}\rangle$ must be a dismental of the set $A-B_n$ that has $k-i$ elements. There are $p_{n,k-i}$ such dismentals.
Question is now: can we find a closed form for $p_{n,k}$ on base of $(1)$ and $(2)$?
Looking at it for small $k$ a conjecture arises, and it is indeed easy to prove with induction that:$$p_{n,k}=n^k\tag3$$
This makes me think that a more elegant route must exist, and giving it a second thought in this light I found the answer under the line:

My second thinking:
Constructing a $n$-dismental $\langle B_0,\dots,B_{n-1}\rangle$ of $A$ boils down to dividing the set $A$ in $n$ disjoint and covering subsets (why on earth didn't I see that immediately...). That means that for each of the $k$ elements of $A$ there are $n$ choices. That tells us immediately that $(3)$ is correct.

addendum:
Induction works like this.
Let $E(n)$ be the statemement that $p_{n,k}=n^k$ for every nonnegative integer $k$.
Then $E(1)$ is true according to $(1)$.
It remains to be proved that $E(n)\implies E(n+1)$.
If for  every nonnegative integer $k$ indeed $p_{n,k}=n^k$ (i.e. $E(n)$ is a true statement) then for an arbitrary fixed $k$ we find: $$p_{n+1,k}=\sum_{i=0}^k\binom{k}{i}p_{n,k-i}=\sum_{i=0}^k\binom{k}{i}n^{k-i}=\sum_{i=0}^k\binom{k}{i}1^kn^{k-i}=(n+1)^k$$and conclude that $E(n+1)$ is a true statement.


text:
Q: Animated background for button How to make animated background for button in Android Studio

*

*Hello guys, I am an java android application developer.  In my project, I want to use a button with an animated background. What does it mean? The button class has a method .setBackgroundResource(int res_id), where do we pass R.drawable.some_res. I have video(R.raw.some_video). Can I use this video as a background for a button, and so that when it ends, it starts playing again. And another question is whether this background will consume a lot of phone resources.

A: To create an animated background for a button in Android Studio, you can use an animation drawable.

*

*Create a new XML file in the res/drawable folder and give it a descriptive name, such as "button_background.xml".

*In the XML file, add the following code:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item android:drawable="@drawable/frame_1" android:duration="50"/>
    <item android:drawable="@drawable/frame_2" android:duration="50"/>
    <!-- Add additional frames as needed -->
</animation-list>

*Replace "frame_1" and "frame_2" with the names of the drawables you want to use for each frame of the animation.

*In your button's Java code, set the background of the button using the following code:

button.setBackgroundResource(R.drawable.button_background);

Note that the "android:oneshot" attribute is set to "false", which means that the animation will repeat indefinitely. If you want the animation to play only once, set this attribute to "true".
Keep in mind that using animations as background resources can consume more system resources than using static images, so be mindful of the size and length of the animation.


text:
Q: Asp.net core Caching In-Memory and Distributed together Can In-Memory caching and Distributed Cache be used together in the same application? Does it make sense after all?
A logic scenario that comes to my mind is to manager Session state (on top of In-Memory, taking advantage of sticky sessions ) and  Distributed for other caching. However I don't know if this makes sense after all.

A: Yes, you can.  One implements IMemoryCache, other implements IDistributedCache.
IMemoryCache will not work properly if you have non-sticky sessions and multiple servers.
Also you may want to use service.AddDistributedMemoryCache(); instead of service.AddMemoryCache();


text:
Q: fetch api - has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status There are many similar questions around this topic but I could not find what I am missing in this fetch api request. could you someone help me to overcome this error ? how to set the http status ok in fetch api request. I understand we need to set this for OPTIONS method but not sure how to set this.
I have also tried adding no-cors mode but it is failing with code 415
The same request when I tried using Postman, it is working fine but failing fetch api request
Error:
from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status
var myHeaders2 = new Headers();
myHeaders2.append("Content-Type", "application/json");
myHeaders2.append("Accept", "application/json");
myHeaders2.append('Acces-Control-Allow-Origin', 'https://example.com');
myHeaders2.append('Access-Control-Allow-Methods', "DELETE, POST, GET, OPTIONS");
myHeaders2.append("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, Origin, X-Auth-Token");
myHeaders2.append("Access-Control-Max-Age", "86400");
// myHeaders2.append("status", "200");

let obj = {};
obj.file_name = 'test1.txt';
obj.file_content = objJsonB64;

var raw = JSON.stringify(obj);

var uploadReqOptions = {
    method: 'POST',
    headers: myHeaders2,
    body: raw,
    redirect: 'follow'
};

fetch("https://destinationxyz.com", uploadReqOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));

A: I have already face this issue.
Told your api provider to set Acces-Control-Allow-Origin in their code.
This not an issue of your code.
Chilll.....

A: Install chrome extention "CORS unblock".
The problem is caused by your browser blocking the requests


text:
Q: Is there any way to find if the given URLs is an RSS feed or atom using Java?  I am writing an RSS parser. Is there any way to find if the given URL is RSS or atom using Java?

A: You could use ROME (I suggest that first) for parsing RSS and Atom Feeds. Alternatively, you'll have to use a SAX parser or create a DOM tree and do the following:
For RSS:
In RSS, you will have to check that there's a rss element, and it's child must contain a channel element. There can be 0 or more item in RSS (I might be wrong).
Example:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
    <title>RSS Title</title>
    <description>This is an example of an RSS feed</description>
    <link>http://www.someexamplerssdomain.com/main.html</link>
    <lastBuildDate>Mon, 06 Sep 2010 00:01:00 +0000 </lastBuildDate>
    <pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>

    <item>
        <title>Example entry</title>
        <description>Here is some text containing an interesting description of the thing to be described.</description>
        <link>http://www.wikipedia.org/</link>
        <guid>unique string per item</guid>
        <pubDate>Mon, 06 Sep 2009 16:45:00 +0000 </pubDate>
    </item>

</channel>
</rss>

For Atom:
In Atom, you will have to check that there's a feed element. There can be 0 or more entry in Atom. (I might be wrong).
Example:
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

    <title>Example Feed</title>
    <subtitle>A subtitle.</subtitle>
    <link href="http://example.org/feed/" rel="self" />
    <link href="http://example.org/" />
    <id>urn:uuid:60a76c80-d399-11d9-b91C-0003939e0af6</id>
    <updated>2003-12-13T18:30:02Z</updated>
    <author>
        <name>John Doe</name>
        <email>johndoe@example.com</email>
    </author>

    <entry>
        <title>Atom-Powered Robots Run Amok</title>
        <link href="http://example.org/2003/12/13/atom03" />
        <link rel="alternate" type="text/html" href="http://example.org/2003/12/13/atom03.html"/>
        <link rel="edit" href="http://example.org/2003/12/13/atom03/edit"/>
        <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
        <updated>2003-12-13T18:30:02Z</updated>
        <summary>Some text.</summary>
    </entry>

</feed>

PS: I don't know which RSS version or Atom version you want to implement, but follow their guidelines.

*

*RSS

*Atom

*RSS 2.0 and Atom 1.0 compared


text:
Q: How do I call the Azure REST API from an interactive PowerShell session I want to be able to call Azure REST API methods from an interactive PowerShell session.  There are instructions on how to do this with a Service Principal here but I want to be able to call these methods using my own credentials rather than switching to a different set.  This will make it easier to work out the methods I need to call locally and also to gather information from Azure on an ad hoc basis.
An example of a call I'd like to make that can't be done with existing PowerShell cmdlets is
https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/products/{productId}/policies/policy?api-version=2019-01-01

A: When you login to Azure with Login-AzureRmAccount or Login-AzAccount and then call an AzureRm or Az cmdlet a bearer token will be obtained by from Azure and stored in your context object.  You can retrieve your context object with Get-AzureRmContext or Get-AzContext and parse the token from that object.
    $Context = Get-AzContext
    $Cache = $Context.TokenCache
    $CacheItems = $Cache.ReadItems()
    $Token = ($CacheItems | Where-Object { $_.Resource -eq "https://management.core.windows.net/" })

The token will last for an hour, if it expires you'll need to renew it by calling an Azure cmdlet again (though it may be possible to renew it programatically).
This code could be wrapped in a function like
function Invoke-AzureRestApi {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [String]$Uri
    )

    $Context = Get-AzContext
    $Cache = $Context.TokenCache
    $CacheItems = $Cache.ReadItems()
    $Token = ($CacheItems | Where-Object { $_.Resource -eq "https://management.core.windows.net/" })
    $Headers = @{Authorization = "Bearer $($Token.AccessToken)"}

    Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers

}

# run an Az or AzureRm cmdlet to get a token prior to calling the function
Invoke-AzureRestApi -Uri https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/products/{productId}/policies/policy?api-version=2019-01-01

# A simpler example to test the function (though this particular example can be more easily achieved with Get-AzResourceGroup)
Invoke-AzureRestApi -Uri https://management.azure.com/subscriptions/{subscriptionId}/resourcegroups?api-version=2019-08-01

UPDATE (31/8/2021):
the token can now be retrieved simply using the Get-AzAccessToken cmdlet
function Invoke-AzureRestApi {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [String]$Uri
    )

    $Token = Get-AzAccessToken
    $Headers = @{Authorization = "Bearer $($Token.Token)"}
    Invoke-RestMethod -Method GET -Uri $Uri -Headers $Headers
}

A: you could just use Get-AzResource to achieve the same outcome, without the headache of dealing with tokens.
Your particular example call doesnt make a lot of sense, it can be replaced with Get-AzResourceGroup


text:
Q: React-Redux: How to actually update a state of redux store which has dependency on other values of the store I am new to using React-Redux. Hence, I'm facing some problems with this particular situation. My Redux Store is something like this:
{
    info: {firstName: 'abc', lastName: 'xyz', email: abc.xyz@gmail.com, name: 'abc xyz', id: 145},
    userInfo: {firstName: 'abc', lastName: 'xyz', email: abc.xyz@gmail.com, contactNumber: 1234567890, country: 'India'}
}

Now, I receive both these details from different pages. I store them on the store and make API calls using react-redux to update the store data. So, I receive both of these data using a separate API call. Now, when I update the userInfo payload, I successfully can update my userInfo store state. But, the firstName and lastName are 2 fields which are common. So, what should be the best practice to update the info, every time I update the userInfo, because they have to be in sync and same.
Pasting some of the redux code for reference:
reducer.js (for info)
import * as actionTypes from './actionTypes';

export const initialState = {
  email: null,
  firstName: null,
  id: null,
  lastName: null,
  name: null
};

export default function(state = initialState, action) {
  switch (action.type) {
    case actionTypes.SET_INFORMATION: {
      const { info = {} } = action;
      return { ...info };
    }
    default:
      return state;
  }
}

reducer.js (for userInfo)
import * as actionTypes from './actionTypes';

export const initialState = {
    firstName: null,
    lastName: null,
    email: null,
    contactNumber: null,
    country: null
};

export default function(state = initialState, action) {
  switch (action.type) {
    case actionTypes.USER_INFORMATION: {
      const { userInfo = {} } = action;
      return { ...state, ...userInfo };
    }
    case actionTypes.GET_USER_INFORMATION_ERROR:
    case actionTypes.PATCH_USER_INFORMATION_HEADER_ERROR: {
      const { error = {} } = action;
      return { ...error };
    }
    case actionTypes.PATCH_USER_INFORMATION_HEADER: {
      const { userInfo: { data = {} } = {} } = action;
      return { ...state, ...data };
    }
    default:
      return state;
  }
}

Please help me with the best practice to update both these data whenever the other one is updated to keep the data in sync. TIA.

A: For a more reducer-centric approach, use another reducer(as a wrapper) to handle cases where data needs to be shared across reducers, like this:
const combinedReducer = combineReducers({
    info: infoReducer,
    userInfo: userInfoReducer
});

function specialCaseReducerWrapper(state, action) {
    switch (action.type) {
        case "SOME_SPECIAL_ACTION": {
            return {
                // specifically pass state.userInfo as an additional argument
                info: infoReducer(state.info, action, state.userInfo),
                userInfo: userInfoReducer(state.userInfo, action)
            };
        }
        default:
            return state;
    }
}

function rootReducer(state, action) {
    const intermediateState = combinedReducer(state, action);
    const finalState = specialCaseReducerWrapper(intermediateState, action);
    return finalState;
}

For reference, check Beyond combineReducers

A:
what should be the best practice to update the info, every time I update the userInfo, because they have to be in sync and same

The best practice is to never keep duplicate data in state. You are already going through a lot trying to synchronize it, and it will get even worse with time. You are very likely to run into situations where data is desynchronized and you or someone else working at this code might simply just forget to synchronize it again after implementing new changes. These bugs are hard to catch too
If you have common data between slices of your store, you need to leave only 1 instance of it


text:
Q: What is the default goroutine? The following code prints 2009/11/10 23:00:00 Num of goroutines:  1. Is there a way to know which go routine it is?
package main

import (
    "log"
    "runtime"
)

func main() {
    r := runtime.NumGoroutine()
    log.Println("Num of goroutines: ", r)
}

https://play.golang.org/p/pFOG6EQEYb

A: It's the main goroutine, encapsulating the main thread of execution. You might for instance observe that by printing goroutine stack traces in your example program:
package main

import (
    "log"
    "os"
    "runtime"
    "runtime/pprof"
)

func main() {
    r := runtime.NumGoroutine()
    log.Println("Num of goroutines: ", r)
    pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
}

Which produces the following:
2009/11/10 23:00:00 Num of goroutines:  1
goroutine profile: total 1
1 @ 0xa22a0 0xa1fc0 0x9d640 0x20180 0x5a0a0 0x98e81
#   0xa229f runtime/pprof.writeRuntimeProfile+0xdf  /usr/local/go/src/runtime/pprof/pprof.go:614
#   0xa1fbf runtime/pprof.writeGoroutine+0x9f   /usr/local/go/src/runtime/pprof/pprof.go:576
#   0x9d63f runtime/pprof.(*Profile).WriteTo+0xff   /usr/local/go/src/runtime/pprof/pprof.go:298
#   0x2017f main.main+0x17f             /tmp/sandbox832735226/main.go:13
#   0x5a09f runtime.main+0x39f          /usr/local/go/src/runtime/proc.go:183

Notice that runtime.main at the bottom of the trace.
A program with two goroutines alive when the traces are dumped:
package main

import (
    "log"
    "os"
    "runtime"
    "runtime/pprof"
)

func main() {
    c := make(chan int)
    go func() { <-c }()
    r := runtime.NumGoroutine()
    log.Println("Num of goroutines: ", r)
    pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
}

Will produce something along the lines of:
2009/11/10 23:00:00 Num of goroutines:  2
goroutine profile: total 2
1 @ 0x20220 0x98f61
#   0x20220 main.main.func1+0x0 /tmp/sandbox584983760/main.go:12

1 @ 0xa2380 0xa20a0 0x9d720 0x201e0 0x5a180 0x98f61
#   0xa237f runtime/pprof.writeRuntimeProfile+0xdf  /usr/local/go/src/runtime/pprof/pprof.go:614
#   0xa209f runtime/pprof.writeGoroutine+0x9f   /usr/local/go/src/runtime/pprof/pprof.go:576
#   0x9d71f runtime/pprof.(*Profile).WriteTo+0xff   /usr/local/go/src/runtime/pprof/pprof.go:298
#   0x201df main.main+0x1df             /tmp/sandbox584983760/main.go:15
#   0x5a17f runtime.main+0x39f          /usr/local/go/src/runtime/proc.go:183


text:
Q: Wordpress Plugin Setting's POST I've developed a few plugin for Wordpress. Currently I've not been able to replicate the way wp save settings. I've a setting page which I learned from a tutorial. It POST to option.php, and wp take care of saving the data.
But I have some custom option page which require more complex handling. Basically I wanted to POST some data to my own php, then redirect back to the original page/url after handling. I can't find a "proper" way to redirect correctly, i.e. without load the whole page then redirect using javascript.
Currently I use GET with add_query_arg(), the url will display the data that I passed. Using POST will trigger a redirect prompt when refreshed.
Is there a built in wp function that does it automatically? OR If I were to POST to option.php, how should I access the data without it handling automatically?
EDIT: Example of one of the complex page would be like this:
I assign a usermeta to some users which we would call SU (SpecialUser). To ease the job of admin, I have a page to display the list of users with a column showing whether they are SU. The text in that column of each row is a link which if clicked, will toggle the state of SU for that user. Currently I use GET, to pass the id of the user and also action to be carried out. Then page itself will detect, if both action and id is valid, the state of the user is toggled. At the same time, the updated result is displayed. The GET query remain at the URL
What I would really like to do is to use POST, pass the id and action to the same page, then toggle the state but not displaying anything, then "redirect" back to the page displaying the updated user list. What I've tried earlier while implementing this is to use javascript to redirect the page, but this means it will have to load the whole page before the javascript can be executed. It's not resource friendly. I would like it to work much like how the Settings API would.
Sorry for the long explaination. I'm sure there's a term to what I wanted to do, but I'm not sure what it is.
Thanks
EDIT: It's more or less like the Plugin page, when you activate/deactivate the plugin. The plugin page is using GET. The problem I have is actually redirecting, so GET or POST shouldn't matter.

A: if you are using the Settings API then you can use your own php inside the $sanitize_callback of your register_setting and return the value you want to save after doing your "more complex handling".

A: I've found a way to overcome what I needed by using wp_redirect(). I'm calling wp_redirect() after I've done processing. Also following advise from WordPress and wp_redirect() function problem, I added noheader=true to the form's action or link to prevent the error "header already sent" from php.


text:
Q: Using string split in Ruby?     str = "ex1:ex2:ex3"

I want to split the string with : delimiter and get only ex1 and ex2, and ignore ex3. When I do,
    first, rest = str.split(":")

It gives me the following
    ex1
   :ex2

I tried replacing : with a space
    str.gsub(":"," ")

But it still gives the same answer with the delimiter (:) with the second part
Is there any good way to split the string using Ruby where I am interested in only the first 2 parts of the string.
Expected answer is:
    ex1
    ex2

Thanks!!

A: str = "ex1:ex2:ex3"
first, rest = str.split(/\:/)
print "#{first} and #{rest}"    # output => "ex1 and ex2"

A: Perhaps you want this:
str = "ex1:ex2:ex3:ex4"

f,s = str.split(':')
f #=> "ex1"
s #=> "ex2"

If you want to return an array:
str.split(':').first(2)
  #=> ["ex1", "ex2"]

A: There is another way with a regex, too. First, we get only the first 2 groups between :, and then remove the rest of the string. And then split:
str = "ex1:ex2:ex3".gsub(/^(\w+\:\w+).*$/, "\1")
first, rest = str.split(":")

A: Through sub and gsub. Remove the last colon part and then replace the colons with newline character.
> str = "ex1:ex2:ex3"
> str.sub(/:[^:]*$/, "").gsub(/:/, "\n")
=> "ex1\nex2"


text:
Q: Converting NULL received from query builder into empty strings in Laravel
This is a sample db to illustrate my problem.I have a table in which there are some field (in fact many) that are optional and haven't been set to any default value.So obviously when I do
$user =  DB::table('users')
    ->select('*')
    ->where('id', $user_id)
    ->first();

gives a NULL for those fields
["id"]=>
int(120)
["name"]=>
string(4) "jack"
["email"]=>
string(12) "jack@example.com"
["mobile"]=>
string(11) "+4400123456"
["facebook_link"]=>
NULL
["twitter_link"]=>
NULL
["instagram_link"]=>
NULL
["youtube_link"]=>
NULL

which is a problem since I'll be sending this as an json API response and the mobile team isn't really happy to see a null there, they would rather prefer an empty string ('') instead.So would I go about this without manually checking each field like I am currently doing
$user->facebook_link = !empty($user->facebook_link)? $user->facebook_link: '';

You might say just assign the columns defaults well that can be done but it will take some more time as it's a remote database.Currently my best bet is COALESCE but I am hoping for some tweak in laravel itself that would solve this issue

A: Seems like there is no other way except defined the accessor method inside User Model itself:
public function getFacebookLinkAttribute($value)
{
  return $value ?: 'default value';
}

With this approach, you only need to set once inside model rather than COALESCE on every query. But do remember, it will return the default value when you accessing it inside your code.
Another approach would be using the resources and transformer(fractal), it might not what you need but it worth to look at it.
Correct me if there is a way to handle this.

A: Unfortunately you are using QueryBuilder not ORM.
So in ORM you have multiple approaches like casting or Accessors.
$casts = [
    'facebook_link' => 'string'
]

OR
public function getFacebookLinkAttribute($value)
{
  return (string)$value;
}


text:
Q: Meaning of "to make amends" What's the meaning of the expression "to make amends" in the texts below:
Text 1:

You have to learn from mistakes and grow as an individual so you dont
  make the same mistakes twice. You can always try to make amends for
  past mistakes, pray God's forgiveness, and become the person you
  prefer to be.

Text 2:

Oh Lord, won't you buy me a Mercedes Benz? My friends all drive
  Porsches, I must make amends. Worked hard all my lifetime, no help
  from my friends, So Lord, won't you buy me a Mercedes Benz?

In the first example (Text 1) I found many different translations in Portuguese that makes sense and could be used but many of them have slightly different meanings and I'm not sure which one would be the more indicated here.
In this specific case does it relate to try to get someone's forgiveness for something you did in the past?
Regarding the Text 2 I have no idea what's the meaning of "make amends" in the context. No translation seems to make sense.
One last question: in Text 1 where it's said pray God's forgiveness the correct wouldn't be pray for God's forgiveness?

A:
make amends (v): to do something to correct a mistake that one has made or a bad situation that one has caused

Your first example of this phrase is fairly standard, and so requires no additional explanation.  You are correct, and it should be "pray for God's forgiveness".  I assume it's an unintentional error.
Janis Joplin's use of "make amends" is not standard.  It does imply that the speaker feels that her lack of a Mercedes Benz is some kind of personal fault, which she needs to make up for through divine intervention -- but, it's more likely that Joplin chose "amends" because it rhymes (more or less) with "Benz", and so fits the song.
Overall, the song is not meant to be taken literally.  It is a satire of consumerism, and possibly of those who think religion and prayer are best used to beg for material wealth.
Side note:  This was one of the last songs Joplin recorded before dying of a drug overdose in October, 1970 at age 27.


text:
Q: least upper bounds that are coprime Given $n$ natural numbers $p_1$, $p_2$, ... $p_n$ find numbers $q_1$, $q_2$, ... $q_n$ that are pairwise coprimes such that $p_i$ ≤ $q_i$ and such that $\prod_{i=1..n} q_i$ is smallest possible.
I come from programing background. When I try to phrase this in my computer science language, then the question would be:
I have integer sided hyper rectangle. How do I find smallest (with respect to volume) integer sided hyper rectangle which contains my hyper rectangle such that greatest common divisor of any two side lengths equals to one.


text:
Q: Override bold fonts with normal fonts For any applied theme, I want to override the bold fonts with normal fonts. How do I do that?

A: Assuming you're using Emacs 24's built-in themes,
my answer to this question applies pretty well.  Something like this (untested):
(defun debold-font-lock ()
  "remove all colors from font-lock faces except comment and warning"
  (mapc (lambda (face)
          (when face
            (set-face-bold-p face nil)))
        (face-list)))

(debold-font-lock)

You can add this to load-theme with an advice if you need it to always happen.
EDIT: I mentioned an advice above, but it's generally better to not advice if
you can help it.
So we can define a new function:
(defun load-theme-no-bold ()
  (interactive)
  (call-interactively 'load-theme)
  (debold-font-lock))

Map this function to a key as required or call it directly from M-x.
EDIT: Advice info.
In Emacs you can change the way any function works using the advice mechanism.
You think "P" should be inserted with the key a is pressed?  No problem.
See docs.
Because this is a powerful tool, it tends to get trotted out a lot, but really
it should only be applied as a last resort, because you never know what
packages out there depend on the existing behaviour.


text:
Q: Export in an if statement using meteor it is fairly easy to import a file within an if statement like so:
import { Meteor } from 'meteor/meteor';

if (Meteor.isServer) {
  const thing = require('./blah').default;
}

However, what I am wondering is if you can export a default member of a module within an if statement without binding it to the global scope or window
if (Meteor.isServer) {
  export serverOnlyFunction = require('./blah').default;
}

How would this be accomplished in meteor?

A: This is not possible as you've written it, since exports must be defined at the top level (from §A.5 of the spec). This is related to how modules are handled when lazy-loading or circular dependencies occur and the code can't be executed during or before loading.
You can avoid this mess entirely by exporting the branch, rather than exporting from within a branch:
export function getTheFunction() {
  if (Meteor.isServer) {
    return serverOnlyFunction;
  } else {
    return functionForEverybody;
  }
}

Alternatively, a wrapper function will work just as well:
export function wrapTheFunction(...args) {
  if (Meteor.isServer) {
    return serverOnlyFunction.apply(this, args);
  } else {
    return functionForEverybody.apply(this, args);
  }
}

If you're using exports directly without the ES6 keyword, you could assign from within the branch:
if (Meteor.isServer) {
  module.exports = serverOnlyFunction;
} else {
  module.exports = functionForEverybody;
}

But, unless you're stuck on ES5, this is poor practice. Exporting a function able to decide is a far more robust solution.
Secondly:
import { Meteor } from 'meteor/meteor'; // <- is an import

if (Meteor.isServer) {
  const thing = require('./blah').default; // <- is *not* an import
}

require is not an import. They are two very different things with very different behavior. Furthermore, require is a runtime call made to an API provided by the runtime (node or requirejs) and return synchronously.
The correct ES6 equivalent would be:
if (Meteor.isServer) {
  System.import('./blah').then((thing) => {
    // do something with thing
  });
}


text:
Q: What is a notation for the minimal ordinal of $\mathbb{R}$? What is a notation for the minimal ordinal of $\mathbb{R}$?
I know that $\beth_1$ and $\mathfrak{c}$ designate the cardinality of $\mathbb{R}$, and that $\Omega$ denotes the smallest uncountable ordinal, and that $\aleph_1$ denotes the first uncountable cardinal, and that $\Omega$ and $\beth_1$ and $\aleph_1$ are all equipollent if CH is true, but what is a notation for the smallest ordinal equipollent to $\mathbb{R}$ which doesn't implicitly assume any position on CH?

A: There need not be any ordinal equipollent to $\Bbb R$, so there isn't really a standard notation for the least such (at least, none that I'm aware of). Note also that $\omega_1$ is typically used to denote the least uncountable ordinal, except when the reader is expected to have little to no familiarity with ordinals, in which case $\Omega$ is used instead. (Thanks, Brian, for prompting the clarification.)
More generally, we'll typically take $\omega_\alpha$ to be the least ordinal having the cardinal $\aleph_\alpha$. In fact, we'll take $\omega_\alpha$ and $\aleph_\alpha$ to be the same thing. We'll choose one notation over the other depending on whether we're talking about cardinalities or order types, or whether we're using cardinal arithmetic or ordinal arithmetic.
If we assume AC (or at least enough choice so that $\Bbb R$ is well-ordered), then the cardinal of $\Bbb R$--that is $\mathfrak{c}$--can be taken to be an ordinal, in particular the least ordinal equipollent to $\Bbb R$.

A: Assuming the axiom of choice and $\frak c$ is a well-ordered cardinal, it means that $\frak c$ is an initial ordinal, namely it is the least ordinal which can be put in bijection with the real numbers.
It is not uncommon to see $\alpha<\frak c$.
If one wishes to be completely formal and separate the cardinal and ordinal form, one can write:

Let $\aleph_\alpha$ be the cardinality of the continuum. We enumerate $\mathbb R$ as $\{x_\beta\mid \beta<\omega_\alpha\}$ ...


text:
Q: JavaScript event handling onkeyup Following snippet:
<input type='text' name='text1' onkeyup='exec(this.value);'/>

The exec() method should not proceed if any of the following key is pressed on the textbox:
shift,
ctrl,
alt,
caps,
tab,
esc,
home,
etc

Is there a cross browser way without jQuery to do it?


text:
Q: Reduce whitespace between columns in a chakra Table I'm creating a basic small Table in chakra-ui, however the whitespace between columns is too much for my particular use case. I've set size="sm" but it's still too much whitespace.

How can we achieve this? Here's a summary snippet of pseudo-code corresponding to my problem:

    // ...

    //...

Here's the full worked example in codesandbox:
https://codesandbox.io/s/responsive-table-forked-ut904?file=/src/ResponsiveTable.tsx:196-344

A: You just to add css to override css of Table:

and in css:
.table-tiny th,
.table-tiny td {
  padding-left: 4px;
  padding-right: 4px;
}

https://codesandbox.io/s/responsive-table-forked-8683s?file=/src/ResponsiveTable.tsx

A: Just Override this sass this will make less padding of table cell

.css-vooc0a {
  padding-inline-start: var(--chakra-space-1);
  padding-inline-end: var(--chakra-space-1);
  text-align: center;
}


text:
Q: Apple Music Library Does Not Sync Correctly Between Two Macs I use a Mac mini as a server and an iMac to work on. I maintain my music collection on the iMac, but I regularly copy the chances over to the Mac mini using an AppleScript with a rsync command.
This used to work fine for the time I was using iTunes. Now, under Catalina, changes to the library are not noticed by the Apple Music App on the Mac mini.
I know the Music Library file is updated correctly, and also the individual albums and songs get copied to the Mac mini just like they should. For example, Roon is running on the Mac mini too, and it notices the changes. But the Apple Music App just shows the status of the collection of the time where I first copied the whole collection to the Mac mini.
Are there some cache files somewhere I have to take care for? So far, the AppleScript syncs the folders /Users/User/Music/iTunes and /Users/User/Music/Music (only from iMac to Mac mini).


text:
Q: How to convert a LambdaExpression to typed Expression> I'm dynamically building linq queries for nHibernate.
Due to dependencies, I wanted to cast/retrieve the typed expression at a later time, but I have been unsuccessfull so far.
This is not working (the cast is supposed to happen elsewhere):
var funcType = typeof (Func<,>).MakeGenericType(entityType, typeof (bool));
var typedExpression =  (Func<T, bool>)Expression.Lambda(funcType, itemPredicate, parameter); //Fails

This is working:
var typedExpression = Expression.Lambda<Func<T, bool>>(itemPredicate, parameter);

Is it possible to get the 'encapsulated' typed expression from a LambdaExpression?

A: var typedExpression =
    (Func<T, bool>)Expression.Lambda(funcType, itemPredicate, parameter); //Fails

This is not surprising, as you have to Compile a LambdaExpression in order to get an actual delegate that can be invoked (which is what Func<T, bool> is).
So this would work, but I 'm not sure if it is what you need:
// This is no longer an expression and cannot be used with IQueryable
var myDelegate =
    (Func<T, bool>)
    Expression.Lambda(funcType, itemPredicate, parameter).Compile();

If you are not looking to compile the expression but instead to move an expression tree around, then the solution is to instead cast to an Expression<Func<T, bool>>:
var typedExpression = (Expression<Func<T, bool>>)
                      Expression.Lambda(funcType, itemPredicate, parameter);


text:
Q: CSS formatting not indenting second row of an ng-repeat output Trying to obtain the following format for output from script:
Days of operation:
                Sunday:     Closed
                Monday:     8am - 9am
                            9am - 10am
                Tuesday:    8am - 9am
                            9am - 12pm
                Wednesday:  8am - 9am
                Thursday:   9am - 10am
                            11am - 12pm

… and so on.  Instead, output ends up like this:
Days of operation:
                    Sunday:     Closed
                    Monday:     8am - 9am
                    9am - 10am
                    Tuesday:    8am - 9am
                    9am - 12pm
                    Wednesday:  8am - 9am
                    Thursday:   9am - 10am
                    11am - 12pm

Could use some help to figure out what I'm doing incorrectly with the layout piece that's preventing me from getting the desired result. Here's the code I have in my index.css for formatting:
#details label{
  width: 240px;
}
#details .hours-layout{
    float: left;
    width: 100px
}
.label-left {
  float: left;
}
.content-right {
  display: block;
  overflow: hidden;
}

Here's the code from my html script:

{{listing_ctrl.COMMON.facilityType}}:{{ listing_ctrl.listing.program }}

{{listing_ctrl.COMMON.facilityOpened}}:{{ listing_ctrl.listing.dateFounded ? (listing_ctrl.listing.dateFounded | date:'MM/dd/yyyy':'+0') : "Not Available" }}

{{listing_ctrl.COMMON.capacity}}:{{ listing_ctrl.listing.capacity }}

{{listing_ctrl.COMMON.hoursOfOp}}:<class="content-right">Not available

{{listing_ctrl.COMMON.hoursOfOp}}:

                                                {{day.day}}:

                                                                Closed

                                                                {{sched.open}} - {{sched.close}}

A: You can use interpolation within the style attribute to set your margin on the second (and third, fourth...) items in your ng-repeat. Putting the pieces together from the comments and answers here is your working solution. The reason you have to use a
 instead of a  is that  tags cannot use margin or height style settings. Personally, I always prefer to use
 elements for positioning. I typically only use  along with ng-if to display conditional text or to apply font/text styles to a word or two in a longer string of text.

                Closed

 0 ? 'margin-left : 100 px' : '' }}">
               {{sched.open}} - {{sched.close}}

The reason I asked about Bootstrap is because this becomes a little cleaner when you use a layout framework. Bootsrap (and Material) use row/column type layouts which makes achieving what you're after easier and responsive. When you need to offset your hours you simply add an offset class using ng-class. Personally, I find this approach much cleaner than using interpolation within the style attribute.

                Closed

 0}">
               {{sched.open}} - {{sched.close}}

A: some thing like the following should help you.

                Closed

           1 && margin-left : 100 px">
               {{sched.open}} - {{sched.close}}

Explaination : you can achieve conditional formatting using ng-style. More info here


text:
Q: Is it safe to use return to skip rest of php file? My PHP application looks like this:
<?php
// File: index.php

// some code...
include( 'template/header.php' );

// More code, for example:
echo "Subscribe to our newsletter here: ...";

And template file:
<?php
// File: template/header.php

$user = get_loggedin_user()
if ( ! $user ) {
  echo 'Please log in';
  return;  // Question is about this statement!
}

// Long PHP code follows, for simplicity reduce it to:
echo "You are logged in as $user";

You see in the condition in template/header.php I use return to skip the header if user is not logged in. I do not want to use else because the code that follows is quite long and nested, so I want to avoid adding another nesting level here...
This usage of return seems to work correctly on php 5.6
Question:

*

*Is this correct, or is there a more appropriate way to skip rest of the header file?

*You know of any notices/warnings/errors that PHP could throw here?

A: Short answer: Yes
Possible, safe, officially supported.

Successful includes, unless overridden by the included file, return 1. It is possible to execute a return statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files.

Example:
<?php
// return.php
$var = 'PHP';
return $var;
?>

<?php
// noreturn.php
$var = 'PHP';
?>

<?php
// Test script

$foo = include 'return.php';
echo $foo; // prints 'PHP'

$bar = include 'noreturn.php';
echo $bar; // prints 1
?>

A: What I like to do is thow a custom exception, because you can catch exceptions, even when you call a function with the login validation in it.
Return should be sufficient if the PHP code is in your current scope, but return is not sufficient when validating if your user is logged in within a function.
To demonstrate this I have attached 2 PHP files below, index.php file which I assume is the file you're executing and a functions file called func.php.
index.php
<?php

require('func.php');

try {
  $user = get_loggedin_user();
} catch(NotLoggedInException $e) {
  echo 'do your redirect here';
  die();
}

var_dump($user); // shows user value

func.php
<?php

class NotLoggedInException extends Exception {

}

function get_loggedin_user() {
    throw new NotLoggedInException("User is not logged in");
}


text:
Q: Efficient evaluation of a function at every cell of a NumPy array Given a NumPy array A, what is the fastest/most efficient way to apply the same function, f, to every cell?

*

*Suppose that we will assign to A(i,j) the f(A(i,j)).

*The function, f, doesn't have a binary output, thus the mask(ing) operations won't help.
Is the "obvious" double loop iteration (through every cell) the optimal solution?

A: A similar question is: Mapping a NumPy array in place.
If you can find a ufunc for your f(), then you should use the out parameter.

A: You could just vectorize the function and then apply it directly to a Numpy array each time you need it:
import numpy as np

def f(x):
    return x * x + 3 * x - 2 if x > 0 else x * 5 + 8

f = np.vectorize(f)  # or use a different name if you want to keep the original f

result_array = f(A)  # if A is your Numpy array

It's probably better to specify an explicit output type directly when vectorizing:
f = np.vectorize(f, otypes=[np.float])

A: If you are working with numbers and f(A(i,j)) = f(A(j,i)), you could use scipy.spatial.distance.cdist defining f as a distance between A(i) and A(j).

A: I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.
One can write his own customised ufunc in C, which surely is more efficient, or by invoking np.frompyfunc, which is built-in factory method. After testing, this is more efficient than np.vectorize:
f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)

%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms

I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post

A: When the 2d-array (or nd-array) is C- or F-contiguous, then this task of mapping a function onto a 2d-array is practically the same as the task of mapping a function onto a 1d-array - we just have to view it that way, e.g. via np.ravel(A,'K').
Possible solution for 1d-array have been discussed for example here.
However, when the memory of the 2d-array isn't contiguous, then the situation a little bit more complicated, because one would like to avoid possible cache misses if axis are handled in wrong order.
Numpy has already a machinery in place to process axes in the best possible order. One possibility to use this machinery is np.vectorize. However, numpy's documentation on np.vectorize states that it is "provided primarily for convenience, not for performance" - a slow python function stays a slow python function with the whole associated overhead! Another issue is its huge memory-consumption - see for example this SO-post.
When one wants to have a performance of a C-function but to use numpy's machinery, a good solution is to use numba for creation of ufuncs, for example:
# runtime generated C-function as ufunc
import numba as nb
@nb.vectorize(target="cpu")
def nb_vf(x):
    return x+2*x*x+4*x*x*x

It easily beats np.vectorize but also when the same function would be performed as numpy-array multiplication/addition, i.e.
# numpy-functionality
def f(x):
    return x+2*x*x+4*x*x*x

# python-function as ufunc
import numpy as np
vf=np.vectorize(f)
vf.__name__="vf"

See appendix of this answer for time-measurement-code:

Numba's version (green) is about 100 times faster than the python-function (i.e. np.vectorize), which is not surprising. But it is also about 10 times faster than the numpy-functionality, because numbas version doesn't need intermediate arrays and thus uses cache more efficiently.

While numba's ufunc approach is a good trade-off between usability and performance, it is still not the best we can do. Yet there is no silver bullet or an approach best for any task - one has to understand what are the limitation and how they can be mitigated.
For example, for transcendental functions (e.g. exp, sin, cos) numba doesn't provide any advantages over numpy's np.exp (there are no temporary arrays created - the main source of the speed-up). However, my Anaconda installation utilizes Intel's VML for vectors bigger than 8192 - it just cannot do it if memory is not contiguous. So it might be better to copy the elements to a contiguous memory in order to be able to use Intel's VML:
import numba as nb
@nb.vectorize(target="cpu")
def nb_vexp(x):
    return np.exp(x)

def np_copy_exp(x):
    copy = np.ravel(x, 'K')
    return np.exp(copy).reshape(x.shape)

For the fairness of the comparison, I have switched off VML's parallelization (see code in the appendix):

As one can see, once VML kicks in, the overhead of copying is more than compensated. Yet once data becomes too big for L3 cache, the advantage is minimal as task becomes once again memory-bandwidth-bound.
On the other hand, numba could use Intel's SVML as well, as explained in this post:
from llvmlite import binding
# set before import
binding.set_option('SVML', '-vector-library=SVML')

import numba as nb

@nb.vectorize(target="cpu")
def nb_vexp_svml(x):
    return np.exp(x)

and using VML with parallelization yields:

numba's version has less overhead, but for some sizes VML beats SVML even despite of the additional copying overhead - which isn't a bit surprise as numba's ufuncs aren't parallelized.

Listings:
A. comparison of polynomial function:
import perfplot
perfplot.show(
    setup=lambda n: np.random.rand(n,n)[::2,::2],
    n_range=[2**k for k in range(0,12)],
    kernels=[
        f,
        vf,
        nb_vf
        ],
    logx=True,
    logy=True,
    xlabel='len(x)'
    )

B. comparison of exp:
import perfplot
import numexpr as ne # using ne is the easiest way to set vml_num_threads
ne.set_vml_num_threads(1)
perfplot.show(
    setup=lambda n: np.random.rand(n,n)[::2,::2],
    n_range=[2**k for k in range(0,12)],
    kernels=[
        nb_vexp,
        np.exp,
        np_copy_exp,
        ],
    logx=True,
    logy=True,
    xlabel='len(x)',
    )

A: All above answers compares well, but if you need to use custom function for mapping, and you have numpy.ndarray, and you need to retain the shape of array.
I have compare just two, but it will retain the shape of ndarray. I have used the array with 1 million entries for comparison. Here I use square function. I am presenting the general case for n dimensional array. For two dimensional just make iter for 2D.
import numpy, time

def A(e):
    return e * e

def timeit():
    y = numpy.arange(1000000)
    now = time.time()
    numpy.array([A(x) for x in y.reshape(-1)]).reshape(y.shape)
    print(time.time() - now)
    now = time.time()
    numpy.fromiter((A(x) for x in y.reshape(-1)), y.dtype).reshape(y.shape)
    print(time.time() - now)
    now = time.time()
    numpy.square(y)
    print(time.time() - now)

Output
>>> timeit()
1.162431240081787    # list comprehension and then building numpy array
1.0775556564331055   # from numpy.fromiter
0.002948284149169922 # using inbuilt function

here you can clearly see numpy.fromiter user square function, use any of your choice. If you function is dependent on i, j  that is indices of array, iterate on size of array like for ind in range(arr.size),  use numpy.unravel_index to get i, j, .. based on your 1D index and shape of array numpy.unravel_index
This answers is inspired by my answer on other question here


text:
Q: Loading images on website load instead of page load On My Website I need to load images on the index page because they are taking too long to load on other pages and it looks awful. Could somebody show me a very easy way to load images in the background of the index page so when the user clicks on the other pages the images have already loaded in their cache?
Thanks in advance

A: Take a look at this. It's about preloading with JS.
http://www.mediacollege.com/internet/javascript/image/preload.html
And this option is without JS:
How to Preload Images without Javascript?


text:
Q: Подключение к IP-камере через OpenVPN Есть OpenVPN-сервер, через который некоторое количество компьютеров соединено в "локальную сеть" с адресами вида 10.10.1.Х
10.10.1.1 - это адрес сервера.
10.10.1.2 - это адрес машины, на которой я хочу видеть поток с IP-камеры.
10.10.1.3 - это Raspberry Pi 3, в eth0 которого подключена камера. Назначены статичные IP на камере(192.168.1.254) и на самой Pi(192.168.1.2). Основным шлюзом у них прописан 192.168.1.1.
Pi по wlan0 подключается к интернету, с помощью OpenVPN создается tun0(который получает адрес 10.10.1.3).
Со всех устройств ping прекрасно добивает до Pi и обратно(внутри OpenVPN сетки).
И застопорился я на "сцеплении" интерфейсов.
В результате хочу получить, чтобы по 10.10.1.3:554 я мог получить RTSP-поток.

A:
хочу получить, чтобы по 10.10.1.3:554 я мог получить RTSP-поток

на машине с ip-адресом 10.10.1.3 надо добавить два правила netfilter-а — для dnat и для snat. приблизительно так:
$ iptables -A PREROUTING -i tun0 -p tcp -m tcp --dport 554 -j DNAT --to-destination 192.168.1.254
$ iptables -A POSTROUTING -o eth0 -p tcp -m tcp -j SNAT --to-source 192.168.1.2

смысл dnat-правила в том, чтобы у пакетов, пришедших на интерфейс tun0, порт 554, подменялся адрес назначения — на 192.168.1.254.
эти пакеты будут уходить через интерфейс eth0, где и сработает уже snat-правило, подменяющее адрес источника — на 192.168.1.2. смысл этого правила в том, чтобы когда ip-камера будет посылать ответные пакеты, оно слало их на этот адрес. netfilter при этом подменит адреса назначения и источника на «исходные», чтобы ответный пакет ушёл в правильном направлении и с правильным обратным адресом.

ах, да, стоит упомянуть, что на этой же машине должна быть разрешена передача пакетов между интерфейсами. смотрите, например, первый пункт этого ответа.


text:
Q: How to set video on webView thumbnail using MPMoviePlayerController? **
   How to set the thumbnail image got from MpMoviePlayerController as a thumbnail         when loading the video url string into web view?
and this code not use in iOS 7.0/ Xcode 5.0 ?
**
if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];

        //            NSData *webData = [NSData dataWithContentsOfURL:videoURL];

        MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
        UIImage  *thumbnail;
        thumbnail = [player thumbnailImageAtTime:1.0 timeOption:MPMovieTimeOptionExact];

        //            NSLog(@"video : %@",webData);
        //            NSData *video = [[NSString alloc] initWithContentsOfURL:videoURL];
        //            [webData writeToFile:[self findUniqueMoviePath] atomically:YES];

        thumbnail = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        editButton.imageView.image=thumbnail;
        NSLog(@"%@",thumbnail);

        UIWebView *webViewAns = (UIWebView *)[scroll viewWithTag:20000+scroll_position];
        face1String = [webViewAns stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.documentElement.innerHTML"]];

        separate_array = [face1String componentsSeparatedByString:@""];

        NSString *imagepath_str = [[NSString alloc]init];

        imagepath_str = [NSString stringWithFormat:@"",thumbnail];

        image_str = [[NSString alloc]init];

        image_str = [NSString stringWithFormat:@"%@%@%@",[separate_array objectAtIndex:0],imagepath_str,[separate_array objectAtIndex:1]];

        [webViewAns loadHTMLString:[image_str description] baseURL:nil];

        face1String = image_str;

        [self dismissViewControllerAnimated:YES completion:nil];
        [self.popoverController dismissPopoverAnimated:YES];

    }
}

Replay :)


text:
Q: Are 'senders' required to have a paypal account when using Adaptive payments>Chained Payments? Are 'senders' required to have or set up a PayPal account when using Adaptive payments>Chained Payments? It's not a problem for the receivers but for the senders, a lot of people just want to use their credit card to pay and don't wish to set up a PalPal account just to check out.

A: Sender is not required to have a PayPal account when making Adaptive Chained Payments. Below is a screen shot of my recent test on their sandbox site for Adaptive payments -> Chained Payments .


text:
Q: Count the total pairs of numbers that have a difference of K Here is how I am solving this problem :
void solve ( int *input, int N, int K, int& count) {
    std::sort ( input, input + N);
    for ( int i = 0; i < N; i++) {
        int find_me  = input[i] + K;
        if (std::binary_search (input + i + 1, input + N, find_me ))
            count++;
        else
            break;
    }
}

input has integer values which is guaranteed to be unique and > 0 , N is the number of elements.
Does anybody see anything wrong with this code, I have submitted this to one programming puzzle contest and bot is saying couple of test cases are failed, I want to know what possible test case this code can fail.

A: I'm not sure if I've understood the codes correctly, but it seems to me that if there does not exist a number with value input[0] + K in the array input, your loop will terminate with that break. I think that's where the problem lies.

A: There are two problems with your code. First, the else break; portion of the if needs to go away to avoid prematurely exiting the for loop. Second, you run one past the end of the loop on the last iteration. Your loop termination condition should be i < N - 1.
However since the items are sorted it seems likely that there's a linear complexity algorithm you could use, similar to a set intersection algorithm where you walk two indexes independently, doing the checks.


text:
Q: Is the number of sequences with equal 0's and 1's small? I think that is n choose n/2. Though when I try to get a feel of what that number should be I get a much larger number than I expect:
i.e. we have
$$ n C \frac{n}{2} = \frac{n!}{\frac{n}{2}! \frac{n}{2}! }$$
using Stirling's?
Recall:
$$n! \sim \sqrt{2 \pi n} \left( \frac{n}{e} \right) ^n$$
What I tried:
$$ \frac{n!}{\frac{n}{2}! \frac{n}{2}! }
\sim
\frac{\sqrt{2 \pi n} \left( \frac{n}{e} \right) ^n}{ \sqrt{2 \pi \frac{n}{2}} \left( \frac{\frac{n}{2}}{e} \right) ^\frac{n}{2}  \sqrt{2 \pi \frac{n}{2}} \left( \frac{\frac{n}{2}}{e} \right) ^\frac{n}{2}}
\sim
\frac{\sqrt{2 \pi n} \left( \frac{n}{e} \right) ^n}{ \sqrt{2 \pi \frac{n}{2} 2 \pi \frac{n}{2} }  \frac{\frac{n}{2} }{e  ^\frac{n}{2}} ^\frac{n}{2}  \frac{\frac{n}{2} }{e  ^\frac{n}{2}}  ^\frac{n}{2}}
\sim
\frac{\sqrt{2 \pi n} \frac{n^n}{e^n} }{ \sqrt{ \pi^2 n^2 }  \frac{n^{n}}{e^n} \frac{1}{2^{n}}} \sim \sqrt{2} \frac{2^n}{\sqrt{\pi} \sqrt{n}}
$$
which I feel has to be wrong.
Why do I feel that? Because n choose n/2 is the number of sequences that have half zero and the other half 1. This number should be much less than the total number of binary sequences (because it you have half 1's and half 0's then to change it to a sequence that is unbalanced should be easy...just change any bit! which means intuitively that half 1's and half zeros should be really small).
Basically, shouldn't most sequences not be balanced? i.e isn't the number of balanced sequences small?
Say the number of not balanced sequences should be
$$2^n - nC\frac{n}{2}$$
shouldn't the above quantity be super large, like $2^n$?
How do I show that the majority of the sequences are unbalanced?

A: Your derivation is correct, and does tell you that most sequences are unbalanced.  The expression $\sqrt{2} \frac{2^n}{\sqrt{\pi} \sqrt{n}}$ is much smaller than $2^n$ when $n$ is large, by a factor of about $\sqrt{n}$.  For instance, if $n=1000000$, your estimate says that only about $1/1000$ of all the binary sequences are balanced.  The number of unbalanced sequences is about $$2^n-\sqrt{2} \frac{2^n}{\sqrt{\pi} \sqrt{n}}=2^n\left(1-\frac{\sqrt{2}}{\sqrt{\pi}\sqrt{n}}\right),$$
and when $n$ is large, the second factor on the right-hand side is almost $1$.