text:
Q: A variation on the local Günther inequality This question is about a variation on the Günther (also known as Günther-Bishop) inequality for manifolds of sectional curvature bounded from above. With Greg Kuperberg, we would deduce from it a conjectured isoperimetric inequality in dimension $4$ which for the moment we only get for small enough domains; see our paper for more details and below for a short account.
Notation and the precise question
Let $(M,g)$ be a Riemannian manifold of dimension $n$, and let us call "candle function" at $x\in M$ the Jacobian of its exponential map, normalized as the function $j_x:Tx M \to \mathbb{R}^+$ such that
$$ \mathrm{d}y = j_x(tu) \,\mathrm{d}t \,\mathrm{d}u \quad\mbox{when }y=\exp_x(tu)$$
where $\mathrm{d}y$ is the Riemannian volume, $\mathrm{d}t$ is Lebesgue measure, and $\mathrm{d}u$ is the Riemannian volume of the unit ball of $T_x M$.
Fix a geodesic segment $\gamma$ of length $\ell$, parametrized by arc length, without conjugate points, and consider the function of two parameters $r\le t$ given by
$$j(r,t) = j_{\gamma(r)}\big((t-r)\gamma'(r)\big)$$
that is, $j(r,t)$ represent how large the volume element at $\gamma(t)$ looks in the exponential chart based at $\gamma(r)$.
For example, if we denote by $s$ be the function $j$ when $M$ is the hyperbolic space, we get
$$ s(r,t) = \sinh^{n-1}(t-r).$$
The question is the following:

Is it true that when $M$ has sectional curvature bounded above by $-1$,
  then (for all geodesic as above) the expression
  $$ j(0,\ell) - (n-1) \int_0^\ell j(0,t) \,\mathrm{d}t - (n-1) \int_0^\ell j(r,\ell) \,\mathrm{d}t +(n-1)^2 \int_0^\ell \int_0^t j(r,t) \,\mathrm{d}r \,\mathrm{d}t$$
  is minimized when $j=s$, i.e. when the curvature is equal to $-1$ along the geodesic?

The $n=4$ version would be enough for our purpose, but I don't see why it would be easier than the general case.
We conjecture that a stronger inequality, obtained by differentiating twice the above, should be true:

Is it true that when $M$ has sectional curvature bounded above by $-1$,
  then (for all geodesic as above) the expression
  $$ -\partial^2_{rt} j  -(n-1) \partial_t j +(n-1) \partial_r j +(n-1)^2 j$$
  is minimized when $j=s$, i.e. when the curvature is equal to $-1$ along the geodesic?

(here for example $\partial^2_{rt}$ means $\frac{\partial^2}{\partial r\partial t}$)
Comparison with Günther, and what we know
A local version of Günther's inequality is that when $M$ has sectional curvature bounded above by $-1$,
$$ \partial_t j / j $$
is minimized when $j=s$. It is easy to derive from this that then
$$ \partial_t j - (n-1) j$$
is minimized when $j=s$. So in a sense, what we ask is to improve this comparison from the operator $\partial_t -(n-1)$ to the operator $(-\partial_r -(n-1))(\partial_t-(n-1))$.
We are able to answer positively our question when $n=2$, but our proofs do not extend to higher dimension, at least not easily. We are also able to prove the above with weaker constants instead of the $(n-1)$, but then we get a smallness constraint when we apply the inequality to get the isoperimetric comparison.
In our paper with Greg, we prove that if the above inequality is true, then whenever $n=4$, $M$ is simply connected and has sectional curvature bounded above by $-1$, the isoperimetric profile of $M$ is bounded below by the isoperimetric profile of the $4$-dimensional hyperbolic space. A similar comparison is conjectured in all dimension and also when comparing with Euclidean space (with of course the assumption that sectional curvature is non-positive). This conjecture is known to be true when $n=2$ (Weil 1926, ... Aubin 70's ) or $3$ (Kleiner 1992), and for the Euclidean comparison when $n=4$ (Croke 1984). Right now, we only get the $n=4$, curvature less than $-1$ case for domains of volume less than an explicit constant, due to the limited solution we have to the present question. Note that we get a fully satisfying version of this conjecture for comparison to a sphere.


text:
Q: Get random directory I have several directories in one main directory. All I want to do is use php to echo a random directory from this list of directories every time the page refreshes.
I have been working with the following code but with no success:
$base_dir = 'images/';
function get_random_dir($base_dir)
    {
        $dirs = glob(sprintf($base_dir),GLOB_ONLYDIR);
        return empty($dirs) ? null : $dirs[array_rand($dirs)];
    }
echo get_random_dir($dirs);

At the moment this returns nothing. If anyone could help me out that would be great, thank you.

A: $base_dir = "images/";
function get_random_dir($base_dir) {
    $dirs = scandir($base_dir);
    return empty($dirs)?null:$dirs[rand(2,count($dirs)-1)];
}

This should work. The rand starts from 2 because 0 is . and 1 is ..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Signals and Variables in VHDL (order) - Problem I have a signal and this signal is a bitvector (Z). The length of the bitvector depends on an input n, it is not fixed. In order to find the length, I have to do some computations. Can I define a signal after defining the variables ? It is giving me errors when I do that. It is working fine If I keep the signal before the variables (that what is showing below) .. but I don't want that .. the length of Z depends on the computations of the variables. What is the solution ?
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity BSD_Full_Comp is
        Generic (n:integer:=8);
        Port(X, Y : inout  std_logic_vector(n-1 downto 0);
             FZ : out std_logic_vector(1 downto 0));
end BSD_Full_Comp;

architecture struct of BSD_Full_Comp is

Component BSD_BitComparator
    Port ( Ai_1  : inout  STD_LOGIC; Ai_0  : inout  STD_LOGIC;
           Bi_1  : inout  STD_LOGIC; Bi_0  : inout  STD_LOGIC;
           S1 : out  STD_LOGIC; S0 : out  STD_LOGIC
      );
END Component;

Signal Z : std_logic_vector(2*n-3 downto 0);

begin

    ass : process

Variable length : integer := n;
Variable pow : integer :=0 ;
Variable ZS : integer :=0;
begin
while length /= 0 loop
length := length/2;
pow := pow+1;
end loop;
length := 2 ** pow;
ZS := length - n;

wait;

    end process;

end struct;

A: Looks like you're trying to change the size of a hardware bus depending on the result of calculation? Remember that once you compile the circuit and burn it on to the FGPA, all your bus sizes are fixed. It's possible to have an FPGA change it's configuration on the fly, but I'd guess that it's not necessary a lot of the time. And I'd guess that it's tricky to do, too.
Maybe explain what exactly you are trying to calculate, and maybe we can come up with a different way of doing it.
A few other things. I'm not 100% familiar with VHDL, but do you need the bi-directional ports (the inouts)? Also, you don't seem to be using BSD_BitComparator; or ports X, Y or FZ; or signal Z in your architecture description.

A:
The length of the bitvector depends on
  an input n, it is not fixed.

It is fixed, it's a generic.  Once you've compiled and elaborated (ie built) the FPGA, n is fixed.  And that's fine, you can use that to define the lengths of signals within the architecture.
As with the other respondent, I'm not sure what you're trying to do with your process.  Are you trying to calculate the length that the Z signal will need to be?
If so, you can put it in a function, and use the function in the declaration of Z:
signal Z:std_logic_vector(calc_z_high_bit(n) downto 0);

A: A generic is fixed at compile/elaboration time.  A variable can change during runtime.  So, what you are aiming for isn't directly possible they way you are trying to do it.
If you want to dynamically specify some bitslice of the bus, you would need to define the bus to be the biggest it can be, and then use your computed n to mux out the slice of the bus you need.


text:
Q: IE8 delivering focus and click to a button on updating a text field I have a very strange problem with IE8; I have reduced this as much as possible to the extract below:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript">
            function dismissOperation() {
                alert("Would dismiss");
            }
        </script>
    </head>
    <body >
        <input type="text" />
        <input type="text" onfocus="alert('text box got focus')" />
        <button onclick="dismissOperation()" onfocus="alert('Dismiss button got focus')">Dismiss</button>
    </body>
</html>

The problem is that when a value is entered into the first textbox followed by return/enter, the button receives focus and the click event is delivered (on the button).
As a test, I added a second text entry box (as above). With the second box added, the focus still goes straight to the button when a value is entered into the first box.
What is causing the focus to go to the button and the click being delivered? Is there any workaround to this?

A: By default button element is considered as a submit button and that could be the reason for this. Give attribute type="button" for your button element.


text:
Q: Do "brownie points" derive from food-rationed "brown points"? The OED has this to say about "brownie points."

Brownie point  n.  [probably a development < brown-nose n. at brown adj. Special uses 2, but popularly associated with 2   and hence frequently spelled with capital initial] colloq. (orig. U.S.)
a notional credit for an achievement; favour in the eyes of another, esp. gained by sycophantic or servile behaviour.

The sense 2 referenced in the etymology note (and boldened for emphasis) refers to "brownie" meaning:

[ < the colour of their uniform.] A member of the junior section of the organization known as the 'Girl Guides'. Also attributive.

But Green's Dictionary of Slang, while listing the etymology as "unknown," offers an alternative theory:

recent research suggests that its origin may also lie in wartime American food rationing, in which ration points in various colours were required to make food purchases: red and brown ones, for example, referred to meats and fats. There are many references in wartime newspapers to 'brown points'.

Indeed, it is not hard to find many uses of the term "brown points" in this fashion.

*

*1944 - The Pantagraph (Bloomington, Illinois) 03 March 18 (paywall)

To confuse things just a bit further, I noticed this reference to "brownie point" from the 19th century, far before other attestations of "brownie point" in GDoS and the OED, which attest it in the 1950s and 60s.

*

*1896 - Star-Gazette (Elmira, New York) 19 Dec. 5/1 (paywall)

Questions:

*

*Does "brownie point" indeed derive from "brown point" as suggested by Green?  Alternatively, is there evidence to back the theories related to "brown-nosing" or girl scouts?

*Does the 1896 reference to "to the brownie point" have any relation to "brownie points" as known today, or is it an unrelated turn of phrase?

A: The origin of 'brownie points'
According to J.E. Lighter, Random House Historical Dictionary of American Slang (1994) "brownie points" originated from a grading or rewards system used by the Brownies subdivision of the Girl Scouts of America, but owed some of its popularity to the influence of the pejorative term "brown-nose":

brownie point n. {from the system used for advancement by the Brownies of the Girl Scouts of America; but strongly influenced by BROWN-NOSE [dated to 1938 and defined as "to curry favor (from) in an obsequious way; to toady (to)"—originally a military term "of scatological inspiration but not now considered vulgar"]} a credit toward advancement or good standing, esp. when gained by servility, opportunism, or the like. [Earliest cited occurrence as a slang term:] 1944–53 in MSU Folklore GF2.1: Army Jargon 29: Blew his stack. Brownie points.

The mysterious 1896 allusion to "brownie points'
The rest of my response focuses on your second question:

Does the 1896 reference to "to the brownie point" have any relation to "brownie points" as known today, or is it an unrelated turn of phrase?

The answer, I think, is that the 1896 instance is completely unrelated to the later concept of "brownie points." In fact, the expression in the 1896 instance—"First, it [a Christmas face] is earnest, oh, so earnest—to the brownie point, in fact"—seems to focus on a connection not between brownie and point, but between brownie and earnest. A newspaper item from three years earlier indicates a similar connection. From "Cordage Trust Visitors: An Illustration of the Difference Between Riding Men and Chappies," in the [New York] Sun (May 7, 1893):

The chappies talked the most, and had lost the least. The other men, the riding and athletic-looking men, were less excited, less voluble, heavier loosers, but all equally unused to their surroundings. Some of the confidences which were exchanged with as frank disregard of the curious outside listeners as if the speakers were safe on a veranda of a country club house, disclosed some new roads to Wall street. Two young men of the chappie order, with the earnest, serious faces of brownies, were standing on the lower steps of the entrance, talking so that even he who ran must hear.

But what does the "earnest face of a brownie" refer to? A search through multiple slang dictionaries from the period 1970–1920 turns up only one entry for brownie—in reference to a nautical term for a polar bear. Moreover, the brownie dessert seems to have got its name in 1896, the Brownie camera first appeared in 1900, and the Girl Scout order known as Brownies were organized in 1914 (originally under the name "Rosebuds"). It seems to me that the most likely sense of brownie here is to the sometimes mischievous but often hard-working and helpful sprites that, in Scottish folklore, have many of the attributes of the elves in the fairy tale "The Shoemaker and the Elves."
In the late 1800s, brownies were a familiar character in people's imaginations, thanks to a series of extremely popular children's books by Palmer Cox, who describes them in The Brownies at Home (1887) as follows:

BROWNIES, like fairies and goblins, are imaginary little sprites, who are supposed to delight in harmless pranks and helpful deeds. They work and sport while weary households sleep, and never allow themselves to be seen by mortal eyes.

In that same book, in a poem titled "The Brownies' Good Work," Cox describes how the brownies harvest the crops of a farmer, who had been badly injured while saving some children from a runaway team of horses. The farmer thinks that his neighbors had done the work while he slept, and the poem ends on this note:

But when he thanked them [his neighbors] for their aid, / And hoped they yet might be repaid / For acting such a friendly part, / His words appeared to pierce each heart; / For well they knew that other hands / Than theirs had laid his grain in bands, / That other backs had bent in toil / To save the products of the soil. / And then they felt as such folks will / Who fail to nobly act, until / More earnest helpers, stepping in, / Do all the praise and honor win.

The accompanying illustrations show the industrious brownies engaged in various tasks, sometimes smiling but often frowning or expressing surprise as their efforts sometimes go awry. Their faces are highly expressive and, indeed, earnest. In The Brownies at Home (1891/1893), Cox emphasizes the sincerity of which brownies are capable, in connection with writing Valentine's Day love letters on behalf of unsuspecting humans:

A Brownie has a level head, / Although perhaps not college-bred, / And knows just when to stop and start, / Or round a phrase to catch the heart; / And though sarcastic flings at men / They may indulge in now and then, / The earnest, active Brownie mind / To thoughts of love is more inclined; / So hearts and arrows, in the main, / The Brownies' missives did contain.

And again in "The Brownies Repair the Streets," in St. Nicholas (December 1910):

But liniments came into play / Before the midnight passed away, / And all the painful clips and raps, / That workmen get around such traps, / Could not the earnest band [of brownies] impress / Enough to halt, or labor less.

Also, from Frank Stockton, "Another Brownie Book," in The Book Buyer (December 1890)):

Here in this new book [Another Brownie Book, by Palmer Cox], we have them all, entering with an earnest and comic zeal into new phases of the life of to-day. They have not yet endeavored to find the North Pole, nor have they tried to revise the tariff laws, but we should not be at all surprised should they make efforts in those directions. They are very generous little fellows, these Brownies, and, true to their traditions, they take delight in doing for us what we do not seem able to do for ourselves.

It seems likely to me that a Christmas face that "is earnest, oh, so earnest—to the brownie point, in fact" is a face that shows serious dedication and resolve to the same point or degree that the faces of Palmer Cox's brownies do as those sprites pursue one of their enterprises for the betterment of a farmer's crops, a single person's chances at love, or the city's streets.

A: Does "brownie point" indeed derive from "brown point" as suggested by Green? Alternatively, is there evidence to back the theories related to "brown-nosing" or girl scouts?
From World Wide Words:

In particular, there are many references in newspapers during 1943–44
  to brown points, which may have contributed the points part of the
  expression

and

However, it seems that Brownie points is actually an allusion to the
  junior branch of the Girl Scouts (the Girl Guides in other countries)

Does the 1896 reference to "to the brownie point" have any relation to "brownie points" as known today, or is it an unrelated turn of phrase?
To my sense and from the reference I post, it does appear to be an unrelated turn of phrase.

It seems probable that two — or even three — threads came together to
  form the phrase. There's no reason why a slang term should have just
  one origin, and in fact the more antecedents and associations one has,
  the more likely it is to become popular.

The threads being army slang, the Brown (point) system of discipline, the Saturday Evening Post of the 1930's and brown nose of the 1940's. All of these are 40 some odd years after your 1898 finding of the phrase

A: According to Wikipedia,
"Brownie points in modern usage are a hypothetical social currency, which can be acquired by doing good deeds or earning favor in the eyes of another, often one's superior."
Also from Wikipedia,
".. proposed etymology is that the term derives from the name of a 19th-century American railroad superintendent, George R. Brown who, in 1886, devised what was then an innovative system of merits and demerits for railroad employees on the Fall Brook Railway in New York state. Accounts of his system were published in railroad journals, and adopted by many leading U.S. railroads. American railroad employees soon began referring colloquially to "brownie points", and at some point, the term entered the general vocabulary."


text:
Q: jQuery - How come the spinner is not showing up in safari I have this jQuery
$(document).ready(function(){
  $('#credit_btn, #checkout_btn').click(function(){
    $("#content_container .notice, #content_container .error").remove();
    $('#loading').show();
  });
});

The HTML

<input class="bigbutton" data-disable-with="One Moment, Processing..." id="checkout_btn" name="commit" type="submit" value="Next Step: Checkout">

why is the spinning not showing up it shows up when i do
  $j('#credit_btn, #checkout_btn').click(function(){
    $j("#content_container .notice, #content_container .error").remove();
    $j('#loading').show();
    return false;
  });

what is happening here and is there anything I can do? Thanks in advance
UPDATE
I tested this jquery as well
  $('#credit_btn, #checkout_btn').click(function(e){
    e.preventDefault();
    $("#content_container .notice, #content_container .error").remove();
    $('#loading').show();
    $(this).closest("form").submit();
  });

the spinner doesnt come up again but it shows up when i remove the line $(this).closest("form").submit(); ...I am confused...why does the form submit have anything to do why the loader

A: This happens because your form gets submitted, and so the page is reloaded. (you are seeing the page that the form direct you to)
This is the normal browser behavior. You might want to try submitting your form with AJAX, if you need to remain on the current page..


text:
Q: when viewing a page in firebug, can I see which event fires when I click a button? I'm viewing a page, and want to know which event is fired when I click on a button, and I want to trace through the .js files to help me learn what is going on.
Is this possible?

A: When you have the script panel enabled, you can click the pause button on the left to stop all JavaScript interaction. When you then press the button it stops and you can use the debugger to step through the code.


text:
Q: Swift 3: Select an Array based on a dictionary I have a popover view controller that contains a table view with a list of options, similar to a drop down selection list.  This table view is populated dynamically, depending on which "select" button the user hits on the parent view controller.  I have several Arrays built for the various option sets to populate the TVC.  How can I use the fieldIndex dictionary to automatically set the array to be used as the TVC datasource for the popover?
class MyWidget : NSObject {

  var fieldIndex : [Int:String] = [
        0 : "make",
        1 : "model",
        2 : "year"
  ]

  var make = String()
  var model = String()
  var year = String()
}

var makes = ["Acme", "Contoso", "Tradewinds"]
var models = ["Model1", "Model2", "Model3"]
var years = ["2015", "2016", "2017"]

A: You can simply create dictionary of type Int: [String]
class MyWidget : NSObject {
// empty fieldData dictionary of type Int: [String]
var fieldData = [Int: [String]]()

}

// add data like this
fieldData[0] = ["Acme", "Contoso", "Tradewinds"]
fieldData[1] = ["Model1", "Model2", "Model3"]
fieldData[2] = ["2015", "2016", "2017"]

// get data like this
let makeArray = fieldData[0]

A: I might approach it this way.
enum Attribute {
    case make, model, year

    var name: String {
        switch self {
        case .make:     return "Make"
        case .model:    return "Model"
        case .year:     return "Year"
        }
    }

    var allAttribtues: [Attribute] {
        return [.make, .model, .year]
    }
}

class AttributeDataSource {
    func options(for attribute: Attribute) -> [String] {
        switch attribute {
        case .make:     return ["Acme", "Contoso", "Tradewinds"]
        case .model:    return ["Model1", "Model2", "Model3"]
        case .year:     return ["2015", "2016", "2017"]
        }
    }
}

let dataSource = AttributeDataSource()

dataSource.options(for: .make)  // -> ["Acme", "Contoso", "Tradewinds"]
dataSource.options(for: .model) // -> ["Model1", "Model2", "Model3"]
dataSource.options(for: .year)  // -> ["2015", "2016", "2017"]

Don't hesitate to make first-class models for your data structures. Most of the time it will make things much more clear.

A: An alternative to using NSObject is to add this logic into a function directly in your code:
func getArray(_ positionInDictionary: Int) -> [String]{
    var fieldData: [Int:[String]] = [0 : ["Choice 01", "Choice 02", "Choice 03"], 1 : ["Choice 11","Choice 12","Choice 13"]]
    if let str = fieldData[positionInDictionary]{
        return str
    }
    else{ return []}
}

Usage:
var dataArray = getArray(1)

Also, this is IMO the simplest and fastest solution, and you can retrieve your dictionary from wherever you want.


text:
Q: Diagonal snake filling array Python 3.7. I'm trying to fill multidimensional array (n*m size) in diagonal-snake pattern:
1   3   4   10  11  21
2   5   9   12  20  22
6   8   13  19  23  30
7   14  18  24  29  31
15  17  25  28  32  35
16  26  27  33  34  36

I have a function for n x n size and it works fine for it. But for n x m size it returns:
1 3  4  10 14

2 5  9  15 20

6 8  16 19 19

7 17 18 20 21

My code:
def method1(i, j, n, m):
    num = i+j
    summ = num * (num + 1) >> 1
    s = n * m
    if num > n-1:
        t = 2*(n-1) - (i+j) + 1
        s -= t*(t+1) >> 1

    if num & 1:
        if num > n-1:
            return s + (n-i)
        else:
            return summ + j+1
    if num > n-1:
        return s + (n-j)
    else:
        return summ + i+1

for i in range(n):
    for j in range(m):
        print(method1(i, j, n, m), end=" ")
    print('\n')

What am I doing wrong?
P.S. Your answer can be in any language.

A: Here is a vectorized solution:
def tr(z):
    return z*(z+1)//2

def snake(Y, X):
    y, x = np.ogrid[:Y, :X]
    mn, mx = np.minimum(X, Y), np.maximum(X, Y)
    return (1 + tr(np.clip(x+y, None, mn))
            + mn * np.clip(x+y - mn, 0, None)
            - tr(np.clip(x+y - mx, 0, None))
            + ((x+y) & 1) * (x - np.clip(x+y + 1 - Y, 0, None))
            + ((x+y + 1) & 1) * (y - np.clip(x+y + 1 - X, 0, None)))

Demo:
>>> snake(7, 3)
array([[ 1,  3,  4],
       [ 2,  5,  9],
       [ 6,  8, 10],
       [ 7, 11, 15],
       [12, 14, 16],
       [13, 17, 20],
       [18, 19, 21]])
>>> snake(2, 4)
array([[1, 3, 4, 7],
       [2, 5, 6, 8]])

Explainer:
The function tr computes the number of elements in a triangle which is more or less half a square (a tiny bit more because we include the diagonal). This is used in snake to compute the offset of each diagonal; diagonals are indexed by x+y.
More precisely, the first three lines in the return statement compute the diagonal offset. The first line counts diagonals in the top left triangle, the second line counts full length diagonals and also those in the bottom right triangle; it counts those also as full length - the third line corrects for that.
The last two lines count within diagonals. The first of the two in top-right direction, the second in bottom-left direction. Observe, that the top-right offset is equal to the x coordinate for all diagonals that start at the left edge. The correction term (np.clip ...) is for diagonals starting at the bottom edge. Similarly bottom-left offsets are y if we start at the top edge and require a correction if we start at the right edge.

A: EDIT:
Here is a version of basically the same algorithm but without any loops:
def snake_matrix(n):
    # Make sequences: [0, 0, 1, 0, 1, 2, 0, 1, 2, 3, ...]
    i = np.arange(n)
    c = np.cumsum(i)
    reps = np.repeat(c, i + 1)
    seqs = np.arange(len(reps)) - reps
    # Make inverted sequences: [0, 1, 0, 2, 1, 0, 3, 2, 1, 0, ...]
    i_rep = np.repeat(i, i + 1)
    seqs_inv = i_rep - seqs
    # Select sequences for row and column indices
    seq_even_mask = (i_rep % 2 == 0)
    # Row inverts even sequences
    row = np.where(seq_even_mask, seqs, seqs_inv)
    # Column inverts odd sequences
    col = np.where(~seq_even_mask, seqs, seqs_inv)
    # Mirror  for lower right corner
    row = np.concatenate([row, n - 1 - row[len(row) - n - 1::-1]])
    col = np.concatenate([col, n - 1 - col[len(col) - n - 1::-1]])
    m = np.empty((n, n), dtype=int)
    m[row, col] = np.arange(n * n)
    return m

Interestingly, after a couple of benchmarks it seems that depending on the size this may or may not be faster than the previous algorithm.

Here is another solution with NumPy. I don't know if there is any other way to make this better (without loops, or in this case list comprehensions), but at least it does not loop over every single element. This one only works for square matrices though.
import numpy as np

def snake_matrix(n):
    # Sequences for indexing top left triangle: [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]...
    seqs = [np.arange(i + 1) for i in range(n)]
    # Row indices reverse odd sequences
    row = np.concatenate([seq if i % 2 == 0 else seq[::-1] for i, seq in enumerate(seqs)])
    # Column indices reverse even sequences
    col = np.concatenate([seq if i % 2 == 1 else seq[::-1] for i, seq in enumerate(seqs)])
    # Indices for bottom right triangle "mirror" top left triangle
    row = np.concatenate([row, n - 1 - row[len(row) - n - 1::-1]])
    col = np.concatenate([col, n - 1 - col[len(col) - n - 1::-1]])
    # Make matrix
    m = np.empty((n, n), dtype=int)
    m[row, col] = np.arange(n * n)
    return m

print(snake_matrix(6))

Output:
[[ 0  2  3  9 10 20]
 [ 1  4  8 11 19 21]
 [ 5  7 12 18 22 29]
 [ 6 13 17 23 28 30]
 [14 16 24 27 31 34]
 [15 25 26 32 33 35]]

There is some more information about this kind of enumeration in OEIS A319571 sequence (although that refers to the general sequence for an infinite grid, in this case you would have one enumeration starting at the top left and another at the bottom right).

A: not clear what you are doing wrong, but the following code should work:
import numpy as np

n = 4
m = 5

x, y = (0, 0)
ux, uy = (1, -1)

a = np.zeros((n, m))
for i in range(n*m):
  print((x, y), i+1)
  a[x, y] = i + 1
  x, y = (x + ux, y + uy)
  if y == m:
    print('right side')  # including corner
    y = m - 1
    x += 2
  elif x == n:
    print('bottom side')  # including corner
    x = n - 1
    y += 2
  elif x == -1:
    print('top side')
    x = 0
  elif y == -1:
    print('left side')
    y = 0
  else:
    continue
  ux, uy = -ux, -uy
print(a)

output:
(0, 0) 1
left side
(1, 0) 2
(0, 1) 3
top side
(0, 2) 4
(1, 1) 5
(2, 0) 6
left side
(3, 0) 7
(2, 1) 8
(1, 2) 9
(0, 3) 10
top side
(0, 4) 11
(1, 3) 12
(2, 2) 13
(3, 1) 14
bottom side
(3, 2) 15
(2, 3) 16
(1, 4) 17
right side
(2, 4) 18
(3, 3) 19
bottom side
(3, 4) 20
right side
[[ 1.  3.  4. 10. 11.]
 [ 2.  5.  9. 12. 17.]
 [ 6.  8. 13. 16. 18.]
 [ 7. 14. 15. 19. 20.]]

To write this, it helped a lot to draw a diagram.


text:
Q: Numerical equivalence between Cartesian products Let $J$ be some (non-empty) set of indices, and let $\left\{ A_\alpha \right\}_{\alpha \in J}$ and $\left\{ B_\alpha \right\}_{\alpha \in J}$ be any two indexed families of sets such that, for each $\alpha \in J$, the sets $A_\alpha$ and $B_\alpha$ have the same cardinality (i.e. are numerically equivalent). Then do the Cartesian products $\prod_{\alpha \in J} A_\alpha$ and $\prod_{\alpha \in J} B_\alpha$ also have the same cardinality?
My Attempt:

The answer is yes. The proof goes as follows:

For each $\alpha \in J$, as $A_\alpha \sim B_\alpha$, so we can find a bijective function $f_\alpha \colon A_\alpha \longrightarrow B_\alpha$. Now let $\mathbf{f} \colon \prod_{\alpha \in J} A_\alpha \longrightarrow \prod_{\alpha \in J} B_\alpha$ be the function defined by the formula
$$
\mathbf{f} \left( \left( a_\alpha \right)_{\alpha \in J} \right) := \left( f_\alpha \left( a_\alpha \right) \right)_{\alpha \in J}.
$$

We show that this function $\mathbf{f}$ is also bijective.

Let $\left( a_\alpha \right)_{\alpha \in J}$ and $\left( a_\alpha^\prime \right)_{\alpha \in J}$ be any two $J$-tuples (i.e. elements) of $\prod_{\alpha \in J} A_\alpha$ such that
$$
\mathbf{f} \left( \left( a_\alpha \right)_{\alpha \in J} \right) = \mathbf{f} \left( \left( a_\alpha^\prime \right)_{\alpha \in J} \right),
$$
that is, such that
$$
\left( f_\alpha \left( a_\alpha \right) \right)_{\alpha \in J} = \left( f_\alpha \left( a_\alpha^\prime  \right) \right)_{\alpha \in J}.
$$
Then, for each $\alpha \in J$, we have
$$
f_\alpha \left( a_\alpha \right) = f_\alpha \left( a_\alpha^\prime \right),
$$
and since $a_\alpha, a_\alpha^\prime \in A_\alpha$ and since the function $f_\alpha \colon A_\alpha \longrightarrow B_\alpha$ is injective, therefore we can conclude that $a_\alpha = a_\alpha^\prime$ for each $\alpha \in J$; hence we have
$$
\left( a_\alpha \right)_{\alpha \in J} = \left( a_\alpha^\prime \right)_{\alpha \in J},
$$
thus showing that $\mathbf{f}$ is injective.

Let $\mathbf{b} \colon= \left( b_\alpha \right)_{\alpha \in J}$ be any element of $\prod_{\alpha \in J} B_\alpha$. We show that there exists an element $\mathbf{a} \in \prod_{\alpha \in J} A_\alpha$ such that $$ \mathbf{b} = \mathbf{f} ( \mathbf{a} ). $$

For each $\alpha \in J$, as $b_\alpha \in B_\alpha$ and as the function $f_\alpha \colon A_\alpha \longrightarrow B_\alpha$ is surjective, so there exists an element $a_\alpha \in A_\alpha$ such that
$$
b_\alpha = f_\alpha \left( a_\alpha \right).
$$
Let us put
$$
\mathbf{a} := \left( a_\alpha \right)_{\alpha \in J}.
$$
This $\mathbf{a} \in \prod_{\alpha \in J} A_\alpha$ of course, and furthermore we also have
$$
\mathbf{f} ( \mathbf{a} ) = \mathbf{b},
$$
thus showing that $\mathbf{f}$ is surjective.

Thus we have shown that
$$
\prod_{\alpha \in J} A_\alpha \sim \prod_{\alpha \in J} B_\alpha.
$$

Is this proof correct and clear enough? If so, then how about the following generalisation of the above result?

Let $I$ and $J$ be any two (non-empty) sets of indices such that $I \sim J$, and let $\left\{ A_\alpha \right\}_{\alpha \in I}$ and $\left\{ B_\beta \right\}_{\beta \in J}$ be any two indexed families of sets such that, for each $\alpha \in I$, we have $A_\alpha \sim B_{\varphi(\alpha)}$, where $\varphi \colon I \longrightarrow J$ is a bijective function. Then
$$
\prod_{\alpha \in I} A_\alpha \sim \prod_{\beta \in J} B_\beta.
$$

Does the result as I have just stated also hold?


text: Q: What is the definition of the Euler characteristic of a stack? I've heard people talk about the Euler characteristic of a stack, and I understand that it is sometimes fractional. This tells me that it is not defined in any usual sense like $\sum (-1)^i\dim H^i(X)$. What is the definition? What are good references for this? What is the inspiration for the definition?


text:
Q: Well-Ordering Principle to Show All fractions can be written in lowest terms This is from Class Note from 6.042 ocw courses at MIT:
"Well Ordering Principle" section:
You can read the original here at page 1 and 2; Well Ordering Principle: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/readings/MIT6_042JF10_chap03.pdf

In fact, looking back, we took the Well Ordering Principle for granted
  in proving that $\sqrt{2}$ is irrational. That
  proof assumed that for any positive integers $m$ and $n$, the fraction $\frac{m}{n}$
  can be written in lowest terms, that is, in the form $\frac{m'}{n'}$ where $m'$
  and $n'$ are positive integers with no common factors. How do we know
  this is always possible?
Suppose to the contrary that there were $m$, $n$ in $\mathbb{Z}^+$ such that the fraction $\frac{m}{n}$ cannot be written in lowest
  terms. Now let $C$ be the set of positive integers that are numerators
  of such fractions. Then $m$ in $C$, so $C$ is nonempty. Therefore, by Well
  Ordering, there must be a smallest integer, $m_0$ in $C$. So by definition of
  $C$, there is an integer $n_0 > 0$ such that the fraction $\frac{m_0}{n_0}$ cannot be
  written in lowest terms. This means that $m_0$ and $n_0$ must have a common
  factor, $p > 1$. But
$(\frac{m_0}{p}) / (\frac{n_0}{p}) = \frac{m_0}{n_0}$
so any way of expressing the left hand fraction in lowest terms would
  also work for $\frac{m_0}{n_0}$, which implies the fraction($\frac{m_0}{p}) / (\frac{n_0}{p})$ cannot be in written in lowest terms either.
So by definition of $C$, the numerator, $\frac{m_0}{p}$, is in $C$. But $\frac{m_0}{p} < m_0$,
  which contradicts the fact that $m_0$ is the smallest element of $C$. Since
  the assumption that $C$ is nonempty leads to a contradiction, it follows
  that $C$ must be empty. That is, that there are no numerators of
  fractions that can't be written in lowest terms, and hence there are
  no such fractions at all.

I don't really understand the part where, the author says:

This means that $m_0$ and $n_0$ must have a common factor, $p > 1$ .

BECAUSE $\frac {m_0}  {n_0}$ is a irreducible fraction, both $m_0$ and $n_0$ have no common factors other than 1. If they had common factors other than one, then $\frac {m_0}  {n_0}$ would not be a irreducible fraction. I think that IT IS NOT THE CASE THAT $m_0$ and $n_0$ must have a common factor, $p > 1$.
Let that fraction be $2/3$, $2/3$ is irreducible. 2 and 3 have no common factors other than $1$.
I assume that if a fraction cannot be written in lowest terms, then the fraction is irreducible, i.e. something like one half.

If you didn't want to access MIT. look no further

A: $m_0$ and $n_0$ are defined so that $m_0/n_0$ cannot be written in lowest terms. This means by definition that they have a common factor (since if they didn't, then $m_0/n_0$ would already be in lowest terms, so can be written in lowest terms). I think you're confusing 'irreducible' with 'cannot be written in lowest terms'. These are actually quite different and mutually exclusive. (The fact that the second property is a hypothetical one that the author is proving cannot occur, and that no such $m_0$ and $n_0$ actually exist probably makes it more difficult.)

A: The proof is needlessly complex. We claim that every fraction $f$ can be written irreducibly, i.e. $\,f = a/b\,$ where $a,b$ are coprime. Indeed, by well ordering, there exists a representation $ f = a/b $ with $\rm\color{#c00}{least}$ denominator $b$. If $a,b$ were not coprime then we could cancel a common factor $d>1$ from $a,b$ yielding an equal fraction with smaller denominator $b/d < b\,$ contra $\rm\color{#c00}{least}$ness of $b$.


text:
Q: Steve Hsu's calculation of geniuses in China On his blog, physicist Steve Hsu wrote the following:

Assuming a normal distribution, there are only about 10,000 people in the US who perform at +4SD and a similar number in Europe, so this is quite a select population (roughly, the top few hundred high school seniors each year in the US).
If you extrapolate the NE Asian numbers to the 1.3 billion population of China you get something like 300,000 individuals at this level, which is pretty overwhelming.

Can you explain Steve's statement in plain English – to non-statisticians using only common arithmetic operators like $+$, and $-$?

A: Steve Hsu is using the augmented 68–95–99.7 rule to calculate what fraction of the population lies within 4 standard deviations of the mean, assuming IQ has a normal distribution.
Given how these tests are constructed, the mean IQ is around 100 with standard deviation of 15. Standard deviation is a standard measure of spread for data (denoted by the Greek letter $\sigma$). If it is small, everyone's score will be clustered tightly around $100$. If it is large, scores will be more dispersed.
Using the Wiki table linked above, we can see that about 0.999936657516334 of the population will have IQ between $100-4 \cdot 15=40$ and $100+4 \cdot 15=160$ (plus or minus 4 standard deviations from the mean). That leaves $$1-0.999936657516334=0.00006334$$ with scores below 40 and above 160. We only care about geniuses, so that gets cut in half to $0.00003167$ (since the distribution is assumed to be symmetric). If the US has a population of 322 million, that gives us $0.5 \cdot (1-0.999936657516334) \cdot 322,000,000 = 10,198$ geniuses.
To get the Chinese numbers, he's assuming that they have the same standard deviation, but a mean that is $0.5$ standard deviations higher (so $107.5$). This is grounded in the NE Asian PISA tests results, which are more of a scholastic achievement test rather than a test of IQ. The two assumptions are that achievement score distribution looks like the IQ distribution and that the Chinese resemble NE Asians.
Assuming this is the case, this means that to make it over 160, you only need (160-107.5)/15=3.5 standard deviations instead of 4. Using the 3.5 $\sigma$ row in the Wiki table, this gives $$0.5 \cdot (1-0.999534741841929)\cdot 1,300,000,000=302,418$$ geniuses, which is fairly close to SH's estimate.


text:
Q: Shell.Application & errors To clarify, I am specifically asking about how to HANDLE errors when using Shell.Application. Or more to the point, CAN one handle errors, and IF SO, how. The font example is just that, an example of the current situation I am trying to solve. But the question remains, can one handle (not avoid, handle) an error when using Shell.Application? There may well be some subtlety to the answer, I.e in general you can, but specifically not in the fonts example. That seems to be the case, and I am inclined to decide that Shell.Application is old, broken technology that should simply not be used, because it can't be robust in all use cases, which to me says it's potentially fragile in any use case.
I am attempting to refine my use of Shell.Application.CopyHere(), specifically for use installing fonts. What I hope to do is address the occasional error where a font file is corrupt or otherwise not a valid font file.
So far as I can tell from this there really is no way to address this. I can use argument value 16 Respond with "Yes to All" for any dialog box that is displayed. to perhaps get past the error, but with no return code I have no way to log a resulting error. Using .CopyHere() in PowerShell with a Try/Catch doesn't work either. Is this just old technology from a time when Microsoft just accepted things failing ungracefully? Or am I missing a technique that solves the issue?
EDIT: Based on that link I provided, I tried the 1024 argument, Do not display a user interface if an error occurs. Like so
$fontFolder.CopyHere($fontFilePath, 1024)

Doesn't seem to do what it says it does, since I am seeing a dialog that says
Cannot install bogus.ttf
The file ... does not appear to be a valid font.

So, not only not able to get a meaningful error back, but the presence of an error disrupts execution of the script and requires user interaction. Ugh.
EDIT 2:
Not really a minimal code example, since my question is CAN this be done, even before how. But this is what I just tried.
fontFilePath = '\\px\Rollouts\Misc\Fonts\bogus.ttf'
$fontFolderPath = "$env:windir\Fonts"
$fontFolder = $(New-Object -ComObject:Shell.Application).Namespace($fontFolderPath)
$fontFolder.CopyHere($fontFilePath, 1024)

Based on what that 1024 argument claims to do, I would expect this to fail, but also not stop processing while a dialog waits for user interaction.
Also, worth noting that bogus.ttf is simply an empty text file renamed with TTF extension. So, guaranteed not to successfully install a font.

A: It seems that the Fonts folder, while it does implement Folder.CopyHere, does not evaluate the flags passed in the second parameter. Doesn't seem there are any other standard utilities to install fonts programmatically, or verify the integrity of the TTF non-interactively.
So this leaves us the option of rolling our own Font registration using the Win32 API. Basically, you have to copy the font to the Fonts folder:
# For .NET versions earlier than 4.0, hardcode to C:\Windows\Fonts
# Fonts special folder is new in 4.0
$fontDir = [System.Environment]::GetFolderPath([System.Environment.SpecialFolder]::Fonts)
Copy-Item C:\Path\To\Font.ttf "${fontDir}\Font.ttf"

This next call isn't strictly necessary, as it only adds the font temporarily to your user session, but it does function as an integrity check to see if the font is valid and can be imported. You need to P/Invoke AddFontResource from the Win32 API:
Add-Type -Name Gdi32 -Namespace Win32 -MemberDefinition @"
  [System.Runtime.InteropServices.DllImport("gdi32.dll")]
  public static extern int AddFontResource(string lpszFilename);
"@

# Returns 1 on success or 0 on failure, if you want your error checking here
[Win32.Gdi32]::AddFontResource("${fontDir}\FontFileName.ttf")

And then register it at the following registry key. This piece is necessary for persisting the font you copied to $fontDir:
New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts' -Name "FontName" -Value "FontFileName.ttf"

You can programmatically get the FontName using the PrivateFontCollection class, and the Families[x].Name property under that, where x is the index of the font in the collection you want the name for.

To address your edit, there isn't going to be a "one size fits all" approach when it comes to handling errors in Shell.Application. There are multiple reasons to avoid using Shell.Application, such as:

*

*APIs are wrought with legacy behavior, such as using modal dialogs to report errors

*Windows standards are implemented inconsistently, such as Fonts ignoring the documented CopyFile flags

*Not available in a non-interactive session

The first two points are cases the example in your question hits. The third comes into play in many automation scenarios, especially when a non-interactive service accounts are used to execute commands. There are very few cases where something can only be done via Shell.Application, and as such it's almost always best to avoid it if there is an alternative API. Your font installation scenario is an excellent example of this.


text:
Q: Can Perl output runtime errors for unitialized variable references, instead of silently exiting the script? I use Perl v5.22.1 on Windows 10 x64.
My scripts contain
use strict;
use warnings "all";

I sometimes find that due to my error, an undefined variable is referenced.  My experience is that Perl silently exits the script without displaying any error or warning.
Are there any additional settings or options that would enable warnings about referencing uninitialized variables?
I found some guidance on setting exit codes here, but I would prefer an actual error or warning naming the variable if that is possible.

A: There are three ways the Perl interpreter will cause a program to exit:

*

*By throwing an exception. If this exception is uncaught, the stringification of the exception will be printed to STDERR, and the program will exit.

*By encountering a severe condition. A message (possibly including the word "panic") will be printed to STDERR, and the program will exit.

*In response to a call to exit or by reaching the end of the program. No message will be output by the Perl interpreter since it didn't initiate the exit (and thus has no way of knowing why the programmed exited).

A program will also exit if killed by the OS (e.g. in response to some uncaught signals).
So, in all cases where the Perl interpreter initiates the exit, it already outputs a message.
So, you are requesting that Perl does what Perl already does.
So, your request is moot.


text:
Q: iPhone functionality with images, click thumbnail and display large image Hi there I am developing a mobile site (NOT AN APP) for an iPhone.
This is a really noob question though I have searched and not really found what I am looking for, as I am not sure which exact search terms to use.
On an iPhone when you click an image it shows that image larger on the screen so you can zoom in/out.
I am using generated thumbnails that are a lot smaller than the original image, how do I load in a full resoloution image when a thumbnail is clicked?
again sorry for the noob question, if someone can point me in the right direction, part of the problem is that I have NO experience of mobile websites or iphone functionality, I will keep playing with jquery mobile and see where I get with that.

A: When you click on the thumbnail, you may redirect the user to an another HTML page where is include the image with a max-width and max-height in %.
In mobile, it's better to have a design in % to adapt the design at all mobiles screen.
<img src="myImage.jpg" alt="myImage" id="myImg" />

And in CSS
#myImg{
max-height:100%;
max-width: 100%;
}

You have others solutions, by using jQuery plugins too : http://fancybox.net/


text: Q: I need to be able to make a video player that detects n number of video files in a folder and play it one after another in kivy I need to be able to make a video player that detects n number of video files in a folder and play it one after another in kivy. I am very new in this so pardon my ignorance. thanks a advance


text:
Q: Returning default value from function when result is error Is there something similar to the ? shortcut which instead of returning a result from a function when there is an error, returns a predefined value?
Basically I want to know if it is possible to do the following in one line:
fn index() -> String {
    let temp = some_func("pass"); // some_func returns a Result
    if temp.is_err() {
        return "No parameters named pass".to_string();
    }
    try_decrypt_data(temp.unwrap())
}

I tried using unwrap_or_else(), but that just returns the closure not the outer function. i.e.
try_decrypt_data(params.get("pass").unwrap_or_else(|| return "No parameters named pass".to_string(); )) // This doesn't work

A: This is kind of possible, but usually not a good idea, especially not in your example (I will explain that later).
You cannot easily return a String and make ? return a default value, but you can define your own string type and implement std::ops::Try for it. Note that Try is still unstable!
Let's see how this would work:
// Just wrap a string
struct StringlyResult {
    s: String,
}

// Convenience conversion
impl From<String> for StringlyResult {
    fn from(s: String) -> Self {
        Self { s }
    }
}

// The impl that allows us to use the ? operator
impl std::ops::Try for StringlyResult {
    type Ok = String;
    type Error = String;

    fn into_result(self) -> Result<Self::Ok, Self::Error> {
        if self.s == "No parameters named pass" {
            Err(self.s)
        } else {
            Ok(self.s)
        }
    }

    fn from_error(s: Self::Error) -> Self {
        if s != "No parameters named pass" {
            panic!("wat");
        }
        Self { s }
    }

    fn from_ok(s: Self::Ok) -> Self {
        if s == "No parameters named pass" {
            panic!("wat");
        }
        Self { s }
    }
}

With that we can implement index() like this:
fn index() -> StringlyResult {
    let temp = some_func("pass")
        .map_err(|_| "No parameters named pass")?;
    try_decrypt_data(&temp).into()
}

(Complete code on the Playground)
So yes, the Try trait enables users to use the ? operator with their own types.

However, as presented in your example, this is a terrible idea. You probably already noticed the "wat" sections in my code above. The problem is that your OK-type already exhausts the whole type (all instances of the type are valid OK-instances).
Consider a function get_file_size() -> u64. Now this function can fail (i.e. it cannot determine the file size). You couldn't just return 0 to signal a failure occurred. How would the caller of your function distinguish between an environment in which the function cannot determine the file size and an environment where there the file is actually 0 bytes large?
Similarly, how would the caller of your function distinguish the situation in which an error occurred and the situation in which the decrypted text is literally "No parameters named pass"? The caller can't! And that's bad.
Notice that there is something similar, which is not as bad, but still not really idiomatic in Rust: get_file_size() -> i64. Here, we could return -1 to signal a failure. And this is less bad because -1 can never be a valid file size! (in other words, not all instances of your type are valid OK-instances). However, in this case it is still super easy to forget to check for errors. That's why in Rust, we always want to use Result.

To make error handling easier, consider using the crate failure. With that, you can easily use strings as error messages without sacrificing type safety or sanity of your program. Example:
use failure::{Error, ResultExt};

fn index() -> Result<String, Error> {
    let temp = some_func("pass")
        .context("No parameters named pass")?;
    Ok(try_decrypt_data(&temp)?)
}

A: I would create an inner function that uses a Result. This allows you to use the question-mark operator for the various error messages / default values that you'd like to return. You can then call the inner function and take either the success value or error value:
fn index() -> String {
    fn inner() -> Result<String, String> {
        let t1 = some_func("pass").map_err(|_| "No parameters named pass")?;
        let t2 = some_func2(t1).map_err(|_| "A second error")?;
        let t3 = some_func3(t2).map_err(|_| "A third error")?;
        Ok(t3)
    }

    match inner() {
        Ok(v) => v,
        Err(v) => v,
    }
}

There's an unstable feature called try blocks that promises to make this slightly less bulky:
#![feature(try_blocks)]

fn index() -> String {
    let v = try {
        let t1 = some_func("pass").map_err(|_| "No parameters named pass")?;
        let t2 = some_func2(t1).map_err(|_| "A second error")?;
        some_func3(t2).map_err(|_| "A third error")?
    };

    match v {
        Ok(v) => v,
        Err(v) => v,
    }
}

A: There is no such utility, but you can always write a macro:
macro_rules! return_if_err {
    ( $to_test:expr, $default:expr ) => (
        if $to_test.is_err() {
            return $default;
        }
    )
}

fn pop_or_default(mut v: Vec<i32>) -> i32 {
    let result = v.pop();
    return_if_err!(result.ok_or(()), 123);

    result.unwrap()
}

fn main() {
    assert_eq!(pop_or_default(vec![]), 123);
}

You cannot return from an outer scope from a closure.


text:
Q: RegEx to match a number in the second line I need a regex to match a number in the second line. Similar input is like this:
^C1.1
xC20
SS3
M 4

Decimal pattern (-?\d+(\.\d+)?) matches all numbers and second number can be get in a loop on the code behind but I need a regular expression to get directly the number in the second line.

A: /^[^\r\n]*\r?\n\D*?(-?\d+(\.\d+)?)/

This operates by capturing a single line at the beginning of the input:
^         Beginning of the string
[^\r\n]*  Anything that isn't a line terminator
\r?\n     A newline, optionally preceded by a carriage return

Then  all the non digit characters, then your numbers.
Since you've now repeatedly changed your needs, try this on for size:
/(?<=\n\D*)-?\d+(\.\d+)?/

A: I was able to capture it with this regex.
.*\n\D*(\d*).*\n

A: Check out group 1 of anything that this matches:
^.*?\r\n.*?(\d+)

If that doesn't work, try this:
^.*?\r\n.*?(\d+)

Both are with multiline NOT set...

A: I would probably use the captured group in /^.*?\r?\n.*?(-?\d+(?:\.\d+)?)/ where…
^                  # beginning of string
.*?                # anything...
\r?\n              # followed by a new line
.*?                # anything...
(                  # followed by...
   -?              # an optional negative sign (minus)
   \d+             # a number
   (?:             #   -this part not captured explicitly-
       \.\d+       # a dot and a number
   )?              #   -and is optional-
)

If it is a flavor that supports lookbehind then there are other alternatives.


text: Q: How to convert word document to PDF in SharePoint 2016 Is it possible to convert a word document to PDF on SharePoint 2016 using custom code such as JavaScript ? I have heard of Word Automation Services but I am looking for custom code solutions that would run on a click of a button. Example, Click on a button and the word document automatically is converted to a PDF document.


text:
Q: Protect specific directories with .htaccess Is it possible to protect specific directories with a single .htaccess and .htpasswd file?
I can only seam to find the ability to protect single files, or an entire directory (and it's sub directories)?
E.g .htpasswd in /public_html/myfolder
and protect
/public_html/myfolder/secret
/public_html/myfolder/admin
but not
/public_html/myfolder/mypublicfiles

A: htaccess files are a per directory options, it's sort of like a <Directory> block but defined by where you put the htaccess file. So you can't arbitrarily setup HTTP authentication on a directory other than the directory that the htaccess file is in.


text:
Q: Using yield without return type I have a big long looping procedure like this:
public void Process()
{
    bool done = false;
    do {
        //do stuff
    }while (!done);
}

that I'd like to chop into bits and have the calling routine display my progress in some sort of UI. It's a class library, so the caller may be anything (Console App, WinForms, WebApp, ...).
It would be easiest if I could do:
public void Process()
{
    bool done = false;
    do {
        //do stuff
        yield return;
    }while (!done);
}

So the caller could keep calling the method until it's done.
This smells more like a job for BackgroundWorker, but that seems "wrong" for a Console App... I won't always NEED multithreading. Or does it? I mean, yeah, I could just have the console's main thread just wait for it to finish.
My question is: Can I use the "piecemeal" deferred execution functionality of "yield return" without actually returning something?

A: As already someone else answered, no that's not the way to go, but why don't you simply use a callback Func or Action or something to let the callee interact with your loop?
public void Process(Action callback)
{
    bool done = false;
    do {
        //do stuff
        callback();
    }while (!done);
}

Or use some other kind of event handling which is typically used for stuff like that.

A: You say you want the caller to respond to progress of the method. You could return progress information:
class ProgressInfo { ... }
...
yield return new ProgressInfo() { ... };

The caller would then foreach over the results and act on them.
This is much nicer than having the caller examine global mutable state. This is a functional solution.

A: No, not possible. Compiler generates iterators for you only when the return type is IEnumerable or IEnumerator.
A workaround would be return some value and change the return type of the method to make compiler happy.

A: The language feature you want is called a coroutine (or, more precisely, a semicoroutine, but let's not be pedantic.) C# iterator blocks are a weak form of coroutine. I recommend against making "dummy" sequences just because you want coroutines.
The await operator in C# 5 is also a form of coroutine and might more closely resemble your desired solution, particularly if your operation is logically an asynchronous, high-latency operation. There are standard patterns for progress reporting with asynchronous coroutines in C# 5; I would start by reading this:
http://blogs.msdn.com/b/dotnet/archive/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis.aspx

A: In short, no.
yield return has to return something.
http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx
The Process method should have a return type of IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>. You may return dummy objects if you really want to use yield.
You might want to investigate different ways to report progress to the caller.


text:
Q: Compress and Decompress a String How to compress strings like "aaabbbc" to "a3b3c" and decompress the same, without using extra memory during processing, primarily in C and also in Java?

A: To do an in-place encoding, the encoded string must never be longer than the original string. Suppose we assume the following encoding rules:

*

*No numeric digits in the original string (so no count delimiter characters are needed)

*A run length of 1 is never explicitly coded (so abc remains abc)

I believe that with these assumptions, a run-length encoding is not ambiguous and will never be longer than the string itself. Then the following algorithm (pseudocode) should do the job of encoding in place:
currentChar ← string[0]
nextOutputPos ← 1
nextReadPos ← 1
count ← 1
while (nextReadPos < length of string) {
    nextChar ← string[nextReadPos++];
    if (nextChar == currentChar) {
        count++;
    } else {
        if (count > 1) {
            write (count as a string) to string at position nextOutputPos
            nextOutputPos ← nextOutputPos + (length of count as a string)
        }
        string[nextOutputPos++] ← currentChar ← nextChar;
    }
}

At the end, the encoded string is contained in the half-open range [0, nextOutputPos) of string.

A: A simple reverse scan does provide a (seemingly) good solution to the encoding part at least. I am doing one scan from right to left and overwriting the portions of the string with the occurrence count.
char * enc(char * ip)
{
    int r,op;
    int l=strlen(ip);
    r=l-1;
    char curr;
    op=r;
    int curr_count=1,mod_curr_count;
    while(r>=0)
    {
        curr=ip[r];

        while(ip[--r]==curr)
        {

            curr_count++;
        }
        if(curr_count!=1)
        {
            while(curr_count)
            {
            mod_curr_count=curr_count%10;
            ip[op--]=(char)(mod_curr_count+48);
            curr_count/=10;
            }
            ip[op--]=curr;
            curr_count=1;

        }
        else
        {
        ip[op--]=curr;
        }
    }

    ip=ip+op+1;
    return ip;
}

Input : aaaaaaaaaaaabbbfffffffffffffffqqqqqqqqqqqqqqqqqqccccpoii
Output: a12b3f15q18c4poi2

A: Here's a possibility in Java, making use of regular expressions:
String str = "aaabbbc";  // string to be encoded

StringBuilder sb = new StringBuilder();  // to hold encoded string

for (String s : str.split("(?<=(.))(?!\\1)")) {
    sb.append(s.charAt(0));
    if (s.length() > 1) // only append length if it's > 1
        sb.append(s.length());
}

System.out.println(sb.toString());

a3b3c


text:
Q: How to use GetById function in c# I am learning c#. I am trying to create a basic list in a mock repository (Rather than jumping into pulling data from SQL straight away). I have a list that contains cars and has fields such as Id, Model, Make, description etc.
I am then trying to create a method in my Car.CS class, of which gets the car by Id. For example if i pass in the ID of the car, it will return the other details of the car.
Unfortunately when i run the console application, it just returns blank in the console? Could someone let me know where i'm going wrong please?
First of all i have an ICarRepository
namespace GeneralConsoleApp
{
    interface ICarRepository
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
    }
}

and then i have my MockCarRepository of which contains the list
namespace GeneralConsoleApp
{
    class MockCarRepository : ICarRepository
    {
        public IEnumerable<Car> Cars =>
            new List<Car>
            {
                new Car {Id = 1, Name="BMW", Price=23000.00M, Description="BMW car" }
            };

        public int Id { get; set; }
        public string Name {get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
    }
}

Next is my Car.cs
namespace GeneralConsoleApp
{
    class Car
    {
        private readonly List<Car> CarList = new List<Car>();

        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Description { get; set; }

        public Car GetCarById(int Id)
        {
            return CarList.FirstOrDefault(z => z.Id == Id);

        }
    }
}

And finally my program.cs main method
namespace GeneralConsoleApp
{
    class Program
    {

        static void Main()
        {
            Car car = new Car();

            Console.WriteLine(car.GetCarById(1));

            Console.ReadLine();
        }
    }
}

A: Your Car class does not use MockCarRepository but has it's own empty list instead (CarList).
You should either populate the list in the Car or use the mock repository there.

A: You problem is that your Car class has a list of Car types from which you are returning a value to the console.
You should be returning a value from the Repository instead.
nammespace GeneralConsoleApp
{
    class MockCarRepository : ICarRepository
    {
           public IEnumerable<Car> Cars => new List<Car>
           {
                   new Car {Id = 1, Name="BMW", Price=23000.00M, Description="BMW car" }
           };

           public Car GetCarById(int Id)
           {
             return Cars.FirstOrDefault(z => z.Id == Id);
           }
    }
    class Program
    {
        static void Main()
        {
            var Repository = new MockRepository();

            Console.WriteLine(Repository.GetCarById(1));

        }
    }
}

A: The CarList is an empty list and that's the reason of having no output.
Change main call to
MockCarRepository car = new MockCarRepository();
Console.WriteLine(car.GetCarById(1).Name);

and you will see the difference.

A: You should do it something like
ICarRepository repository= new MockCarRepository();
CarService carService= new CarService(repository);
Console.WriteLine(carService.GetCarById(1));

You would need to add CarService class which can inject the mock repository or actual database repository and modify Car class to be a model.
    class CarService
    {
        private readonly ICarRepository _repository;
        public CarService(ICarRepository repository)
        {
           _repository=repository;
        }

        public Car GetCarById(int Id)
        {
            return _repositoy.GetCarById(id);
        }
    }

    class Car
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Description { get; set; }
    }
    interface ICarRepository
    {
        Car GetCarById(int Id);
    }
    class MockCarRepository : ICarRepository
    {
        public IEnumerable<Car> Cars =>
            new List<Car>
            {
                new Car {Id = 1, Name="BMW", Price=23000.00M, Description="BMW car" }
            };
        public Car GetCarById(int Id)
        {
            return Cars.First(z => z.Id == Id);
        }
    }

A: A few issues here regarding separation of concerns. Your Car model just needs to model the properties associated with a Car.
Likewise your CarRepository should contain just the methods needed to perform queries against your data store, like
GetCarById(int id)

or
IEnumerable<Car> FindByManufacturer(string manufacturer);

In terms of mocking your data store, you would create a class specifically for mocking, like MockCarRepository, and then at run-time you can instantiate it. The reason this is super useful, is that because you ultimately programming against the interface ICarRepository, when you are ready to use real data, all you need to do is create a new implementation of your ICarRepository, using whatever store you want, native SQL Connection, EntityFramework, CosmosDB etc. and just change where you are instantiating your type to satisfy the ICarRepository.
I would recommend you look into SOLID design principals - great resource below, which explains things far better than I could.
https://learn.microsoft.com/en-us/archive/msdn-magazine/2014/may/csharp-best-practices-dangers-of-violating-solid-principles-in-csharp
With a few small tweaks you could use something like the below.
namespace GeneralConsoleApp
{
interface ICarRepository
{
    Car GetCarById(int id);
}

class MockCarRepository : ICarRepository
{
    private List<Car> _mockCars;

    public MockCarRepository()
    {
        _mockCars = new List<Car>
        {
            new Car {Id = 1, Name="BMW", Price=23000.00M, Description="BMW car" }
        };
    }

    public Car GetCarById(int id)
    {
        return _mockCars.FirstOrDefault(v => v.Id == id);
    }
}

class SqlCarRepository : ICarRepository
{
    private readonly string _connectionString;

    public SqlCarRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public Car GetCarById(int id)
    {
        // use the _connectionString to create your database connection.
        var car = FROM DATABASE;
        return car;
    }
}

class Car
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        // All repositories should implement ICarRepository
        // meaning switching repo implementation is a one line change below, a DI container adjustment, or some sort of strategy pattern.
        ICarRepository mockRepo = new MockCarRepository();;

        var carFound = mockRepo.GetCarById(1);

        Console.WriteLine("Found car: " + carFound.Description);

        Console.ReadLine();

    }
}

}


text:
Q: Check if row exists in database table using SQLAlchemy I am learning SQLAlchemy and trying to check if a record exists in postgreSQL database using SQLAlchemy. There are many similar question here, but I am stuck. Here is my query:
ret = session.query(exists().where(COMPANY.name == 'MyTestCompany')).scalar()

"COMPANY" is table name , when I run it, I get error:
"NameError: name 'COMPANY' is not defined"

Should I somehow "register" COMPANY table as an object in current session or the problem lies somewhere else?

A: The error you are getting means there is no COMPANY variable defined in your python code.
Did you use any other ORM features? Usually you would need to create a Company Model to run a query like this. A model would look something like this:
class Company(Base):
    __tablename__ = 'company'
    id = Column(Integer, primary_key=True)
    name = Column(String)

Check out how they create a User model in this tutorial
If you want to interact with SQL directly without ORM features you might be interested in SQLAlchemy Core


text:
Q: Build failure when adding jar file directly in java build path in maven based project and not adding its entry in pom file? I have a maven based project. And I have few dependencies that are our custom dependencies.
Now till now, if I add these dependencies in java build path and make their entry in pom file using
   <dependency>
        <groupId>abc</groupId>
        <artifactId>abc</artifactId>
        <scope>system</scope>
        <version>1.0</version>
        <systemPath>${basedir}\src\lib\abc.jar</systemPath>
    </dependency>

And make project build then it works fine.
But as I tried by removing its entry in pom file, as I have already added in java build path build fails with error's
package com.abc does not exist
I want to know why it is failing as by adding entries in java build path in dynamic java project (not maven), it works fine and build gets created.
I have dependency like this

A: Maven wants dependencies in repositories.  Using the system scope will cause interesting forms of pain down the road!
First, if you can locate mavenized versions of the jars you use, then switch to those.  If not, then install them to your local repository (.m2 folder) with mvn install:install-fileor your in-house Maven repository (Nexus, Artifactory etc).
At the time where I had a similar situation I ended up doing the install as part of the build which worked well as a temporary solution.   You can see the accepted answer at https://stackoverflow.com/a/10803426/53897


text:
Q: I need help centering a ul item within a div containing a 100% width background I am new to html and css. I am currently taking a class on html5 and css3. We are required to create a website for the class. I have started creating the layout and I am having trouble getting the navigation at the top to be centered on the page. There is a Ul with a 100% background but I cannont get the buttons (text) to be centered without the Ul no longer being 100% width. `
Here is my CSS code:
#horizontalNav {
    display: block;
}

#horizontalNav li {
    float: left;
    margin-left: 13px;
    margin-right: 30px;
}

#horizontalNav ul {
    overflow: hidden;
    background-color: #003300;
    width: 100%;
    margin: 0;
    padding: 0;
    list-style-type: none;
}

/* Button Styles*/
#horizontalNav a.navBtn {
    color: #009933;
    font-size: 1.8em;
    text-decoration: none;
    font-family: Impact, Charcoal, sans-serif;
}

#horizontalNav a.navBtn:hover {
    color: #FFFF99;
}

/*Drop down menu */
#horizontalNav ul li:hover ul {
    display: block;
}

#horizontalNav ul ul {
    display: none;
    position: absolute;
    min-width: 150px;
    max-width: 150px;
    padding-top: 2px;
    padding-bottom: 8px;
    margin-left: -10px;
}

#horizontalNav ul ul li {
    display: block;
    clear: both;
}

#horizontalNav ul ul li a {
    color: #009933;
    font-size: 1.4em;
    font-family: Impact, Charcoal, sans-serif;
    text-decoration: none;
}

#horizontalNav ul ul li a:hover {
    color: #FFFF99;
}`

A: As my comment stated, you cannot center floated elements. Use display: inline-block;
Change
#horizontalNav li {
    float: left;
    margin-left: 13px;
    margin-right: 30px;
}

