text:
Q: it is possible to rewrite this promise as a async function? I wrote this promise, where I fetch and .json with objects that contains personal datas
const cpf_person = new Map()

fetch('pessoas.json')
.then(response => response.json())
.then(response =>{
     for (let object of response) {
        const {cpf} = object
        console.log(cpf)
        cpf_person

 .set(cpf, object)
     } return cpf_person

})
.then(map => console.log(map, map.size, map.get('103.439.122-44')))

on the second .then use a for loop to create a new Map from those objects, then return to the third one to manipulate it.
I've be trying to repeat this process using async function, but I'm getting problems on the second .then where I use the for loop, I achieved this so far:
const cpf_person2 = new Map()

async function tal(){
    const fet =     await fetch('pessoas.json')
    const json =    await fet.json()
    const loop =    await json => { (json => { //I'm not passing through this stage
        for (let object of response) {
            const {cpf} = object
            console.log(cpf)
            cpf_person.set(cpf, object)
        }
    })
}
}

I know I can just write the for loop on the function without using it as a promise, but is possible?

A: I think you are stuck in a ".then" -mindset.
Think of your function (tal) as executing line by line.
When there is an await, the next line won't execute until the await line finished its job.
To fix, move the loop out of the function and delete the function line entirely and change the loop to for (let object of json) { ....
async function tal(){
    const fet = await fetch('pessoas.json')
    const json = await fet.json()
    for (let object of json) {
        const {cpf} = object
        console.log(cpf)
        cpf_person.set(cpf, object)
    }
}


text:
Q: What is the use of the chain rule? While studying calculus at home, I reached derivatives, and a book mentioned the chain rule. The book didn't go into much detail, and the internet searches gave me little information, so I was hoping that someone could enlighten me on this fundamental principle of calculus.

A: Mathematicians often like to compose functions. That is
$(f\circ g)(x) = f(g(x))$,
as you will often see it.
As a more illustrative example of composition we will define two functions:
$f:\mathbb{R} \to \mathbb{R}:x \mapsto \frac{1}{x}$ and $g:\mathbb{R}\to\mathbb{R}:x\mapsto x+1$.
Using these functions, we get:
$(f\circ g)(x) = f(g(x)) = f(x+1) = \frac{1}{x+1}$,
a function that probably isn't too foreign to you.
Using composition, we can [de]construct many functions. Normally, you might use the quotient rule on the above example when deriving, however it is equally valid to treat it like a composition of functions, then use the chain rule to derive it.
The chain rule is defined as:
$(f \circ g)'(x) = (f' \circ g)(x) \cdot g'(x) = f'(g(x)) \cdot g'(x)$.
Often you will find one rule easier to use than the other, and you slowly learn which would be faster as you do more exercises.

A: Information about the chain rule can be found here, it's basically the way of differentiating composite functions, and hence is massively useful in all of differential calculus where most functions are composites of composites of ... etc... of functions, so the chain rule is useful. It basically states that the derivative of a function $$h(x) = f(g(x))$$ is given by $$h'(x) = f'(g(x)) \cdot g'(x)$$ where the notation $f'(x)$ refers to the derivative of the function $f(x)$ with respect to $x$.

A: The other answers focus on what the chain rule is and on how mathematicians view it. But you've asked what it's good for. The answer lies in the applications of calculus, both in the word problems you find in textbooks and in physics and other disciplines that use calculus. I searched for "chain rule application problems" and found a few sites that might help you.
Here's part of an example from http://www.ugrad.math.ubc.ca/coursedoc/math100/notes/derivative/chainap.html

Example 2: Chemistry and The Ideal Gas Law
The properties of gases have been studied for centuries, and it has
  been found that many gases satisfy an approximate relationship called
  the Ideal Gas Law which states that
$$PV = n R T .$$
Suppose that a 1 litre size gas cylinder containing 100 moles of
  oxygen gas has been carelessly placed near a radiator, so that its
  temperature rises at the rate of 2 degrees per minute. At what rate
  will the pressure build up in the cylinder?

You will find some nice examples here, too:
http://www.ugrad.math.ubc.ca/coursedoc/math102/2011/keshet.notes/Chapter7.pdf

A: Okay, so you (hopefully) know how to take the derivative of something like $\tan x$, or
$$\frac{d}{dx}(\tan x)=\sec^2x$$
well what if I gave you something like
$$\frac{d}{dx}(\tan(x^2))$$
Now we have a separate function embedded within our first function. The chain rule says do the derivative like normal (just treat the $x^2$ like an $x$), then multiply by the derivative of the inside function. So we get
$$\frac{d}{dx}(\tan(x^2))=\sec^2(x^2)\cdot 2x=2x\sec^2(x^2)$$
Another way people write this a lot of times is
$$\frac{dy}{dx}=\frac{dy}{du}\cdot\frac{du}{dx}$$
where $u$ is the "embedded" function. So, in our example we would have $u=x^2$, so $y=\tan u$. Then we would get
$$\frac{dy}{dx}=(\sec^2(u))(2x)=2x\sec^2(x^2)$$
So it's consistent with how we did it before, just a little different way of looking at it

A: It is sometimes easier to find functions with respect to something that is not what you use to derivate.
Say for example you want to measure the acceleration $a$ of a race car on a race track.
Say you can measure the speed $v$ of the car at known positions $x$ on the track.
The result of your measurements would be discrete values for $v$ depending at the positions $x$ that you measured it at.
Let's say you somehow create a function out of those discrete values. (for example by fitting a curve to the data points). You now have a function of the speed $v$ with respect to $x$, like so: $v(x)$.
Remember the goal: the acceleration $a$ of the car is what you want to know. this is defined as
$$a=\frac{dv}{dt}$$
What is the derivative of $v$ with respect to $t$? $v$ does not depend on $t$. Is $v$ a constant value in respect to $t$? Certainly not. The race car did have a different speed at different times. What's also certain is that the race car changed its position over time, which means that its Position is a function of time: $x(t)$
And this is the somewhat "indirect" way that $v$ changes with respect to $t$, because $x$ does. If you now expand the original fraction with $dx$, you get:
$$a=\frac{dv}{dt}=\frac{dv}{dt}\cdot\frac{dx}{dx}=\frac{dv}{dx}\cdot\frac{dx}{dt}$$
Which is the formula of the chain rule.

A: Ideas form the chain rule are used throughout, deeper integration is fundamentally based on it. But the main use of it is to be able to differentiate a function within a function (within a function...). It is also easy to identify the differential of an expression from the chain rule, as the format is eye catching. This comes up in integration by parts in a case where you might have to spot what something integrates to.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Download and Convert You tube Videos With Video Download Studio? I have video download studio and I want to download some videos from you tube but there appears to be some problem when I I do it. How should I do it properly?

A: You can't "properly" download videos from YouTube, you have to agree not to in order to use YouTube:

you agree not to access User Videos (as defined below) for any reason other than your personal, non-commercial use solely as intended through and permitted by the normal functionality of the Services, and solely for Streaming. "Streaming" means a contemporaneous digital transmission of the material by YouTube via the Internet to a user operated Internet enabled device in such a manner that the data is intended for real-time viewing and not intended to be downloaded (either permanently or temporarily), copied, stored, or redistributed by the user.

— http://www.youtube.com/t/terms


text:
Q: GetLogicalDriveStrings, why list of strings Do I understand correctly that this function returns drive letters?
If yes, then why does GetLogicalDriveStrings gives series of null-terminated strings and not series of chars?

A: Because it returns strings that can be used as input to functions like GetDriveType which require the input to be in the form "c:" not just 'c'.


text:
Q: How to create a custom date field with Ethiopic calendar in Python/Django I am building a Django application in which I need to store date information, but I'm working with Ethiopian data and the default date time/calendar in Python/Django is Gregorian.
Is there a way I can create custom date time object that matches the Ethiopic calendar, and configure it as a default date time object?

A: I know almost nothing about the ethiopic calendar, but maybe I can help with some starting points and ideas.
You should probably use the gregorian based datetime objects internally and convert from and to the ethiopic calendar before displaying or after receiving input from the user. This is assuming all dates in the ethiopic calendar can be represented in the gregorian and vice versa.
You can maybe use a package from PyPI like this: ethiopian-date-converter
If you really need to use ethiopic dates internally in your code, you would probably need to roll your own datetime-like object, ModelField, FormField etc. Storing ethiopic dates in a database is probably also an adventurous task. It might not be worth it, depending on the task you are trying to solve.
If you can get away with gregorian dates internally (in the database, in your algorithms etc.), you might only need to build a template filter for output and a custom Field for input.
I hope this will get you started.


text:
Q: Custom Fonts with SAPUI5 Theme Designer I have been developing a custom theme for using in HANA cloud platform Portal. I need to use custom fonts on my site, so I have deployed the fonts as an HTML application in HCP.
How can I use the fonts uploaded in this application in UI theme designer so that custom font-family is applied to all the apps using the custom theme?
I could not find a CSS parameter in the expert's tab related to fonts.
Thanks.

A: You'll have to customise the font using the CSS tab, e.g.:

A: You might can load a custom font in the head of you index file, and then apply custom CSS to your project in order to have full control. You can load an additional custom CSS file from your index page, but I think you can also add it to your theme. I attached a code sample:

* {
    font-family: Montserrat, sans-serif !important;
}
<link href="http://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css">

and also load a custom CSS file which applies your font to you desired


text:
Q: Continuity of the complex natural log I want to understand the continuity of the principal branch of $\log(z)$. Since $\log|z|$ is already continuous, it is sufficient to show that $\text{Arg} \colon \mathbb{C}\setminus \{z \in \mathbb{R}:z \le 0\} \to \mathbb{R}$ defined by $z \mapsto \text{Arg}(z)$ is continuous as well. The idea my professor mentioned was to pick a convergent sequence $\{z_n\}$ and show that its image under $\text{Arg}$ is still convergent. Her argument goes as follows:

Fix $\epsilon>0$ and let $z_0$ be the limit point of $\{z_n\}$. Since the set $G:= \mathbb{C}\setminus \{z \in \mathbb{R}:z \le 0\}$ is open we can find a $ 0 < \delta < \epsilon$ such that
  $$
\Sigma_\delta(z_0) := \{z \in G:|\text{Arg}(z) - \text{Arg}(z_0)| < \delta \} \subseteq G.
$$
  Now since $z_n \to z_0$ we can find a $N$ so that if $n \ge N$ we have $z_n \in \Sigma_\delta(z_0)$. This implies that for $n\ge N$ we have $|\text{Arg}(z_n) - \text{Arg}(z_0)| < \delta < \epsilon $, and $\text{Arg}(\cdot)$ preserves convergent sequences.

However, it seems to me that the line "Now since $z_n \to z_0$ we can find a $N$ so that if $n \ge N$ we have $z_n \in \Sigma_\delta(z_0)$." is precicely what we are trying to prove. What am I missing here?
Additionally, what is a good way to think about convergent sequences/continuous functions in terms of polar coordinates since the representation in this way is not unique as it is in Cartesian coordinates.


text:
Q: Could not connect with Authentication=ActiveDirectoryPassword. could not find driver I have a SQL Server running the OS Windows Server 2012 R2. It is running Microsoft SQL Server 2012.
On another computer, I am running an IIS web server, and I have installed PHP version 7.2.13, and Microsoft Driver 5.3 for PHP for SQL Server.
I am trying to connect to a database on the SQL Server via PHP:
<?php