to
#horizontalNav li {
    display: inline-block;
    margin-left: 13px;
    margin-right: 30px;
}


text:
Q: Window service need access to shared folder I have a window service that needs to check file in a shared folder.  It looks like it cannot see the file.  The shared folder is on a window server 2008.  The window service is on my computer and configured as local system.  I have a console app that can see the shared folder without any problem. What do I need to do to make this work?

A: The service needs to be configured to run under the credentials of a user with permissions to the shared folder. The LocalSystem account only has permissions to the local machine. When you run your console application, it is running under your credentials.

A: Your credentials must be given to the service
First you have to give the IP of the server and their credentials then this will connect to the shared folder
directly this will be not possible
because service has no rights to access shared folder


text:
Q: WPF/C# - Throw away the Content for a Checkbox in a Datagrid TL;DR How do I make a Checkbox not draw/include the label for the content or the space required for the label?
I'm using Visual Studio in conjunction with C# and WPF.  I have a Checkbox in a DataTemplate inside of a DataGrid. My issue is that I suspect that while the Content is empty, the space for the content is still being taken up.
The end result is that I have a checkbox smashed to the left of the column, and a vast desert of whitespace to it's right
My current UI disaster looks like this:

Right now, my XAML looks like the following.  As you can see, I've tried messing around with the Horizontal and HorizontalContentAlignments with little to no luck.
 <DataGridTemplateColumn Header="Y/N">
   <DataGridTemplateColumn.CellTemplate>
     <DataTemplate>
       <CheckBox IsChecked="{Binding Path=IsSelected, UpdateSourceTrigger=PropertyChanged}"
                                  HorizontalContentAlignment="Center">
         <TextBlock>
         </TextBlock>
       </CheckBox>
     </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
 </DataGridTemplateColumn>

I've tried setting the size of the DataGridTemplateColumn but I don't see it really centering the checkbox even with the Horizontal* attributes set which makes me think it's got the space for the Label in there.
Any help on this is greatly appreciated.

A: <DataGridTemplateColumn Header="Y/N" Width="50">
   <DataGridTemplateColumn.CellTemplate>
     <DataTemplate>
       <CheckBox IsChecked="{Binding Path=IsSelected, UpdateSourceTrigger=PropertyChanged}"
                                  HorizontalContentAlignment="Center">
         <TextBlock>
         </TextBlock>
       </CheckBox>
     </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
 </DataGridTemplateColumn>

Insert Width into DataGridTemplateColumn
or
 <DataGridCheckBoxColumn Header="Y/N" Binding="{Binding Path=IsSelected, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                        </DataGridCheckBoxColumn>

You can use this way


text:
Q: Waiting for Jobs Launched by Other Jobs to Finish Goal
I'm trying to use PowerShell to process files in parallel while limiting the number of currently executing processes. If the list of files to process were known at the start of execution, a queue could be used to achieve this.
However, this script needs to accommodate files added to the "to process" directory while the script is running. The way I'm attempting to achieve this is by having each job, upon completion, remove itself and then call the function that checks for files to process/launches new jobs.
Problem
The difficulty I've encountered is getting PowerShell to wait for processing to finish before exiting.
Using Get-Job | Wait-Job appears to cause blocking. That is, the script never returns unless I manually intervene. In ISE, after $maxConcurrentJobs number of files are processed, I have to press Ctrl+C it in order to get the rest of the files processed and to allow the script to exit.
Using a while loop works as desired in PowerShell ISE. However, in PowerShell (command-line), the while loop approach only processes $maxConcurrentJobs number of files—that is, any additional files in "to process" never get processed. Apparently, when the first set of processing jobs finishes, the next set are not launched.
While ($true) {
    if ((Get-Job | Where-Object { $_.PSJobTypeName -eq 'BackgroundJob' }).Count -eq 0) { break; }
    Start-Sleep -s 1
}