// Now connect to an Azure SQL database by setting Authentication to ActiveDirectoryPassword
$azureServer = "vgissql";
$azureDatabase = "dbo.pctProjectTracking";
$azureUsername = "myuid";
$azurePassword = "mypassword";
$connectionInfo = "Database = $azureDatabase; Authentication = ActiveDirectoryPassword;";

try
{
    $conn = new PDO( "sqlsrv:server = $azureServer ; $connectionInfo", $azureUsername, $azurePassword );
    echo "Connected successfully with Authentication=ActiveDirectoryPassword.\n";
    $conn = null;
}
catch( PDOException $e )
{
    echo "Could not connect with Authentication=ActiveDirectoryPassword.\n";
    print_r( $e->getMessage() );
    echo "\n";
}

?>

If I try opening this php file in a browser, I get:
Could not connect with Authentication=ActiveDirectoryPassword. could not find driver
Any ideas on what could be wrong here?


text:
Q: How to apply tranition to a left align element? My project has a panel aligned to right:
<s:BorderContainer id="panelRight" right="0" top="60" bottom="30" width="333">

When I execute that code
move.target = panelRight;
move.xBy = +panelRight.width;
move.play();

Nothing happens: this is because the panelRighti saligned to right !
How can I solve that ?

A: You could use Animate class instead of Move and add effect not for x but right property. It will be looks like:
var moveEffect:Animate = new Animate();
moveEffect.target = panelRight;
moveEffect.motionPaths = Vector.<MotionPath>([new SimpleMotionPath("right", null, null, -panelRight.width)]);
moveEffect.play();

The effect will be looks same.
Animate class


text:
Q: If $A,B$ are $n\times n$ matrices and we have that $AB= I_n$, why do we need to show that $BA=I_n$ as well to show that $A$ is an inverse of $B$? If $A,B$ are $n\times n$ matrices and we have that $AB= I_n$, why do we need to show that $BA=I_n$ as well to show that $A$ is an inverse of $B$?

A: No, we do not need to show this, since in the group $GL_n(K)$ it follows that a left inverse is also a right inverse.
Reference: For square matrix, right or left inverse is equivalent to inverse.

A: At first glance, it might seem necessary to show this because it is a matter of definition.
Moreover, consider the real vector space $E$ of all $C^\infty$ maps $f:\mathbb{R}\to\mathbb{R}$, the ring $A$ of all linear maps $T:E\to E$ and the two following elements of $A$ :
$\phi:E\to E,f\mapsto f'$
and
$\psi:E\to E,f\mapsto[x\mapsto\int_0^xf(t)\,dt]$
It can be seen that $\phi$ has a right inverse but no left inverse and $\psi$ has a left inverse but no right inverse.
In fact : $\phi\circ\psi=id_E$ but neither $\phi$ nor $\psi$ is a bijection.