Question
How can I wait for all my script's jobs to complete without the script blocking or exiting prematurely?

Code
function StartProcessingFile([IO.FileInfo]$file) {
    $destination = "$PSScriptRoot\Processed\$((get-date).ToString('yyyyMMdd-HHmmss'))-$($file.BaseName).csv"
    $inputFile = Move-Item $file.FullName -Destination $destination -PassThru

    Start-Job -Name $file.Name -ScriptBlock { param($x) Start-Sleep -s 10; } -ArgumentList $inputFile # In real life, ScriptBlock will call a PowerShell cmdlet that processes the file
}

$maxConcurrentJobs = 2;
function ProcessFiles {
    While ((Get-Job | Where-Object { $_.PSJobTypeName -eq 'BackgroundJob' }).Count -lt $maxConcurrentJobs) {
        $file = Get-ChildItem -Path "$PSScriptRoot\ToProcess" *.csv | Sort-Object -Property LastWriteTime | Select-Object -First 1
        if ($file -eq $null) { break }

        $job = StartProcessingFile($file)
        Register-ObjectEvent -InputObject $job -EventName StateChanged  -Action { Unregister-Event $eventsubscriber.SourceIdentifier; Remove-Job $eventsubscriber.SourceIdentifier; Remove-Job $eventsubscriber.SourceObject; ProcessFiles; } | Out-Null
    }
}

ProcessFiles

While ($true) {
    Get-Job
    Write-Host
    if ((Get-Job | Where-Object { $_.PSJobTypeName -eq 'BackgroundJob' }).Count -eq 0) { break; }
    Start-Sleep -s 1
}

#Get-Job | Wait-Job


text:
Q: Encode AWS KMS asymmetric key sign/verify signature to base64 and verify I am using an AWS KMS asymmetric ECC (ES256) key to sign and verify tokens using API calls in Python3. The response returns
{
    "KeyId": "arn:aws:kms:us-east-1:000000000000:key/1234",
    "Signature": "b'0D\\x02 \\x18\\xd9\\x13\\x96\\x9d\\xb00p\\xc9H\\'-\\xc6@{\\xd1V\\xf5\\xeb\\x83\"1\\x0e:\\x98\\xb4\\xea6P\\x0f\\xdf\\x82\\x02 \\x1fPt\\xc0\\x81pB\\xaa\\xe7_\\xf2~\\x91BlU\\x05\\xba1\\xe0\\xfe\\xf6\\xe4\\xebL\\nl\\xfc\\xf8\\xce\\xc6_'",
    "SigningAlgorithm": "ECDSA_SHA_256"

}
If I use AWS CLI the response "Signature" is base64 encoded:
{
    "KeyId": "arn:aws:kms:us-east-1:000000000000:key/1234",
    "Signature": "MEQCIBqjAiAnMKkugooWU6/AqCyfhQUocoiVeIIf8lL2p7YbAiBEJOl2cp9HzQNufiMBezIjZuSGW6ID13l7JSzTgLlv+g==",
    "SigningAlgorithm": "ECDSA_SHA_256"
}