Now, if $u,v:\mathbb{R}^n\to\mathbb{R}^n$ are linear maps such that $u\circ v=id_{\mathbb{R}^n}$ then $u$ is surjective and $v$ is injective, hence both are bijective (because both are linear and $\mathbb{R}^n$ is finite dimensional.
It is now clear that : $v\circ u=u^{-1}\circ\left(u\circ v\right)\circ u=u^{-1}\circ u=id_{\mathbb{R}^n}$.
Hence the proposition : if $A,B$ are square $n\times n$ matrices such that $AB=I_n$ then $BA=I_n$.

A: Here is an easy way to prove that $AB=I_n$ implies $BA=I_n$ without appealing to any advanced concepts or algebraic structures.
Recall that a matrix is invertible if and only if its determinant is different from $0$.
Now, taking the determinant of both sides we have that $\det(AB)=1$. Since the matrices are square, this means that $\det A \cdot \det B=1$. This implies that $\det A, \det B \neq 0$, so $A$ and $B$ are invertible.
Left multiply the initial relation by $A^{-1}$ to get that $B=A^{-1}$. Now since $A^{-1}\cdot A=I_n$, we get that $BA=I_n$.

A: This answer addresses the author's original question without appealing to (basic facts of) groups.
As to how to prove that the right-inverse implies the left-inverse, there are many answers of that here.
As to the why this must be proven, which is at the crux of the original question, it is clear from the definition of matrix multiplication and working with examples that the operation is not commutative. Thus, if $AB = I_n$, then there is no guarantee that $BA = I_n$.


text:
Q: C++ Splitting array of strings into subgroups I have an array of string (which length is always different) and I need to split this into groups (which also number is different from time to time);
int main()
{
    // Array that I want to split;
    void Names = { Sara, Kaya, Hya, Jenny, Mary, Tiffany, Stefan };

    int groupNumber = 3;

    //Now I would like to split the names into 3 different groups as evenly as
    //possibile so that I can print
    // Group 1 : Sara,Hya,Jenny;
    //Group 2 : Kaya,Mary;
    //Group 3 : Tiffany, Stefan;
}

A: This is a sample code that splits the array into multiple groups. I hope it helps to get started.
int groupNumber = 3;
std::vector<std::string> names = { "Sara", "Kaya", "Hya", "Jenny", "Mary", "Tiffany", "Stefan" };
std::vector<std::vector<std::string>> groups;
groups.resize(groupNumber);
for (int i= 0; i < names.size(); ++i)
{
    groups.at(i % groupNumber).push_back(names.at(i));
}

You can use this loop to print out the groups.
for (auto group : groups)
{
    for (auto name : group)
    {
        std::cout  << name << " , ";
    }
    std::cout << std::endl;
}

Output

A: #include <iostream>
#include <array>
#include <vector>

using std::cout;

template <typename T>
std::ostream& operator <<(std::ostream& stream, const std::vector<T>& vec) {
    stream << "{";
    for (auto it = vec.begin(); it != vec.end(); ++it) {
        if (it != vec.begin()) stream << ", ";
        stream << *it;
    }
    stream << "}";
    return stream;
}

template <size_t GroupN, typename T> // T can be deduced
std::array<std::vector<T>, GroupN> split_vector(std::vector<T> vec_to_split) {
    std::array<std::vector<T>, GroupN> result;
    size_t remaining = vec_to_split.size();
    size_t optimal_size;

    for (size_t i = 0; i < GroupN; ++i) {
        optimal_size = (remaining + GroupN - i - 1) / (GroupN - i);
        // ceiling division, 7/3->3, 4/2->2, 2/1->2
        result[i].reserve(optimal_size);
        for (size_t j = vec_to_split.size() - remaining; j < vec_to_split.size() - remaining + optimal_size; ++j)
            result[i].push_back(vec_to_split[j]);
        remaining -= optimal_size; // 7-3=4, 4-2=2, 2-2=0
    }

    return result;
}

int main() {
    std::vector<int> v {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
    auto [v1, v2, v3] = split_vector<3>(v); // Structured binding, C++17 or above only
    cout << v1 << ", " << v2 << ", " << v3 << "\n";
    return 0;
}

The top function is just a pretty-printer for std::vector since they're not printable be default. I used int not std::string, but it doesn't matter,
The main function returns an array so its size is given at compile-time as a template argument.


text:
Q: Code logic should not allow query to go through but it still does PHP SQL I receive a $_GET['id'] from the URL - I want it only numeric if not go to a 404 page. I believe I should work - but I have new relic that tells me otherwise and im stump. (note i'm working with legacy code so I apologize for the mysql_query commands and i'm aware I should be using PDO instead)
    if(isset($_GET['item']) && is_numeric($_GET['item'])) {
        $id = $_GET['item'];
    }
    else {
        $timestamp = date("Y-m-d");
        $get_item = json_encode($_GET['item']);
        $err = date("Y-m-d").": Get Item is wrong:".$get_item."\n";
        $file = "/logs/error_log_".$timestamp.".log";
        file_put_contents($file, $err, FILE_APPEND | LOCK_EX);
        header( 'Location: http://www.example.com/404.php' ) ;
    }

    $iquery = "SELECT * FROM products WHERE products_id = $id";
    $iresult = mysql_query($iquery);

    if ($iresult == false) {
        $timestamp = date("Y-m-d");
        $err = date("Y-m-d").": SQL:".$iquery."\n";
        $file = "logs/error_log_".$timestamp.".log";
        file_put_contents($file, $err, FILE_APPEND | LOCK_EX);
        header( 'Location: http://www.examples.com/404.php' ) ;
    }
    $iline = mysql_fetch_array($iresult, MYSQL_ASSOC);

according to my log the query itself receive nothign so $id receives nothing and my log file fires with nothing and new relic fires and tells me that my query is failing.
I don't get it.

A: It seems like you expect the script to stop after you call header(), but there's nothing in your code that would cause that to happen. header() just adds an HTTP header to the response; it doesn't end your script. If you only want the query to be executed when $_GET['id'] is numeric then you should do the query inside the first if block, not after the else block.


text:
Q: Understanding relative compactness of a sequence of functions I'm trying to understand the following definition of pre-compactness (from Wikipedia):

A relatively compact subspace (or relatively compact subset, or
  precompact) $Y$ of a topological space $X$ is a subset whose closure is
  compact. Since closed subsets of a compact space are compact, every
  subset of a compact space is relatively compact. In the case of a
  metric topology, or more generally when sequences may be used to test
  for compactness, the criterion for relative compactness becomes that
  any sequence in $Y$ has a subsequence convergent in $X$.

I'm thinking of $X$ as a functional space, e.g., the space of all right continuous functions with left limits and of $Y$ as a sequence of functions in $X$ indexed by $n$, say $\{f^{n}(t)\}$.
In this case, according to the definition, the criterion for relative compactness is that ${\it any}$ sequence in $Y$ has a convergent subsequence. But what does that mean in the above case where $X$ itself is a sequence of functions? Is it simply that the sequence  $\{f^{n}(t)\}$ must have a convergent subsequence? Could you give an example where the ${\it any}$ part makes sense?

A: As the space of all right continuous functions with left limits, I believe $X$ is not necessarily a metric space, since it is not generally bounded. Therefore, the equivalence between sequential compactness and compactness does not necessarily hold for $Y$.
If you add the condition that the functions in $X$ be bounded, then then space can be expressed as a metric space, equipped with the $sup$ norm
By construction, subset $Y$ itself is a sequence of functions where $Y$ is defined as $\{f^{n}(t)\}$ and so you are correct in that $\{f^{n}(t)\}$ must have a convergent subsequence.
Note $\{f^{n}(t)\}$ itself need not converge as it is the closure of $Y$ that is compact.


text:
Q: Illegal operand of type void when defining UnaryPredicate I'm trying to use std::partition with a custom UnaryPredicate.
void Rank(vector< pair<double, string> >& pairs) const
{
    partition(pairs.begin(), pairs.end(), [](const pair<double, string>& a) { isnan(a.first); });
}

When doing this I get the following errors from Visual Studio 2015:

*

*Error    C2297   '&&': illegal, right operand has type
'void'   Imaging c:\program files (x86)\microsoft visual studio
14.0\vc\include\algorithm    1839

*Error    C2171   '!': illegal on operands of type 'void' Imaging c:\program files (x86)\microsoft visual studio
14.0\vc\include\algorithm    1844

*Error    C2297   '&&': illegal, right operand has type 'void'    Imaging c:\program files (x86)\microsoft
visual studio 14.0\vc\include\algorithm  1844

The following however has not issue:
bool pairIsNan(const pair<double, string>& a)
{
    return isnan(a.first);
}
partition(pairs.begin(), pairs.end(), pairIsNan);

Can anyone clarify what is wrong with the first set of code and how to resolve it?

A: Your lambda doesn't return anything, it's corresponding function is really something like:
void pairIsNan(const pair<double, string>& a)
{
    // Discard the result of the isnan function
    (void) isnan(a.first);
}

To make it work you need to return the result of the isnan function call in the lambda:
partition(pairs.begin(), pairs.end(), [](const pair<double, string>& a)
{
    // Return the result
    return isnan(a.first);
});


text:
Q: How do I ensure that DOM operations in a single tick happen at once? DOM operations are synchronous but their rendering to the screen is often clubbed together. How do I ensure that they are always processed as a single transaction in terms of rendering on the screen?
I tried requestAnimationScreen and inserted an alert() to see the state in-between. It works as a single transaction for Chrome and Safari but not Firefox. Moreover, is there any spec that defines this behaviour or is this completely browser dependent?
FWIW, if I remove alert() it works as a single transaction even on Firefox.
Here is the code snippet:

function f(showAlert) {
  const boxes = document.querySelectorAll('.box');
  const firstBox = boxes[0];
  const secondBox = boxes[1];

  firstBox.remove();

  if (showAlert) {
    alert("Check");
  }

  const div = document.createElement('div');
  div.classList.add('box');
  div.classList.add('new');

  secondBox.parentElement.insertBefore(div, secondBox);
}

document.querySelector('.btn1').onclick = () => {
  requestAnimationFrame(() => {
    f(true);
  });
};

document.querySelector('.btn2').onclick = () => {
  requestAnimationFrame(() => {
    f(false);
  });
};
.box {
  height: 500px;
  width: 500px;
  background-color: blue;
}

.box.default {
  background-color: pink;
}

.box.new {
  background-color: green;
}

.btn-bar {
  position: fixed;
  right: 0;
  top:0;
}

Box 1

Box 2

Box 3

Box 4

Box 5

  <button class="btn1">Alert</button>
  <button class="btn2"> No alert</button>


text:
Q: Anonymous types syntax I know we can use such syntax
var r = new MyType { name = "dd"}

Is it possible to have such syntax in any simpler way
MyType myType = GetMyType("some method returns instance of mytype"){
       name="myname",
       otherProp = otherPro,
       ExecuteMyTypeMethod()
    };

A: Note that what you've shown are not anonymous types, which are like this:
var r = new { name = "dd" }; // Note the lack of a type name

This is object initializer syntax - and no, it only works with constructors. I've occasionally found that a pain too, but that's the way it is.
EDIT: A comment suggested using extension methods. You could do this:
public static T With<T>(this T item, Action<T> action) where T : class
{
    action(item);
    return item;
}

at which point you could write:
MyType myType = GetMyType("some method returns instance of mytype").With(t => {
   t.name="myname";
   t.otherProp = otherPro;
   t.ExecuteMyTypeMethod();
});

The only benefit of this is that you can still perform the initialization in a single experssion. Usually I'd prefer to just use separate statements.


text:
Q: Push forward and pullback in products I am reading this Questions about Serre duality, and there is one part in the answer that I'd like to know how it works. But after many tries I didn't get anywhere. So here is the problem.
Let $X$ and $B$ be algebraic varieties over an algebraically closed field, $\pi_1$ and $\pi_2$ be the projections from $X\times B$ onto $X$ and $B$, respectively.  Then it was claimed that $R^q\pi_{2,*} \pi_1^* \Omega_X^p \cong H^q(X, \Omega^p_X)\otimes \mathcal{O}_B$.
I am guessing it works for any (quasi)coherent sheaf on $X$.
Basically, I have two tools available, either Proposition III8.1 of Hartsshorne or going through the definition of the derived functors.
Thank you.

A: Using flat base-change (Prop. III.9.3 of Hartshorne), one sees that $$R^1\pi_{2 *} \pi_1^*\Omega_X^p = \pi_1^* H^q(X,\Omega^p_X) = H^q(X,\Omega^p_X)\otimes \mathcal O_B.$$


text:
Q: function using .reduce() returning array and undefined value I wrote out this function that is supposed to take in an array of book objects that are formatted like this:
{
    id: "5f447132c30e8abe6c988a8b",
    title: "veniam voluptate magna ipsum officia",
    genre: "Historical Fiction",
    authorId: 37,
    borrows: [
      {
        id: "5f446f2ea6b68cf6f85f6e28",
        returned: true,
      },
      {
        id: "5f446f2ead0070f44676f2f6",
        returned: true,
      },
    ],
  }

and return an array that looks like this:
[
  { name: 'Science', count: 3 },
  { name: 'Classics', count: 2 },
  { name: 'Historical Fiction', count: 1 },
  { name: 'Travel', count: 1 },
  { name: 'Young Adult', count: 1 }
]

so i went and made this:
function findMostCommonGenres(books) {
  const mostCommonGenres = books.reduce((genres, book) => {
    const genreObj = genres.find(currGenre => currGenre.name === book.genre);
    !genreObj ? genres.push({
      name: book.genre,
      count: 1,
    }) : genreObj.count++;
    return genres;
  }, []);
  mostCommonGenres.sort((genA, genB) => genB.count - genA.count);
  mostCommonGenres.splice(5);
  console.log(mostCommonGenres);
}

but for some reason it is returning the array AND an undefined value like this:
[
  { name: 'Science', count: 3 },
  { name: 'Classics', count: 2 },
  { name: 'Historical Fiction', count: 1 },
  { name: 'Travel', count: 1 },
  { name: 'Young Adult', count: 1 }
]
undefined

the array it returns is exactly what i need but im not sure where the undefined is coming from or how to get rid of it... any help would be appreciated thanks !!

A: You are not returning a value in your function findMostCommonGenres
If there is no return value then the function by default returns undefined and depending on where (Chrome devtools as an example) you run this piece of code you will see the return value printed (in this case undefined)
This is how I would write it to not see the undefined
function findMostCommonGenres(books) {
  const mostCommonGenres = books.reduce((genres, book) => {
    const genreObj = genres.find(currGenre => currGenre.name === book.genre);
    !genreObj ? genres.push({
      name: book.genre,
      count: 1,
    }) : genreObj.count++;
    return genres;
  }, []);
  mostCommonGenres.sort((genA, genB) => genB.count - genA.count);
  mostCommonGenres.splice(5);
  return mostCommonGenres;
}
console.log(findMostCommonGenres({<your books objects here>}))


text:
Q: How to publish a R markdown document to be hosted on a server as a website securely (private) for a company without R-studio connect? How to publish an R markdown document to be hosted on a server as a website securely (private) for a company without R-studio connect?
The link needs to be unchanged every time I re-run the R-markdown script to update the page. So that all employees can always use the same link to access the document. It also needs to be private and secure. Until now I have shared it through Microsoft Sharepoint but I have issues with the file link of the R markdown file changing from time to time, which means the new link has to be then re-distributed to all employees, which is a headache for everyone. Rpubs is good, but it is not private. R-studio connect is too expensive.
Anyone have a good idea?
Thanks in advance!


text:
Q: android-How to align actionbar menus and navigationDrawer these are my menus :
    <item
    android:id="@+id/search"
    android:icon="@drawable/ic_action_search"
    android:orderInCategory="2"
    android:title="@string/search"
    yourapp:showAsAction="always|withText"/>
<item
    android:id="@+id/newadd"
    android:icon="@drawable/ic_action_new"
    android:orderInCategory="3"
    android:title="@string/newadd"
    yourapp:showAsAction="always|withText"/>
<item
    android:id="@+id/sort"
    android:icon="@drawable/ic_action_sort_by_size"
    android:orderInCategory="1"
    yourapp:showAsAction="always"/>

when I run the app , all 3 of them are on the right side of actionbar , How can I make  them to move to left side of actionbar ?
also , I've an navigationDrawer , the icon is on the left side and I want to move it to the right side , How can I do so ?
I don't have any search on my actionbar .
How can I do so ?
thanks

A: You can use custom views for actionbar
ActionBar mActionBar = getActionBar();
View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);

actionbar xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="@dimen/activity_horizontal_margin" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:src="@drawable/ic_launcher" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/imageView1"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:src="@drawable/ic_launcher" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/imageView2"
        android:paddingLeft="12dp"
        android:paddingRight="12dp"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

set these methods for actionbar to make navigation drawer home icon visible
  getActionBar().setBackgroundDrawable(
                    new ColorDrawable(Color.parseColor("#56B1D8"))); //$NON-NLS-1$
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            ActionBar actionBar = getActionBar();
            getActionBar().setDisplayShowCustomEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
            // actionBar.setDisplayUseLogoEnabled(false);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayUseLogoEnabled(false);
            actionBar.setDisplayShowHomeEnabled(false);
            // getActionBar().setIcon(R.drawable.ic_navigation_drawer);
            // navigation icon on actionbar
            actionBar.setHomeButtonEnabled(true);
            actionBar.setIcon(null);

A: Assuming you're a right-to-left reader and trying to support such.  As for the app as a whole I believe it takes its cues from your device's selected language and locale.  Forcing right-to-left?  IDK how to do that, but to flip the actionbar as you've described I suspect that's what you'd be doing.
Aside from that just make sure you're using start and end vs. left and right for other alignments.  Both start and end will honor your devices settings where as left and right will not.


text:
Q: Why doesn't my conditional operator work? Why does this function return undefined instead of "old"?
function test(age) {
  12 < age ? "old" : "young";
}

test(15);

A: Your condition is fine. You need to return

function test(age) {
  return 12 < age ? "old" : "young";
}

console.log(test(15));

When you leave off a return statement, a function returns undefined by default.


text:
Q: Linux - compare system date with date in file and send e-mail to admin I have a tacacs+ server running on Debian 7.8. I used the apt-get install tacacs+ to get the tacacs+ installed, so nothing special here. I use the tacacs+ to authenticate users in a Cisco VPN machine.
My problem is that I couldn't find anything developed already for tacacs+ to send e-mails to users/server admins  before their password expire. There is a possibility to ask an user to change the password on logon, but if the account is already expired, it doesn't work.
Below is a sample of the account setup for an user in tac_plus.conf file.
user = example.user {
default service = permit
login = des some_crypted_pass_here
expires = "Sep 30 2016"
}

Could you please provide a script that can compare the date in "expires" with the system date, and if less than 14 days are left till system date = expires, to send an automated e-mail to a specific address ( e.g. admin@domain.local ) with a warning message ( e.g. "The tacacs+/Cisco VPN account for example.user will expire in X days" ) ?
Thank you all in advance.

A: @John1024 After following your advice, I came up with this:
#!/bin/bash

#location of temporary file to store the results
temp_file=/usr/local/src/temp_file_tacacs

#grep | cut | awk in the file /etc/tacacs+/tac_plus.conf and exporting resuts to temporary file
grep -e "user\|expires" /etc/tacacs+/tac_plus.conf | cut -d'=' -f 2 | tr -d { | tr -d \" | awk 'NR%2{printf $0":";next;}1' > $temp_file

#Getting current system date
date_current=$(date "+%s")

while IFS='' read -r line || [[ -n "$line" ]]; do
        #getting the user
        user=$(echo $line | awk '{print $1}')
        #getting the expiration date coresponding to the user
        date_expire=$(echo $line | awk -F: '{print $2}' | xargs)
        #converting the date in the same format as $date_current ( was retrieved earlier )
        date_converted=$(date -d "$date_expire" +"%s")
        #calculating the difference between the 2 dates
        date_diff=$(expr $date_converted - $date_current)

        #checking if result is < 14 days ( 1209600 seconds = 14 days )
        if [ $(expr $date_diff - 1209600) -gt 0 ]
        then
                #echo "$user - more than 14 days untill account will expire."  #left here for debugging purposes

                #ignoring there results and sending them to /dev/null ( just because I needed something in the while - then - else loop).
                echo "" > /dev/null
        else
                #echoing the results and sending them with with sendmail
                #If sendmail is not sending, check your /var/log/exim4/mailnlog.
                #I had to dpkg-reconfigure exim4-config and select "internet sites" option to be able to send e-mails to remote domains. Check
                # http://chepri.com/jake-strawn-fixed-mailing-to-remote-domains-not-supported-debian-5-lenny/ for more info about this

                #NOTE: For each result, you will get a  different e-mail. If too many accounts are about to expire, you may be blocked by the mail server for spamming!!

                echo -e "Hello Admins,\\n\\nThe $user Cisco VPN Account will expire in less than 14 days!" | /usr/bin/mail -s "The Cisco VPN Account for $user is about to expire" "email@domain.com"

        #END of the while loop
        fi

done < "$temp_file"

#deleting the temporary file
rm -rf $temp_file


text:
Q: DB connection not open i try this simple code with oledb connection but connection not open
    Imports System.Data.OleDb
Public Class WebForm2
    Inherits System.Web.UI.Page
    Protected Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click

        Dim connetionString As String
        Dim cnn As OleDbConnection
        connetionString = "Provider=SQLOLEDB;Data Source=((localdb)\v11.0);Initial Catalog=test;User Id=MyUsername; Password=MyPassword;Integrated Security=SSPI;"
        cnn = New OleDbConnection(connetionString)
        Try
           cnn.Open()
           MsgBox("Connection Open ! ")
           cnn.Close()
        Catch ex As Exception
           MsgBox("Can not open connection ! ")
        End Try

i also try this connection string
        connetionString = "Provider=SQLOLEDB;Data Source=test;Integrated Security=SSPI;"

same DB working well with sql client this connection string
    Imports System.Data.SqlClient

Public Class WebForm2

    Inherits System.Web.UI.Page
    Dim globalp As String
    Dim globals As String
    Private strConn As String = "Data Source=(localdb)\v11.0;Initial Catalog=test;Integrated Security=True"

extra code not mention for simplicity of question.
any thing extra required so please mention in comments.
also another problem is that some told me that this issue arise due to  SQL Server Authentication
i try to  change security authentication mode in visual studio built in sql server but i don't get properties popup menu or right below in vs corner section of properties, from Object Explorer,
New error occur in this code section  `Imports System.Data.OleDb
Public Class WebForm2
Inherits System.Web.UI.Page
Dim globalp As String
Dim globals As String
'Dim strConn As String = "Provider=Provider=Microsoft.Jet.OLEDB.4.0;Data Source=((localdb)\v11.0);Initial Catalog=test;Integrated Security=SSPI;"
Dim strConn As String = "Provider=SQLNCLI11.1;Integrated Security=SSPI;Initial Catalog=Test;Data Source=(localdb)\v11.0;"

Dim conn As OleDbConnection
' Dim strConn As String = "Provider=SQLOLEDB; Data Source=(localdb)\v11.0; Initial Catalog=test; Integrated Security=SSPI"
'  Private strConn As String = " Provider=Microsoft.Jet.OLEDB.4.0; Data Source=(localdb)\v11.0;Initial Catalog=test; User Id=MyUsername; Password=MyPassword"
' Private sqlCon As OleDbCommand
'Private strConn As OleDbCommand
'Provider=SQLOLEDB;

Protected Sub SubmitButton_Click(sender As Object, e As EventArgs) Handles SubmitButton.Click

    If Page.IsValid Then

        '  cnn = New OleDbConnection(strConn)
        '  cnn.Open()
        '  MsgBox("Connection Open ! ")
        '  cnn.Close()

        'sqlComm.CommandText = "sp1_userinformation"
        ' sqlComm.CommandType = CommandType.StoredProcedure

        ' sqlComm.Parameters.AddWithValue("UserName", name.Text)
        ' sqlComm.Parameters.AddWithValue("pass_word", fname.Text)
        ' sqlComm.Parameters.AddWithValue("CNIC", (cnic.Text))
        ' sqlComm.Parameters.AddWithValue("PartialAddress", (limitedtextarea.Text))
        ' sqlComm.Parameters.AddWithValue("Email", (email.Text))

        ' sqlCon.Open()
        'lcit.Text = sname
        ' sqlComm.ExecuteNonQuery()
        ' Dim sname As String = name.Text
        Dim sfname As String = fname.Text
        Dim scnic As String = cnic.Text
        Dim slimit As String = limitedtextarea.Text
        Dim semail As String = email.Text
        Dim stel As Int64 = Int64.Parse(tel.Text)
        Dim stel1 As Int64 = 0 & stel
        Dim query As String = String.Empty
        Dim sdob As Date = Date.Parse(dob.Text)

        query &= "INSERT INTO Userinfo (UserName, pass_word, CNIC, "
        query &= "                     PartialAddress, Email, Telephone,DateOfBirth)  "
        query &= "VALUES (@colName,@colID, @colPhone, @colBranch,@colCourse,@coldblFee,@dobv)"
        ' query &= "                     PartialAddress, Email)  "
        ' query &= "VALUES (@colName,@colID, @colPhone, @colBranch,@colCourse)"
        ' Using (sqlCon)
        'sqlCon = New SqlConnection(strConn)
        ' Dim sqlComm As New SqlCommand()

        '  sqlComm.Connection = sqlCon
        Using conn As New OleDbConnection(strConn)
            Using comm As New OleDbCommand()
                With comm
                    .Connection = conn
                    .CommandType = CommandType.Text
                    .CommandText = query
                    .Parameters.AddWithValue("@colName", username.Text)
                    .Parameters.AddWithValue("@colID", sfname)
                    .Parameters.AddWithValue("@colPhone", scnic)
                    .Parameters.AddWithValue("@colBranch", slimit)
                    .Parameters.AddWithValue("@colCourse", semail)
                    .Parameters.AddWithValue("@coldblFee", stel1)
                    .Parameters.AddWithValue("@dobv", sdob)

                End With
                '  Try
                conn.Open()
                comm.ExecuteNonQuery()
                '  Catch(ex as SqlException)
                'MessageBox.Show(ex.Message.ToString(), "Error Message")
                ' End Try
            End Using
        End Using

        ' End Using

    End If

End Sub`

Error is (Must declare the scalar variable "@colName".)
error location   comm.ExecuteNonQuery()

A: Try with SQL Server Native Client instead:
Provider=SQLNCLI11.1;Integrated Security=SSPI;Initial Catalog=Test;Data Source=(localdb)\v11.0;

EDIT:
Your code would be:
    Dim connetionString As String
    Dim cnn As OleDbConnection
    connetionString = "Provider=SQLNCLI11.1;Integrated Security=SSPI;Initial Catalog=Test;Data Source=(localdb)\v11.0;"
    cnn = New OleDbConnection(connetionString)
    Try
       cnn.Open()
       MsgBox("Connection Open ! ")
       cnn.Close()
    Catch ex As Exception
       MsgBox("Can not open connection ! ")
    End Try

Side Note: sql localdb does not work with SQL Server standard authentication, it only works with Windows integrated authentication.

A: OleDbCommand's use positional parameters and the question mark ? as the parameter marker, as oposed to SqlCommand's that use named parameters. So the sql statement should be:
INSERT INTO Userinfo
(
  UserName, pass_word, CNIC, PartialAddress,
  Email, Telephone, DateOfBirth
)
VALUES (?,?, ?, ?,?,?,?)

To add parameters to OleDbCommand.Parameters collection you don't need to change anything, you can use the parameter name you want as long as all parameter names are different. But rememeber, you need to add the parameters in order, because parameters are positional.


text:
Q: dependency injection in lumen I'm trying to understand dependency injection in lumen
I want to add userService
{
    protected $userService;
    public function __construct(UserService $userService, $config)
    {
        $this->userService = $userService;
    }

apply it here:
Console/Commands/Command2.php
    $server = app(Server::class, [$config]);

getting an error
In Container.php line 993:
  Unresolvable dependency resolving [Parameter #1 [  $config ]] in class App\SocketServer\Server

A: Dependencies with parameters can be configured in service providers. A service provider can be generated by running:
php artisan make:provider UserServiceProvider

Modifying the setup method in the UserServiceProvider.php file
    public function register()
    {
        $this->app->singleton(UserService::class, function ($app) {
            $config = ['debug' => true];
            return new UserService($config);
        });
    }

registering it in config/app.php:
'providers' => [
    // Other Service Providers

    App\Providers\UserServiceProvider::class,
],

And then Laravel will be able to inject the dependency:
    protected $userService;
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }


text:
Q: Dynamic select field, based on Datepicker chosen date issue in Woocommerce This post is a follow-up on another question:
Dynamic select field options based on selected day in Woocommerce checkout
So, with this answer help, I did manage to build a dynamic select field on the checkout page, which had changing options, based on the chosen date from a Datepicker. This solution works perfectly on the author test server…
However on my site, the code give some problems if the pickeded date is in May or October. Actually it seems that it doesn't work at all.
Those were and are the main requirements:
If Mon-Fri is chosen, pick-up ('delivery_time') every 30 minutes from 10:00 to 18:00
If Sat-Sun is chosen, pick-up ('delivery_time') every 30 minutes from 10:00 to 15:00
Only first Sundays in month is available. Other Sundays, no options available. (new requirement added in April and was working)
Can this have anything to do with my installation? I've tried to disable all plugins and deactivated localizer for Datepicker as well.
Following is the code for Dynamic select:
/**
 *
 * 2018-04-16
 * Picking date and time
 * Dynamic select based on selected day
 *
 */

add_action( 'wp_enqueue_scripts', 'enabling_date_picker' );
function enabling_date_picker() {

    // Only on front-end and checkout page
    if( is_admin() || ! is_checkout() ) return;

    // Load the datepicker jQuery-ui plugin script
    wp_enqueue_script( 'jquery-ui-datepicker' );
    wp_enqueue_style('jquery-ui', "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/smoothness/jquery-ui.css", '', '', false);
    }

// Datepicker field and select time field
add_action( 'woocommerce_before_order_notes', 'datepicker_custom_field' );
function datepicker_custom_field($checkout) {

    echo '
' . __('Hvornår vil du hente din ordre?') . '
';
    echo '
';

    woocommerce_form_field('delivery_date', array(
        'type' => 'text',
        'class'=> array('delivery-date-class form-row-first'),
        'label' => __('Vælg dato for afhentning'),
        'required' => true,
        //'placeholder' => __('Pick a date')
    ), $checkout->get_value('delivery_date') );

    $options = array('' => __('Afhentning kl.') );

    woocommerce_form_field( 'delivery_time', array(
        'type'          => 'select',
        'class'         => array('delivery-time-class form-row-last'),
        'label'         => __('Vælg tidspunkt for afhentning'),
        'required'      => true,
        'options'       => $options,
    ),  $checkout->get_value( 'delivery_time' ) );

        // Restricted options array
    $options1 = array(
        '10:00'   => __( '10:00' ),
        '10:30'   => __( '10:30' ),
        '11:00'   => __( '11:00' ),
        '11:30'   => __( '11:30' ),
        '12:00'   => __( '12:00' ),
        '12:30'   => __( '12:30' ),
        '13:00'   => __( '13:00' ),
        '13:30'   => __( '13:30' ),
        '14:00'   => __( '14:00' ),
        '14:30'   => __( '14:30' ),
        '15:00'   => __( '15:00' ),
    );

    // The other part of options array
    $options2 = array(
        '15:30'   => __( '15:30' ),
        '16:00'   => __( '16:00' ),
        '16:30'   => __( '16:30' ),
        '17:00'   => __( '17:00' ),
        '17:30'   => __( '17:30' ),
        '18:00'   => __( '18:00' ),

    );

        // The third part of options array
    $options3 = array(
        'Sundays_Closed' => __( 'Åbent første søndag i måneden'),
    );

    // Merging options arrays
    $options1 = array_merge($options, $options1); // Partial
    $options  = array_merge($options1,$options2); // Full

    echo '

';

    ?>

    <?php
}

A: I have made some little changes in your code:

*

*I Have moved the jQuery script in footer at the end (as it's the best way for jQuery).

*I have embed all your select options (all different arrays) in a separate utility function.

But I am not sure that it will work on your server configuration... I hope that this will solve the problem (that I don't have on my both test servers configs).
Your code revisited code:
add_action( 'wp_enqueue_scripts', 'enabling_date_picker' );
function enabling_date_picker() {

    // Only on front-end and checkout page
    if( is_admin() || ! is_checkout() ) return;

    // Load the datepicker jQuery-ui plugin script
    wp_enqueue_script( 'jquery-ui-datepicker' );
    wp_enqueue_style('jquery-ui', "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/smoothness/jquery-ui.css", '', '', false);
}

// Utility function (with all option arrays)
function select_options( $type = '' ){
    $options = array('' => __('Afhentning kl.') ); // Default start
    $options1 = array( // Restricted options array
        '10:00' => __( '10:00' ), '10:30' => __( '10:30' ), '11:00' => __( '11:00' ),
        '11:30' => __( '11:30' ), '12:00' => __( '12:00' ), '12:30' => __( '12:30' ),
        '13:00' => __( '13:00' ), '13:30' => __( '13:30' ), '14:00' => __( '14:00' ),
        '14:30' => __( '14:30' ), '15:00' => __( '15:00' ),
    );
    $options2 = array( // complementary options array
        '15:30' => __( '15:30' ), '16:00' => __( '16:00' ), '16:30' => __( '16:30' ),
        '17:00' => __( '17:00' ), '17:30' => __( '17:30' ),'18:00' => __( '18:00' ),
    );

    if( $type == 'partial' ){
        return array_merge($options, $options1); // Partial;
    } elseif ( $type == 'full' ){
        return array_merge($options,$options1,$options2); // Full
    } elseif ( $type == 'close' ){
        return array( 'Sundays_Closed' => __( 'Åbent første søndag i måneden') ); // Sundays closed
    } else {
        return $options; // Default (start)
    }
}

// Checkout Datepicker field and select time field
add_action( 'woocommerce_before_order_notes', 'datepicker_custom_field' );
function datepicker_custom_field($checkout) {

    echo '
' . __('Hvornår vil du hente din ordre?') . '
';
    echo '
';

    woocommerce_form_field('delivery_date', array(
        'type' => 'text',
        'class'=> array('delivery-date-class form-row-first'),
        'label' => __('Vælg dato for afhentning'),
        'required' => true,
        //'placeholder' => __('Pick a date')
    ), $checkout->get_value('delivery_date') );

    $options = select_options();

    woocommerce_form_field( 'delivery_time', array(
        'type'          => 'select',
        'class'         => array('delivery-time-class form-row-last'),
        'label'         => __('Vælg tidspunkt for afhentning'),
        'required'      => true,
        'options'       => $options,
    ),  $checkout->get_value( 'delivery_time' ) );

    echo '

';
}

add_action( 'wp_footer', 'date_picker_js_script' );
function date_picker_js_script() {
    // Only on checkout page
    if( ! is_checkout() ) return;
    ?>

    <?php
}

Code goes in function.php file of your active child theme (or active theme).
I have tested your code on 2 different test servers with WooCommerce 3.2.x and 3.3.x, and it works (tested that on different browsers and platforms).

This issue could be related to your theme, some plugin or other customizations made by you.


text:
Q: TinyMCE initialization should be inside dom ready event? They don't encapsulate initialization code in dom ready event In their official samples like this(click view source).
Is it safe to use it without dom ready event ? It controls dom ready event inside of initialization ?

A: This is no problem, because you can wrap inside a document ready block. That's what i do using tinymce. What they have on their page is just a simple example.

A: On Dom Ready is something that was --mostly-- developed for a certain browser that doesn't follow the "rules"  (in case you're wondering, it starts with an I and ends with an E)  Dom ready helps with other things as well, but bottom line is that you can most often get away without it, especially since IE6 is finally on its way out.
Try it out, test widely as you should be doing anyway, and if you're happy with the results, run with it.  This is one of the things that there's no set standard for.  Quite a bit of my company's legacy Javascript (including several instances of Tiny that are about to be deprecated) has been running in production without dom listeners for 2+ years without issue.


text:
Q: Add a "+" before each word in a string using jQuery I have created an array, "outData", using javascript, which looks like this:

I'm now trying to:

*

*loop through the outData array using jQuery each;

*if the checkbox called 'bmm' is ticked, split the strings in the outData array into individual words;

*add a "+" sign before each word;

*finally, join the words with the plus signs into new strings (with a space between each word) and push into a new array called "outPlus".

I'm stuck on how to correctly add the plus sign before each word split from the strings.
My code currently looks like this:
$(document).ready(function() {

    $("#multi").submit(function(e) {
        e.preventDefault();
        $("#output").empty();
        var array1 = [];
        var array2 = [];
        var array3 = [];
        $(".col1").each(function() {
            var word1 = $(this).val();
            if ( word1 !== "" ) {
                //word1 = word1.replace(/\s+/g, '');
                array1.push(word1);
            }
        });
        $(".col2").each(function() {
            var word2 = $(this).val();
            if ( word2 !== "" ) {
                //word2 = word2.replace(/\s+/g, '');
                array2.push(word2);
            }
        });
        $(".col3").each(function() {
            var word3 = $(this).val();
            if ( word3 !== "" ) {
                //word3 = word3.replace(/\s+/g, '');
                array3.push(word3);
            }
        });
        console.log(array1);
        console.log(array2);
        console.log(array3);
        var outData = [];
        var outPlus = [];
        $(array1).each(function( a, b ) {
            $(array2).each(function ( c, d ) {
                outData.push( b + " " + d );
                $(array3).each(function( e, f ) {
                    outData.push( b + " " + d + " " + f );
                });
            });
        });

        console.log(outData);

        if ( $("input[name='bmm']").prop("checked") == true ) {
            $(outData).each(function( g, h ) {
                outPlus.push( h.split(" ") );
            });

            console.log(outPlus);

            $(outPlus).each(function( i, j ) {
                    var output = j.replace(/(^|\s)/g, '$1+');
                    console.log(j);
                });
        }

        console.log(outPlus); //Uncaught TypeError: j.replace is not a function
    });

});

Current output:
Uncaught TypeError: j.replace is not a function

Desired output:
+used +car
+used +car +for +sale
+used +car +on +sale
etc...

Would be very grateful for help to produce the desired results. Many thanks in advance.

A: An alternate to @Rory would be to use /(\w+)/g regex.
Idea is to capture all words and replace them with +$1
Get new array

var outData = [
  'used car',
  'used car for sale',
  'used car on sale',
  'used cars'
];

var output = outData.map(function(text) {
  return text.replace(/(\w+)/g, '+$1');
});

console.log(output);

Replace original array

var outData = [
  'used car',
  'used car for sale',
  'used car on sale',
  'used cars'
];

outData.forEach(function(text, i, a) {
  a[i] = text.replace(/(\w+)/g, '+$1');
});

console.log(outData);

A: To fix this you can use a regular expression which follows any whitespace character, or the first character in the string, with a +. Try this:
$(outPlus).each(function(i, j ) {
  var output = j.replace(/(^|\s)/g, '$1+');
  console.log(j);
});

Here's a simplified example:

var outData = [
  'used car',
  'used car for sale',
  'used car on sale',
  'used cars'
];

outData = outData.map(function(text) {
  return text.replace(/(^|\s)/g, '$1+');
});

console.log(outData);

A: Need to use join() at-once after split() to concatenate your array with + sign like below (easy).

var outData = ['used car', 'used car for sale', 'used car on sale'];

var outPlus = [];

$(outData).each(function( g, h ) {
    outPlus.push("+"+h.split(" ").join(' +'));
});
console.log(outPlus);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: You could output this on your last console.log line which would quickly change the output to what you want:
console.log('+used,car,on,sale'.replace(/,/g, ' +'))
It basically replaces the comma for a space and +, it's quick and easy, otherwise I would use .split method and split where the comma is and re-build from the returned array.

A: Ther is no nead for jquery in this, try this:
If you don't want es6 function syntax => you can always use old function

const data = [
  'used car',
  'used car for sale and something else'
]

const addPlus = data => data.replace(/\+?(\S+)/g, '+$1')

const addPlusInArray = array => array.map(addPlus)

console.log(addPlusInArray(data))

.replace(
/\+?(\S+)/g find any nont whitespace (optional + infront)
'+$1' replace with content of first capture group
)
.map (
addPlus result of this function caled with first argument as array element will become new content of new array
)


text:
Q: Automatically insert row to MySQL after 60 seconds using PHP I'm looking for a way to automatically insert row to MySQL. Currently I using PHP Cron to do this, but values don't look perfect in MySQL - photo below.

What should I do to get clearly date_added values like for example:
2018-04-30 13:50:00
2018-04-30 13:51:00
2018-04-30 13:52:00
2018-04-30 13:53:00
2018-04-30 13:54:00
2018-04-30 13:55:00
2018-04-30 13:56:00
2018-04-30 13:57:00

I want to do this because it's important for me to make analytics and remove all empty data if exists. Below script is a 60 seconds cron made in php.
$date = date('Y-m-d H:i:s');

/* Define functions */
function write_cron($timestamp, $cron_name, $var_name) {
    $filename = realpath(dirname(__FILE__)).'/times/'.$cron_name.'.php';
    $content = file_put_contents($filename, '<? $'.$var_name.'[\'time\'] = \''.$timestamp.'\'; ?>');

    $return = true;
    if (!$content) {
        die('System ERROR
system/cron/times/'.$cron_name.'.php must be writable (change permissions to 777)');
        $return = false;
    }
    return $return;
}

/* Times */
$timestamp = time();
$daily_time = strtotime(date('j F Y'));

$realPath = realpath(dirname(__FILE__));
if (!is_writable($realPath.'/times')) {
    die('System ERROR
system/cron/times/ directory must be writable (change permissions to 777)');
}

if (file_exists($realPath.'/times/5min_cron.php')) {
    include($realPath.'/times/5min_cron.php');
}

if ($cron_5min['time'] <= ($timestamp-60)) {
    $write = write_cron($timestamp, '5min_cron', 'cron_5min');
    if ($write) {
    $db->Query("INSERT INTO `m_z_analytics_empty` (`coins`, `1_min`, `1_day`, `date_added`) VALUES ('0.00', '1', '0', '".$date."')");
    }
}

5min_cron.php
<? $cron_5min['time'] = '1514768460'; ?>

A: Change
$date = date('Y-m-d H:i:s');

into
$date = date('Y-m-d H:i:00');


text:
Q: Argparse optional stdin argument I am trying to specify an optional argument that takes stdin. This will be mainly used for piping data in my program, so someprog that outputs | python my_prog.
I followed the argparse documentation and I read a lot of questions/answers on this on Stackoverflow but none of them seem to work for me.
Here's what I originally have:
parser = argparse.ArgumentParser(description='Upgrade Instance.')
parser.add_argument('--app', '-a', dest='app', action='store', required=True)
parser.add_argument('--version', '-v', dest='version', action='store', default='', required=False)
parser.add_argument('--config', '-c', dest='config', action='store', default = '', required=False)
args = parser.parse_args()

Now what I want to do is allow the user to pass in version using a pipe, instead of passing it in.
I added parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin) to the top but that makes it a positional argument. How is that possible? I thought nargs=? makes it optional.
I need it to be an optional argument. So I changed it to:
parser.add_argument('--infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)

This makes it an optional argument, but the program hangs waiting for stdin as thats default, if no pipe is passed. Removing the default=sys.stdin and piping something into my program I get:
close failed in file object destructor:
sys.excepthook is missing
lost sys.stderr

when running it. When I print args, I get: Namespace(app='app', config='', g=False, hosts='03.app', infile=None, version='').
It seems what I am doing is very simple, common and many people asked about it. But it doesn't seem to be working with me.
Any suggestions on how I can get it working?

A: This does it... without specifying arguments. If you pass pipe input to the program it goes, it you don't, it still goes. raw_input() will work as well.
import sys

if not sys.stdin.isatty():
    stdin = sys.stdin.readlines()
    print stdin
    sys.stdin = open('/dev/tty')
else:
    print "No stdin"

test_raw = raw_input()
print test_raw

Demo -
rypeck$ echo "stdin input" | python test_argparse.py -a test
['stdin input\n']
raw_input working!
raw_input working!
rypeck$ python test_argparse.py -a test
No stdin
raw_input working!
raw_input working!

A: I was poking at this issue myself and found a small improvement on the options here--hopefully it'll help future travelers. It's not 100% clear if you were hoping to only read from stdin when you provide a flag, but it seems that may have been your goal; my answer is predicated on this assumption. I'm working in 3.4, in case that becomes an issue...
I can declare a single optional argument like:
parser.add_argument("-v", "--version", nargs='?', const=sys.stdin, action=StreamType)

I'm not specifying a default because it is used only if the option is completely absent, while the const is used only if the flag is present but has no arguments. StreamType is a tiny argparse.Action subclass I wrote which just tries to read a line from the stdin stream and just saves the raw value if that doesn't work:
class StreamType(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        try:
            setattr(namespace, self.dest, values.readline().strip())
        except AttributeError:
            setattr(namespace, self.dest, values)

This should produce something like:
$ blah --version v1.1.1
Namespace(version='v1.1.1')

$ echo "v1.0.3" | blah --version
Namespace(version='v1.0.3')

A: What do you do with args.infile?  since you get a Namespace, argparse is not the part that is hanging or giving the error.
p = argparse.ArgumentParser()
p.add_argument('--infile', type=argparse.FileType('r'),default='-')
# p.add_argument('infile', nargs='?', type=argparse.FileType('r'),default='-') # positional version
args = p.parse_args()
print(args)
print args.infile.read()
-----------
$ cat myprog.py | python myprog.py --infile -
$ cat myprog.py | python myprog.py
$ python myprog.py myprog.py  # with the positional version
$ python myprog.py - < myprog.py  # with the positional version

echos the code nicely.  The second call works with the 'optional positional' as well.
There is an unfortunate overlap in terminology, optional/positional and optional/required.
If a positional argument (yes, another use of 'positional') has a prefix character like - or -- it is called optional.  By default its required parameter is False, but you may set it to True.  But if the argument is 'infile' (no prefix), it is positional, even though with ? is is optional (not required).
By the way, default action is 'store', so you don't need to specify that.  Also you don't need to specify required, unless it is True.
With a FileType, a handy way of specifying stdin is -.
Don't use '?' with --infile unless you really want a None

A: I'm not sure if I got your question correctly, but even if not, as I came here trying to solve my problem, this answer may help.
import argparse
import sys

def get_args():
    parser = argparse.ArgumentParser(prog="my program")
    parser.add_argument("--version", type=str, default = None)
    args,unknown = parser.parse_known_args()
    print(f"normal unknown: {unknown}")

    if not sys.stdin.isatty():
        stdin = sys.stdin.readlines()
        stdin = ' '.join( (x.strip() for x in stdin ))
        args, unknown2 = parser.parse_known_args(stdin.split(), namespace = args)
        unknown.extend(unknown2)
        print(f"stdin unknown: {unknown2}")

    print(f"args: {args}")

get_args()

Now, I get
echo A --version=1.2.3 B | parse.py --C=some_value
normal unknown: ['--C=some_value']
stdin unknown: ['A', 'B']
args: Namespace(version='1.2.3')


text:
Q: What exactly makes a black hole STAY a black hole? I don't understand how, as a black hole gets smaller and smaller from the excretion of Hawking radiation, it retains its ability to capture photons. I imagine there would be a point in its life cycle where its mass/gravity just isn't enough for it to be able to do so and its body could be revealed, and perhaps gain back some of its previous volume from the lack of gravity being able to hold it together as tightly?
I have no formal education in physics yet.

A: I take it, that this question is actually about how tiny black holes actually behave. That the aim is to get some kind of intuition about what happens. As such, this answer focuses on describing the last seconds of a black hole. The question gets answered, but the context is also illuminated.

Actually, the black hole does not stay black at all. It evaporates. The more mass it loses to Hawking radiation, the hotter the Hawking radiation becomes, and the faster it evaporates. This is a self-amplifying process that reaches infinite power within a finite time. In the last second of the life of the "black" hole, the Hawking radiation becomes so fierce that it carries away more energy than all the nuclear arsenals on this planet , all taken together, could deliver. Magnitudes of more energy! The radiation will consist of ever harder gamma rays, and at some points electrons/positrons, (anti-)protons, (anti-)neutrons, and other (anti-)particles will start being emitted with ever growing numbers. And all of this radiation is coming out of a tiny sphere comparable to the size of a proton!
As such, "capturing photons" is not really a description of the evaporating black hole anymore. It's a freaking source of photons. Nevertheless, this is all Hawking radiation, and does not tell you any more about the inside of the event horizon than any other Hawking photon does that is emitted in the earlier, cooler stages of evaporation.
And anyways, if something does not interact with a photon, the photon cannot tell you anything about it. So, even though the event horizon becomes too small to interact with incoming radiation appreciatively, it does not reveal anything about its innards. The event horizon still remains the impenetrable shroud that gobbles up anything of sizes comparable to the Schwarzchild radius of the black hole and smaller.

A: After writing this answer, I noticed there are a couple alternative explanations that might be interesting to mention, so I'll add them as well.
Explanation 1
What makes something into a black hole isn't exactly how much mass it has, but also how compactified it is. In principle, any amount of mass can form a black hole, as long as you compactify it enough.
The size needed for some amount of mass to form a black hole is know as the Schwarzschild radius. Roughly speaking, if you pick an amount of mass and manage to compress it below the Schwarzschild radius, you'll have a black hole. It is given by a simple expression. Namely,
$$R_S = \frac{2 G M}{c^2},$$
where $M$ is the mass, $c$ is the speed of light, and $G$ is Newton's gravitational constant (which sort of measures how intense gravity is). For example, for something with the mass of the Earth, the Schwarzschild radius is roughly $0.88$ cm, while for the Sun it is about $2.9$ km (I must admit I didn't double check the computation, I'm trusting Google on these numbers, but they are pretty much what I remember).
Hence, the black hole stays a black hole while it evaporates because it is shrinking while it is losing mass, and always shrinking enough so that it is always at the correct size.
Explanation 2
The second way of thinking is a bit less familiar. It turns out that black holes aren't really objects, but rather regions in spacetime. In fact, this is so true that black holes are what we call vacuum solutions: there isn't matter anywhere in the spacetime. All of the mass of the black hole is there due to effects of gravity itself. Another way of thinking it is that a black hole is so collapsed that its mass is entirely due to gravitational energy.
It is a bit harder to grasp this concept, but once you get it, the rest is simpler. The black hole stays there because it isn't "made" of anything. There isn't a star just below the event horizon waiting to come out. There is nothing there, but gravity. As it loses mass, gravity weakens and it gets smaller, but there isn't anything behind the horizon to come out.
Edit: the question "What do we mean when we say that black holes aren't made of anything?" later asked for a more technical discussion of parts of this explanation. I suggest checking it out.
Explanation 3
The third explanation might be a bit simpler than the second. Once something falls into a black hole, that's it. It can't come out. Ever. By the very definition of what a black hole is. Hence, as the hole shrinks, there is no way something could come out of the hole to be its "body". That would violate the very meaning of what is a black hole.

This is a simplified answer. Since OP doesn't have formal education in Physics, I might have overlooked a few details and nuances in here, but I did my best to keep the answer as faithful as possible.

A: As simplified answer to your question is this:

*

*It is possible that they stay black holes because only large black holes can exist.

A longer discussion.

*

*Remember that Physics is an experimental or observational science first of all. Theories that are not supported by experiments or observations may be interesting thought experiments at best.

*We have never seen a "small" black hole and can not really know if they can, will or ever have existed. With small I here mean a black hole that loses more in mass over time than it gains (the very basis of your question).

*What we have found out is that at small scale of stuff, the classic mechanics break down and are better described by other theories, often based on quantuum  effects. The so called Schwartschild radius is built on classical mechanics and probably does not hold up for small things, and hence is probably not relevant for "small" black holes.

*Basically a lot of our theories, makes assumptions and speculates around how small black holes could be created and how they would behave. History has shown that sometimes theories get it right, sometimes wrong. Until proven by experiments the only thing we can do with the theories is to consider them as brain games. You may want to learn the theories, but stay away from believing that they are reality, until experimentally shown to be at least possible.

A: This is not a competing answer but rather a supplementary one.
You say "capture photons" as if gravity is so strong that photons cannot escape, like the pop science idea that "escape velocity is faster than light speed."  To me, this is the wrong picture. General relativity tells us that what we call "gravity" is not a force; rather, the presence of mass and energy changes the rules of geometry in the regions near them in ways that make the trajectories of objects curve. You don't fall towards Earth because of a force pulling. You fall because paths are bent in such a way that they progress towards the Earth.
You can think of it like space and time are a big sheet of graph paper, which in empty space is flat and with lines at 90°, but near a mass like the Earth are curved.  They curve more and more the closer you get to Earth, but before they diverge too much from being straight, you would hit Earth's surface. Now, imagine you crammed all the matter in the Earth into a much smaller space at its center, so the lines could continue curving.  At some point they would curve so much, the geometry would change so much, that outward is no longer a possible direction. You could not move further away from the center by changing direction or adding speed, any more than right now you could travel backwards in time by traveling in a certain direction or getting to a certain speed (not even 88 mph).  "Backwards in time" is simply not an available direction.
A black hole is simply an object whose mass is compressed so much that the curvature can get close enough to the center to reach this critical stage (Schwartzchild radius) where outward is no longer possible. But there is no minimum size. Earth could become a black hole if it were compressed as described to under 1 cm.  The reason in reality we do not observe "small" black holes is the only known process capable of compressing matter to those extremes, is the collapse of stars. And this can only happen with a certain minimum mass.
(It is speculated that cosmic ray particles crashing into the atmosphere at extremely high energies may create black holes with the mass of a few atoms, which would Hawking evaporate in nanoseconds.  But this has not been proven.)

A: Some other supplementary points to amplify other answers.
A black hole isn't really a hole in the sense we use on earth.  Its a name, a label.  So let's not get hung up on the name that we use. So I'll call it a BH here.
General relativity tells us that any matter or energy (same thing really for this) bends spacetime.  Meaning it bends the geometry of space itself (among other things).
If you pack enough "stuff" in any space, it bends space enough that there is a region of space where anything whatsoever cannot avoid moving inwards. Literally all directions, every which way, are so twisted they * all * point inwards.  There isn't any direction which lets you go outward, at all.
What this means is, anything whatsoever within that part of space, can only ever go more "into" the center of that part of space, never ever outward.  We say that "all futures (the future for any object or energy) points inward".
Its in that sense it is like having some kind of "black hole".  Its a part of space where no light can emerge from, and like an infinitely deep hole, whatever falls over the "edge" is lost from view forever. You can't ever get near enough the edge to see through inside that part of space, because light itself also falls inward.
General relativity gets complicated when you ask what counts as "stuff".  Because matter and energy count as the same thing, enough energy in a small enough space, creates this BH effect as well. This is why some answers say that enough gravitational energy alone, can create and sustain a BH, with or without matter.
As a BH incredibly slowly loses energy via Hawkings radiation, the amount of "stuff" within it, shrinks.  If it was spread out equally everywhere it might be a problem.  But it isn't.  Its moved to the center and so its now an infinite or near infinitely dense amount of stuff in an infinitely small part of the hidden off area of space.  The boundary can shrink, and there's still always enough stuff at the center to maintain a BH effect, albeit for a smaller volume of space.


text:
Q: Dont know how to use a drag and drop jQuery plugin I just find out this plugin http://www.konsolestudio.com/dad/, but i have no idea how to use it. I tried to follow the instructions, but they are not clear for me, and i cant't figure out how the plugin works. Can anyone give a hand? Thanks a lot.

A: Include sources

<link rel="stylesheet" type="text/css" href="http://www.konsolestudio.com/source/jquery.dad.css">

HTML

1

2

3

4

5

JS
$('.dad').dad();

http://jsfiddle.net/atvty29u/1/


text:
Q: Proof of Function Norms
Let:
  $$f_n(x) = \begin{cases} 1 & -n \le x \le n \\ 0 & \text{ otherwise} \end{cases}$$
  Prove that $\|f_n\|_∞ = 1$, but $\|f_n\|_2 \to \infty$ as $n \to \infty$
  and that there is no constant $C$ such that $\|f\|_2 \le C\|f\|_\infty$ for all
  functions $f$.

My attempt:
I know that for $\|f_n\|_2$ it goes to $\infty$ since the integral will equal to $x$ from the limits $-n \to n$ and if $n = \infty$ we have that $\|f_n\|_2 = \infty$. But why does $\|f_n\|_\infty = 1$? Also, since they both don't approach the same limit it means there is no constant $C$?

A: The definition of $M=||f||_\infty$ is the essential supremum of $f$. In other words, it is the the smallest number $M$ such that $f(x)\leq M$ for $x$ almost everywhere (in your case with respect to the Lebesgue measure, most likely). In your case the essential supremum is the same as the regular supremum, because your function is well behaved. The largest value that $f_n$ can take for any $n$ is 1, so that is the value of $||f_n||_\infty$.
For the second part, because $||f_n||_2\rightarrow\infty$ as $n\rightarrow\infty$, for any fixed $C$, I can choose $n$ large enough such that $||f_n||_2>C=C||f||_\infty$. Therefore, no such $C$ could ever satisfy $||f_n||_2\leq C||f||_\infty$ for all $n$.
EDIT:
In case the supremum norm is defined by $||f||_\infty=\lim_{p\rightarrow\infty}||f||_p$, you can use the following calculation.
$$
||f_n||_p=\left(\int_{-n}^n 1^p dx\right)^{1/p} = (2n)^{1/p}
$$
This right hand side converges to 1 for all $n$ as $p\rightarrow\infty$, hence $||f_n||_\infty=1$ for all $n$.

A: Check your definition of $\|f_n\|_\infty$. If you've defined it as the essential supremum, it's not hard to see that $f^{-1}(a,\infty) = \emptyset$ if $a > 1$ and $f^{-1}(a,\infty) \supset [-n,n]$ for $a \leq 1$ and so you can show $\|f\|_\infty = 1$. On the other hand, if your definition is something like $\lim_{\ p\rightarrow \infty} \|f_n\|_p$, then calculating the value of the integral isn't difficult. Remember, the $\infty$ norm is supposed to act like a "maximum" or "supremum" of the function's absolute value, which is obviously 1 here.
As for the constant, it looks like you've got it. If there was such a constant, it would hold for your $f_n$, which it obviously doesn't.


text:
Q: Setting up GitHub webhooks for an OpenShift build I tried to set up a github webhook to trigger builds on OpenShift following these docs.
I am confused about two things:
(1) When I create the secret, as prescribed by the above docs, do I need to create one YAML entry or two? Ie. are the following snippets (taken from the above link) supposed to be the same YAML entry?
type: "GitHub"
github:
  secretReference:
    name: "mysecret"

with the second one being:
- kind: Secret
  apiVersion: v1
  metadata:
    name: mysecret
    creationTimestamp:
  data:
    WebHookSecretKey: c2VjcmV0dmFsdWUx

(2) If I query oc describe bc [name-of-my-build-config], I get (all masks of [this] form were added by me)
Webhook GitHub:
    URL:    https://[blabla].openshift-online.com:6443/apis/build.openshift.io/v1/namespaces/[my-namespace]/buildconfigs/[my-build-config]/webhooks/<secret>/github

So now when I enter this url as a GitHub webhook, what should I replace <secret> with in the above URL? Also, what should I enter in the textbox for Secret on Github (see screenshot below)

I understand that the WebHookSecretKey: c2VjcmV0dmFsdWUx is just an encoded version of the plaintext secret key... So where should I use the plaintext key? Should I also use mysecret anywhere, eg substitute in for <secret> in the above url?

A: The easiest way to get the full GitHub Webhook URL in OpenShift 4.x is to first get the URL from
$ oc describe bc my-build

...
Webhook GitHub:
    URL:    https://api.example.com:6443/apis/build.openshift.io/v1/namespaces/my-project/buildconfigs/my-build/webhooks/<secret>/github
...

Then, to fill in the <secret> portion of the URL, you get this from
$ oc get bc -o yaml

...
  triggers:
  - github:
      secret: 467ed550-c447-411d-87ad-2d3a3fa81538
    type: GitHub
...

So, for this example, the GitHub Webhook URL would be
https://api.example.com:6443/apis/build.openshift.io/v1/namespaces/my-project/buildconfigs/my-build/webhooks/467ed550-c447-411d-87ad-2d3a3fa81538/github


text:
Q: Segmentation fault with cudaMemcpy2D I have a 2D array dev_histogram stored in GPU and a 2D array histogarm stored in CPU. I want to copy content of dev_histogram into histogram. Below are relevant bits of my program. I can post full code as well.
int *dev_histogram; // Array for histogram, GPU
int histogram[SIZE_THETA][SIZE_RHO]; // Array for histogram, CPU

size_t pitch;
histogramSize = sizeof(int) * SIZE_THETA * SIZE_RHO;
cudaMallocPitch((void**)&dev_histogram, &pitch, SIZE_THETA * sizeof(int), SIZE_RHO)

houghTransformation << <width, height >> >(dev_edges, dev_histogram, pitch, n_pixels, width, height);

// Here I get a Segmentation fault:
cudaMemcpy2D(histogram, pitch, dev_histogram, SIZE_THETA * sizeof(int), SIZE_THETA * sizeof(int), SIZE_RHO * sizeof(int), cudaMemcpyDeviceToHost)

Could you please help me understand how to copy my matrix back? Mostly, I am confused with what to put as pitch for my source.

A: In the CUDA toolkit reference manual you can see that the pitch in the cudaMallocPitch is the allocated width in bytes for the 2D array you are copying. Your dev_histogram will have an actual width equal to pitch and height equal to your specified height. Each line of your 2D array has pitch bytes allocated but only width*sizeof(int) bytes of valid data.
In the same document the prototype for cudaMemcpy2D is
cudaError_t cudaMemcpy2D (void ∗ dst, size_t dpitch, const void ∗ src, size_t spitch, size_t width, size_t height, enum cudaMemcpyKind kind)

here dst is your array on the host, dpitch is the width in bytes of the destination array (histogram) and spitch is the width in bytes of the source array (dev_histogram). width and height are the dimensions of your 2D array.
You must call it like this then:
cudaMemcpy2D(histogram, SIZE_THETA*sizeof(int), dev_histogram, pitch, SIZE_THETA * sizeof(int), SIZE_RHO, cudaMemcpyDeviceToHost);

Edit: after ArchaeaSoftware I noticed that indeed the height is really number of rows, height in number of bytes doesn't make sense. Updated answer because you still need to change the pitches.

A: Specify SIZE_RHO as the height, not SIZE_RHO * sizeof(int):
<cudaMemcpy2D(histogram, pitch, dev_histogram, SIZE_THETA * sizeof(int), SIZE_THETA * sizeof(int), SIZE_RHO * sizeof(int), cudaMemcpyDeviceToHost);
>cudaMemcpy2D(histogram, pitch, dev_histogram, SIZE_THETA * sizeof(int), SIZE_THETA * sizeof(int), SIZE_RHO, cudaMemcpyDeviceToHost);

A: Often when storing data in contiguous memory you want to make a section of memory have a dimension that is a multiple of a storage unit so that data can be read efficiently. For example, rather than reading 4 individual bytes in a row you might read one 32 bit word. You do it for efficiency. Look up memory alignment.
For the same reason you want to make certain arrays have the size of pitch*height where pitch is the width rounded up to the nearest multiple of whatever storage unit you are using. If your array is 31*5 then you use a pitch of 32 but a width of 31. Four 32 bit reads are expected to be faster than thirty one 1 byte reads. You discard the extra "padding" byte.
You probably want to set pitch = width. The reason for your seg fault is that you haven't initialised it. Check that width and height are compatible with your GPU specifications for thread block size.


text:
Q: How To Fetch Data From Markdown File and Display it as a HTML input Form Is there any way to fetch data from markdown file and display it as a input form.
For the example lets say i have markdown file called data.md like this
---
title: "the data" // input form title
image: "the data" // input form image attachment
---
//text area
---

And then with a bunch of code the data from markdown above will be convert as an input an HTML form.
Kindly show me where should i start.

A: Take a look at frontmatter.
Assuming you're serving your .md file at /docs/example.md. Try something like this
$.GET('/docs/example.md').then(function(content){
    var parsed = frontmatter(content, { safeLoad: true });
    $('input[name=title]').val(parsed.data['title']);
});


text:
Q: stop slider after finish sliding i have a n animate div with left and right arrow , i just want to stop the slider after images finish , the problem that i have is the slider continue going to left and right with empty space , this is my code

function () {

    var size = $("div.slide-here li").size();

    var div_size = size / 4 * 163;
    $('.photo-gallery div.slide-here').css('width', div_size);
    $('.photo-pagging .left-arrow a').click(
        function () {
            $('.photo-gallery div.slide-here').animate({ left: '+=196px' });

            return false;
        });
    $('.photo-pagging .right-arrow a').click(
        function () {
            $('.photo-gallery  div.slide-here').animate({ left: '-=196px' });

            return false;

        });

A: just put in a boundary conditions for the end points by multiplying the image width * the number of images - 1 * - 1 for moving left and 0 for moving right. This would be a check on the first element obviously.
Its hard to be more specific with the given info.
edit: * instead of x for multiplication operator

A: Welcome to Stackoverflow! Your question was not clear enough, I suggest you read this regarding better questions in the future.
Regarding your question, here is a recommended read regarding building a jQuery slider plugin with images.
Good luck!


text:
Q: gobject-2.0-0 not able to load on macbook I am facing this error when I start my flask application on Python3 and Mac OS:

OSError: cannot load library 'gobject-2.0-0': dlopen(gobject-2.0-0, 2): image not found.  Additionally, ctypes.util.find_library() did not manage to locate a library called 'gobject-2.0-0'

I am using weasyprint in my project which is causing this issue.
I tried to install glib and it is installed in my system.

A: If you installed weasyprint package in your virtual env but did not installed some required packages for that, then that might be the reason. It was actually, in my case.
If you're mac user you need install pango and libffi, not to mention python as well.
Installation guide on mac
brew install python pango libffi
(venv) pip install weasyprint

A: To expand on the existing answers on Apple Silicon (M1) Macs:
If you have installed the packages with Homebrew and they are still not found or linked under /usr/local/lib, it is because they are installed on arm64 and found in /opt/homebrew/lib instead.
If you're using Python installed with Homebrew it should work without any extra work, however system Python and any managed Python versions (e.g. installed with Pyenv) will require some configuration.
1. Manual symlinking
Instead of linking each library individually to /usr/local/lib, you can link the /opt/homebrew/lib contents (as long as you don't have an existing /usr/local/lib directory):
sudo ln -s /opt/homebrew/lib /usr/local/lib

This will work as long as the library you're looking for is not from a keg-only formula (those will have to be linked individually).
2. Environment variables
A lot of answers point to setting some environment variable, like LDFLAGS or DYLD_LIBRARY_PATH to add search paths for libraries, but these will not work with Python based on my testing:
macOS comes with System Integrity Protection (SIP) which, among other things, sanitizes your environment variables in subprocesses, for example Python. Anything starting with LD or DYLD will be purged, so setting the environment variables in your terminal profile will not work.
You can Disable SIP to get these working, but Apple recommends only doing it temporarily when needed.
If you decide to go this route, here are a few options:
In Homebrew's Github discussions the question was answered by setting LDFLAGS:
export LDFLAGS=-L/opt/homebrew/lib

Similarly you could add the necessary paths to DYLD_LIBRARY_PATH
export DYLD_LIBRARY_PATH=/opt/homebrew/lib

A: I just managed the same issue on my Mac M1.
The problem was that symlinks to the libraries were not created (can't say should it be done by homebrew or weasyprint when installation).
So, I had to do it manually
sudo ln -s /opt/homebrew/opt/glib/lib/libgobject-2.0.0.dylib /usr/local/lib/gobject-2.0
sudo ln -s /opt/homebrew/opt/pango/lib/libpango-1.0.dylib /usr/local/lib/pango-1.0
sudo ln -s /opt/homebrew/opt/harfbuzz/lib/libharfbuzz.dylib /usr/local/lib/harfbuzz
sudo ln -s /opt/homebrew/opt/fontconfig/lib/libfontconfig.1.dylib /usr/local/lib/fontconfig-1
sudo ln -s /opt/homebrew/opt/pango/lib/libpangoft2-1.0.dylib /usr/local/lib/pangoft2-1.0

This solved the problem.
In order to TEST if Python can find the library you may run
from ctypes.util import find_library

find_library('gobject-2.0')  # Pass any other lib name as an argument

UPD. There is no such problem if you install python with homebrew.

A: I had the same issue after the homebrew update. Turned out the issue was because of the older pango lib version.
I did brew install pango
This upgraded pango lib from 1.48.2 -> 1.50.4 which internally installed gobject's latest version as dep. And my issue got resolved.


text:
Q: Expire offer after a few minutes In my Asp.Net MVC 5 website, I have an entity called Offer with an expiration time. For instance once an offer is started, it will be expired after 30 minutes. What I need is some way to set the status as Expired and email the owner of the offer to notify that their offer has expired.
What I found out so far are:

*

*Using an endpoint on my website which tells the website to find expired offers and do this for all of them, then calling that endpoint from a Windows Service.

*Same as above but using a scheduler library (instead of Windows Service)

*Using scheduler for each offer. Meaning when I create an offer, add a scheduler entry for that specific offer.

None of these seem ideal so I'm asking here, looking for a better alternative. If there's none, which one would you go for?

A: When you create the offer server-side, set an expiration timestamp and remember it (persist to a DB, etc). If someone attempts to redeem their offer after that time has passed, say it's expired. You don't need to actively track whether each individual offer has expired (unless you want to show the remaining time in the UI, in which case a little JavaScript can count down to the expiration timestamp).


text:
Q: How to extend 'T? I'm trying to write an extension for 'T, basically the following in C#:
public static T With<T>(this T obj, Action<T> action)
{
    action(obj);
    return obj;
}

I tried to translate it to F#:
[<Extension>]
type Ext =
    [<Extension>]
    static member With<'T>(obj: 'T, action: Action<'T>): 'T =
        action.Invoke(obj);
        obj;

and
module Extensions =
    type 'T with
        member this.With(action: Action<'T>): 'T = Ext.With(this, action);

But this yields the error "Unexpected keyword 'with' in type name." in the last snippet.
A search returned this, but it obviously works only for array types: How to define a type extension for T[] in F#?
How can I extend the generic type 'T, or is there any workaround?

A: It appears that you can accomplish this as follows:
open System.Runtime.CompilerServices

[<Extension>]
type Ext =
    [<Extension>]
    static member With(obj, act) =
        act(obj)
        obj

// example of usage
"a".With(fun s -> printfn "%s" s).With(fun s-> printfn "%s" (s + "2"))

You don't really need the explicit types (generic or otherwise) at all. F# will infer the necessary types based on the body of the method.
Of course, you could accomplish this in a more F#-esque way without using extensions at all:
let withval =
    fun act value ->
       act(value)
       value

// example of usage
"a"
   |> withval (fun s -> printfn "%s" s)
   |> withval (fun s-> printfn "%s" (s + "2"))


text:
Q: Blender fbx import from ascii format I have a FBX model which I would like to open in Blender but when I try to import the model it says: ASCII FBX files are not supported. Is there a way to import the model to Blender somehow? I don't have access to any Autodesk software.

A: Unfortunately I can't comment yet but here's an update to maZZZu's answer:
The Bos FBX Importer will also not open ASCII .fbx files, however Autodesk's FBX Converter still does.
Here's the updated URL: https://www.autodesk.com/developer-network/platform-technologies/fbx-converter-archives

A: For some reason Blender import doesn't support FBX models that are serialized to text.
As a workaround the model can be changed to binary FBX model and imported to Blender. At least I am able to use Autodesk FBX 2013.3 Converter even I don't have any other Autodesk software installed.
Other option that might work is to use Bos FBX Importer.
PS. If you want to export FBX models from Blender and be able to import them again, you can choose version: FBX 7.4 binary not FBX 6.1 ASCII in the export settings panel.

A: I tried Audtodesk converter - useless because of UV destroying.
I use Paint 3D (if you have win10 of course). Works fluent. Just open it then save in fbx again.
p.s. have a nice day!

A: This simple commandline tool worked for me to convert an ASCII FBX to a Blender-compatible binary FBX: https://github.com/BobbyAnguelov/FbxFormatConverter/releases/
It can convert between binary and ascii - see usage info, for example:
# ASCII to Binary
FbxFormatConverter.exe -c in_ascii.fbx -o out_binary.fbx -binary

# Binary to ASCII
FbxFormatConverter.exe -c in_binary.fbx -o out_ascii.fbx -ascii

It's for Windows, but I used it fine with wine under linux.
If you use the pre-compiled version, technically you should agree to the FBX SDK license agreement.

A: If you have Visual Studio installed try to open the original file then save it and import in Blender. This should work.

A: What really works is this:
https://www.autodesk.com/developer-network/platform-technologies/fbx-sdk-2020-0?us_oa=akn-us&us_si=9066be5d-863a-4cd3-b98f-87bda034316b&us_st=fbx%20sdk
there you can download sdk for all common used os.
You can compile the ConvertScene sample with: cmake, gcc, libxml2-dev
The resulting binary can be used to convert ascii fbx to bin fbx that can be imported in blender.

A: This site has a good explanation. It says that ASCII format is human readable, contains all the model's info, but it's not Blender-readable. We need Binary format, and whoever makes the model needs to choose ASCII to give customers all the data, or they choose binary to make it importable to Blender. When they choose ASCII, we need to covert it ourselves. Supposedly there's a free tool for converting this using the Autodesk. I'm still looking around the Autodesk site for a free tool, but it may require some trial software. https://www.blender3darchitect.com/modeling-for-architecture/import-ascii-fbx-files-blender/.
Update: I found this page with links to Autodesk tools, including the FBX 2013.3 Converter for Windows 64-bit mentioned earlier in this thread: https://www.autodesk.com/developer-network/platform-technologies/fbx-converter-archives
Update 2: It* worked! I converted my ASCII FBX to Binary, and I imported successfully into Blender 2.80. (*It = FBX 2013.3 Converter for Windows 64-bit)


text:
Q: Creating new column in a dataframe based on other columns in r I have a dataframe with 144 columns with lots of NAs, I want to create new column with dichotomous value based on current columns. So that, if columns 1: 126 have values the new column get "Q" and if columns 126:144 have values the new column get "R". In the case that there are values for both (1:126 & 126:144), it will get "R" too. If non has value the new column get "NA".

A: Ok, let's say your data.frame is called df, using below as an example:
df = data.frame(matrix(runif(144*100),ncol=144))
df[df < 0.99] = NA

Then you can do:
df$new_column = NA
df$new_column[rowSums(!is.na(df[,1:126]))>0] = "Q"
df$new_column[rowSums(!is.na(df[,126:144]))>0] = "R"