Whenever I attempt to base64 encode base64.urlsafe_b64encode(string) the "Signature" using the API response in Python3, I cannot verify the signature. Here's an example of the error I receive:

An error occurred (InvalidKeyUsageException) when calling the Verify
operation: asn1: structure error: tags don't match (16 vs {class:1
tag:2 length:39 isCompound:true}) {optional:false explicit:false
application:false private:false defaultValue: tag:
stringType:0 timeType:0 set:false omitEmpty:false} ecdsaSignature @2

How can I base64 encode the "Signature" bytes string returned from the API and still be able to verify?
UPDATE:
If I update to base64.b4encode instead of base64.urlsafe_encode I get the same result:
def _sign_token(self, key_id, message):
    signature = kms_client.sign(
        KeyId=key_id,
        Message=message,
        MessageType="RAW",
        SigningAlgorithm="ECDSA_SHA_256",
    )
    logger.log(msg=signature, level=cl.log_level)
    return base64.b64encode(signature["Signature"]).decode()

log message returns:

{"asctime": "2021-04-03 19:40:27,593", "levelname": "INFO", "name":
"util.sign", "lineno": 214, "message": null, "env": "local", "KeyId":
"arn:aws:kms:us-east-1:000000000000:key/309d8dc5-409e-4f57-96a8-c71223c84dc2",
"Signature":
"b'0E\x02!\x00\xcc\x82\xf4$@?\x9e\n\xd7$\x94\x9f.\x1d5\x19{W\x1e\xcff\x8b&\xf0\xef\x88\xcf^"\xf6\xa4\x1b\x02
\x0c\x18\xab?\x93\xd5\x88Cx\xf6\x0c\x1b\xcf\xd9\xd9\xd2\xd4"\xcf\x94\xede_>\x8c\x01~J\xea\x0ezB'",
"SigningAlgorithm": "ECDSA_SHA_256", "ResponseMetadata":
{"HTTPStatusCode": 200, "HTTPHeaders": {"content-type":
"application/x-amz-json-1.1", "content-length": "233", "connection":
"close", "access-control-allow-origin": "*",
"access-control-allow-methods":
"HEAD,GET,PUT,POST,DELETE,OPTIONS,PATCH",
"access-control-allow-headers":
"authorization,content-type,content-length,content-md5,cache-control,x-amz-content-sha256,x-amz-date,x-amz-security-token,x-amz-user-agent,x-amz-target,x-amz-acl,x-amz-version-id,x-localstack-target,x-amz-tagging", "access-control-expose-headers": "x-amz-version-id", "date": "Sat, 03
Apr 2021 19:40:27 GMT", "server": "hypercorn-h11"}, "RetryAttempts":
0}}

Verify error:

"stacktrace": "An error occurred (InvalidKeyUsageException) when
calling the Verify operation: asn1: structure error: tags don't match
(16 vs {class:1 tag:13 length:69 isCompound:false}) {optional:false
explicit:false application:false private:false defaultValue:
tag: stringType:0 timeType:0 set:false omitEmpty:false}
ecdsaSignature @2"

def _verify_signature(self, key_id, message, signature):
    response = kms_client.verify(
        KeyId=key_id,
        Message=message,
        MessageType="RAW",
        Signature=signature,
        SigningAlgorithm="ECDSA_SHA_256",
    )
    logger.log(msg=response, level=cl.log_level)
    return response

client.verify requires signature to be bytes https://boto3.amazonaws.com/v1/documentation/api/1.11.4/reference/services/kms.html#KMS.Client.verify
If I leave off the .encode() I get the same:

"stacktrace": "An error occurred (InvalidKeyUsageException) when
calling the Verify operation: asn1: structure error: tags don't match
(16 vs {class:1 tag:13 length:69 isCompound:false}) {optional:false
explicit:false application:false private:false defaultValue:
tag: stringType:0 timeType:0 set:false omitEmpty:false}
ecdsaSignature @2"

def _sign_token(self, key_id, message):
    signature = kms_client.sign(
        KeyId=key_id,
        Message=message,
        MessageType="RAW",
        SigningAlgorithm="ECDSA_SHA_256",
    )
    logger.log(msg=signature, level=cl.log_level)
    return base64.b64encode(signature["Signature"])

NOTE:
If I pass the client.sign response "Signature" to client.verify without base64 encoding, verification passes.

A: The string encoded by AWS cli is not urlsafe-base64 encoded! It is encoded using the standard base64, i.e. base64.b64encode.
Standard base64 encoding uses three metacharacters /, + and =. / and + are not safe to use in either paths or query strings, and URL-safe encoding replaces these two with _ and - respectively. Since / and + are present in the AWS CLI encoded string, it can be deduced that it uses standard base64 encoding and not the URL-safe one.
The return value of base64.b64encode is bytes object. Usually Base-64 encoding is used to encode binary into text. To get the value as text instead you need to decode it (as UTF-8 into unicode string, for example):
base64_encoded_as_str = base64.b64encode(binary_value).decode()

A: The AWS support process worked. It turned out I was doing a decode() operation on the base64 encoded signature when attempting to verify instead of base64.b64decode()


text:
Q: Add item to dictionary which has same value in list of dictionary I am trying to add a key id with the same uuid.uuid4() into the inner dictionary when 'node' values are equal and a new uuid.uuid4() when a distinct uuid is found.
Let's say 2 keys ('node' in this case) have same value like-> node: 'Bangalore', so I want to generate the same ID for it and a fresh ID for every other distinct node.
This is the code I'm working on now:
import uuid
import json

node_list = [
  {
    "nodes": [
      {
         "node": "Kunal",
         "label": "PERSON"
      },
      {
         "node": "Bangalore",
         "label": "LOC"
      }
    ]
  },
  {
    "nodes": [
      {
         "node": "John",
         "label": "PERSON"
      },
      {
         "node": "Bangalore",
         "label": "LOC"
      }
    ]
  }
]

for outer_node_dict in node_list:
      for inner_dict in outer_node_dict["nodes"]:
            inner_dict['id'] = str(uuid.uuid4()) # Remember the key's value here and apply this statement somehow?

print(json.dumps(node_list, indent = True))

This is the response I want:
"[
  {
    "nodes": [
      {
         "node": "Kunal",
         "label": "PERSON",
         "id": "fbf094eb-8670-4c31-a641-4cf16c3596d1"
      },
      {
         "node": "Bangalore",
         "label": "LOC",
         "id": "24867c2a-f66a-4370-8c5d-8af5b9a25675"
      }
    ]
  },
  {
    "nodes": [
      {
         "node": "John",
         "label": "PERSON",
         "id": "5eddc375-ed3e-4f6a-81dc-3966590e8f35"
      },
      {
         "node": "Bangalore",
         "label": "LOC",
         "id": "24867c2a-f66a-4370-8c5d-8af5b9a25675"
      }
    ]
  }
]"

But currently its generating like this:
"[
 {
  "nodes": [
   {
    "node": "Kunal",
    "label": "PERSON",
    "id": "3cce6e36-9d1c-4058-a11b-2bcd0da96c83"
   },
   {
    "node": "Bangalore",
    "label": "LOC",
    "id": "4d860d3b-1835-4816-a372-050c1cc88fbb"
   }
  ]
 },
 {
  "nodes": [
   {
    "node": "John",
    "label": "PERSON",
    "id": "67fc9ba9-b591-44d4-a0ae-70503cda9dfe"
   },
   {
    "node": "Bangalore",
    "label": "LOC",
    "id": "f83025a0-7d8e-4ec8-b4a0-0bced982825f"
   }
  ]
 }
]"

How to remember key's value and apply the same ID for it in the dictionary?

A: Looks like you want the uuid to be the same for the same "node" value. So, instead of generating it, store it to a dict
node_uuids = defaultdict(lambda: uuid.uuid4())

and then, in your inner loop, instead of
inner_dict['id'] = str(uuid.uuid4())

you write
inner_dict['id'] = node_uuids[inner_dict['node']]

A complete working example is as follows:
from collections import defaultdict

import uuid
import json

node_list = [
  {
    "nodes": [
      {
         "node": "Kunal",
         "label": "PERSON"
      },
      {
         "node": "Bangalore",
         "label": "LOC"
      }
    ]
  },
  {
    "nodes": [
      {
         "node": "John",
         "label": "PERSON"
      },
      {
         "node": "Bangalore",
         "label": "LOC"
      }
    ]
  }
]

node_uuids = defaultdict(lambda: uuid.uuid4())

for outer_node_dict in node_list:
      for inner_dict in outer_node_dict["nodes"]:
            inner_dict['id'] = str(node_uuids[inner_dict['node']])

print(json.dumps(node_list, indent = True))


text:
Q: WebDriver: want to get the child elements of an element created using@FindBy I am using Page Factory and I have 2 radio buttons(male and female), both of the radio buttons have the name locator as common, name='radl', additionally 'value' of male radio button='m' and female radio button is 'f'. I need to select any one of these radio buttons based on user input.How do I get the child elements of the below "gender" element?
@FindBy(name ="radl")
WebElement gender;

A: Split up the genders into two webelements. Click the one you want.
@FindBy(css ="input[name='radl'][value='m']")
WebElement maleGender;

@FindBy(css ="input[name='radl'][value='f']")
WebElement femaleGender;


text:
Q: Find a executable file path programmatically and fast I want to find a .exe files path programatically in Java, for example:

*

*Skype.exe is entered into a program to find the direct path to it

*Program does an algorithm that finds the file path

*Program returns the file path C:\Users\Public\Desktop\Skype.exe

A method I have tried is sorting through the systems files until "skype.exe" is found, but that takes up a lot of time and resources.
Is there any hack that could make it almost instant, like maybe a Win_Api function/cmd command or is sorting through the file system until the program is found the only way?

A: I actually found something that works, albeit not the fastest but only takes around 100ms - 500ms to do depending on the exe.
You need to use a runtime process to do this.
Basically you go into the root of your drive, and then search the filesystem using these commands in the cmd.
cd \
dir /s /b mytool.exe

This will return the filepath.
My code for it:
(Hackish I know)
try {
        Process p = Runtime.getRuntime().exec("./res/getPrograms.bat " + exeName);
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while(true) {
            line = input.readLine();
            if(line == null) {
                break;
            }
            System.out.println(line);
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

And the .bat file (I am passing the parameter "eclipse.exe" to the bat file which is represented as %1):
cd \
dir /s /b %1
exit

The output becomes:
C:\Users\Mitchell\workspace\Remote Admin>cd \

C:\>dir /s /b eclipse.exe
C:\eclipse\eclipse.exe

A: As an extension to @Minor's answer, if you wanted to increase performance by limiting search to only programs that are currently "installed" on Windows, the following registry keys contain information on "installed" programs.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

Using powershell, you can access properties of installed software stored in these keys. Of particular interest is the InstallLocation property.
Then, you just modify your Java code to utilise another batch script that retrieves these install locations, and specifically target these install locations for exe files.
getInstalledPrograms.bat
@echo off
powershell -Command "Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object {$_.DisplayName -match \"%1\"} | Select-Object -Property InstallLocation"
exit

getPrograms.bat
@echo off
cd %1
dir /b /s "*%2*.exe"
exit

Java Example:
String search = "skype";
try {
    Process getInstalled = Runtime.getRuntime().exec("./src/getInstalledPrograms.bat " + search);
    BufferedReader installed = new BufferedReader(new InputStreamReader(getInstalled.getInputStream()));
    String install;
    String exe;
    int count = 0;
    while(true) {
        install = installed.readLine();
        if(install == null) {
            break;
        }
        install = install.trim();
        // Ignore powershell table header and newlines.
        if(count < 3 || install.equals("")) {
            count++;
            continue;
        }
        Process getExes = Runtime.getRuntime().exec("./src/getPrograms.bat " + "\"" + install + "\"");
        BufferedReader exes = new BufferedReader(new InputStreamReader(getExes.getInputStream()));
        while(true) {
            exe = exes.readLine();
            if(exe == null) {
                break;
            }
            exe = exe.trim();
            System.out.println(exe);
        }
    }

} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Currently my Java example duplicates InstallLocation returned by getInstalledPrograms.bat, although the script works fine in cmd. Conceptually though, this solution is sound.

A: If you want to know WHICH executable is being executed from the command line when you type .  Use the which/where commands..
Unix/linux/Mac OSX Possix
<which>
which chmod
which cd
which ls
which myprogram
returns  returns nothing if no such program file exists.
for Windows use where
<where> /?       for help on this command
If you don't have an executable but an alias or some sort of environment function/procedure/shell command..   use the <type> command on Unix/linux/Mac OS X.    That will tell yo if you are dealing with an alias, environment function, or executable.


text:
Q: multiple image upload loop only adding one image id and path database Hi every one I am trying to create an mvc application that allows the user to upload multiple photos to a folder and saves the Id and path in the database. Currently my application adds all the files to the folder but only adds the last selected image id and path to the database.
Thanks for any help with this problem
View
 @using (Html.BeginForm("Create", "Home", null, FormMethod.Post,
                                                              new { enctype = "multipart/form-data" }))
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)
            <fieldset>

                <legend>Image</legend>
                <form action="" method="post" enctype="multipart/form-data">

                        @Html.LabelFor(model => model.ImagePath)

                        <input id="ImagePath" title="Upload a product image" multiple="multiple" type="file" name="files" />

                        @**@

<input type="submit" value="Create" />

                </form>
            </fieldset>
        }

Controller
public ViewResult Create()
            {
                return View("Create", new Image());

            }

        [HttpPost]
        public ActionResult Create(Image Image, IEnumerable<HttpPostedFileBase> files)
        {

         if (ModelState.IsValid)
            {

            foreach (var file in files)
            {
                if (file.ContentLength > 0)
                {

                    file.SaveAs(HttpContext.Server.MapPath("~/Img/") + file.FileName);
                    Image.ImagePath = file.FileName;

                }
                repository.Create(Image);
            }
           }
           return RedirectToAction("Index");

        }

Model
public partial class Image
{
    [Key]
    public int ID { get; set; }
    public string ImagePath { get; set; }
}

EFRepositoty
public void  Create(Image Image)
            {

                if (Image.ID == 0)
                {
                    context.Images.Add(Image);
                }
                else
                {
                    Image dbEntry = context.Images.Find(Image.ID);
                    if (dbEntry != null)
                    {
                        dbEntry.ImagePath = Image.ImagePath;

                    }
                }
                context.SaveChanges();

        }

A: This is because you are redirecting to index inside your loop so it only processes the first file. Move your ModelState.IsValid check outside of the loop
if(!ModelState.IsValud)
    return View();

And then put redirect to last line of method.
What's happening with the Image entity is when its saved the first time the object is given an ID then for each other file in the loop it's just updating the same record in the database, this is why you will only see the last file in the db.
At the end of each loop you should set the image = null will fix things.

A: The solution I used was based on Stephens comment although Matts is an equally good solution:
                    Image image = new Image();
                    if (file.ContentLength > 0)
                    {
                        file.SaveAs(HttpContext.Server.MapPath("~/Img/") + file.FileName);
                        image.ImagePath = file.FileName;
                    }
                    repository.Create(image);


text:
Q: Monthly payment using for loop I'm new to Python, and I'm trying create a program that will let me keep adding a monthly payment for 12 months. This is what I've done so far:
for i in range(1,13):
   print('this is month',i)
   add = int(input('how much money do you want to add?: '))
   print(add)

Please keep the code simple. Thanks.

A: There are a couple of ways to do this:

*

*In-place addition
# start with zero dollars paid at month 1
add = 0
for i in range(1,13):
    print('this is month',i)
    month_add = int(input('how much money do you want to add?: '))
    add += month_add

print(add)

*Variable re-assignment:
add = 0
for i in range(1,13):
    print('this is month',i)
    month_add = int(input('how much money do you want to add?: '))
    add = add + month_add

print(add)

*Keep track of each month's payment using a list and sum at the end:
# initialize the monthly payment list
monthly_payments = []
for i in range(1,13):
    print('this is month',i)
    add = int(input('how much money do you want to add?: '))
    monthly_payments.append(add)

total_paid = sum(monthly_payments)
print(total_paid)

*Use a dictionary to keep track of each month's payment:
monthly_payments = {}
for i in range(1,13):
    print('this is month',i)
    add = int(input('how much money do you want to add?: '))
    monthly_payments[i] = add

total_paid = sum(amount for month, amount in monthly_payments.items())
print(total_paid)

A: Simple!
add = 0
for i in range(1,13):
   print('this is month',i)
   add += int(input('how much money do you want to add?: '))
   print(add)