text:
Q: Solving a differential equation with a power series expansion about $x_0=0$ We have the ODE, $y''+3xy'+3y=0$. We have that $x_0=0$ is an ordinary point as the coefficient of $y''$ is 1. Then, I let, $$y(x)=\sum_{n=0}^{\infty}\,a_nx^n,$$ such that, $$y'(x)=\sum_{n=1}^{\infty}\,na_nx^{n-1},$$ and, $$y''(x)=\sum_{n=2}^{\infty}\,n(n-1)a_nx^{n-2}.$$ We can hence rewrite the differential equation as, $$\sum_{n=2}^{\infty}\,n(n-1)a_nx^{n-2}+3x\sum_{n=1}^{\infty}\,na_nx^{n-1}+3\sum_{n=0}^{\infty}\,a_nx^n=0.$$ We pull the coefficients under the sum to get, $$\sum_{n=2}^{\infty}\,n(n-1)a_nx^{n-2}+\sum_{n=1}^{\infty}\,3na_nx^{n}+\sum_{n=0}^{\infty}\,3a_nx^n=0.$$ Re-indexing the first term gives us, $$\sum_{n=0}^{\infty}\,(n+2)(n+1)a_{n+2}x^{n}+\sum_{n=1}^{\infty}\,3na_nx^n+\sum_{n=0}^{\infty}\,3a_nx^n=0.$$ The only way to start the first and last sums at $n=1$ is to pull out the $n=0$ term from both. Then we have, $$2a_2+3a_0+\sum_{n=1}^{\infty}\,((n+2)(n+1)a_{n+2}+3na_n+3a_n)x^n=0.$$ I'm having trouble figuring out what the coefficients are supposed to be. Are $2a_2=0$, and $3a_0=0$? Or is $2a_2+3a_0=0$. I know the sum inside the summation is $0$. Wasn't sure about the external terms however.
Additionally, I am given boundary conditions, $y_1(0)=1$, and $y_1'(0)=0$. I'm not really sure what $y_1$ is referring to here. Any help would be appreciated.

A: We want the polynomial on the LHS to be zero for $\forall x$, therefore every coefficient (including the constant term) must be zero. Thus we have
$$ 2a_2 + 3a_0 = 0 $$
$$ (n+2)a_{n+2} + 3a_n = 0 $$
We can disregard the first equation, since it's effectively the second with $n=0$. So now we have the following recurrence relation
$$ a_0 = y(0) = 1 $$
$$ a_1 = y'(0) = 0 $$
$$ a_{n} = \frac{3a_{n-2}}{n} $$
Since $a_1 = 0$, all the following odd-powered coefficients must also be $0$.
For even-powered coefficients, we can prove from observation
$$ a_n = \frac{3^{n/2}}{n(n-2)(n-4)\cdots 6\cdot 4\cdot 2}a_0 $$
Setting $n=2k$ gives a "nicer" form
$$ a_{2k} = \left(\frac{3}{2}\right)^k \frac{1}{k!} $$


text:
Q: Embedded SVG into Inkscape I have a SVG file (an exported Gliffy diagram) that I want to open and edit in Inkscape. When viewing the code of the file using the developer options of Chrome, it looks like:
<svg xmlns="...>
  <g transform="...>
    <image xlink:href="data:image/svg+xml,%0A%20...></image>
  </g>
  ... (about 20 more <g>...</g> tags)
</svg>

When decoding the part starting with %0A%20..., it translates to something like
data:image/svg xml,
        <svg xmlns="http://www.w3.org/2000/svg" height="50000" width="50000">
            <style>
                .gliffy-rte-text {
                  ...

The issue is, that in Inkscape those parts will be replaced by a placeholder telling me "Linked image not found" and as speculated here, Inkscape most likely is not able to read the CSS styling correctly or probably at all.
I would very much appreciate any thoughts or ideas on how to convert the file such that it can be edited and displayed correctly in Inkscape.

A: You might convert all styling to element attributes using SVGOMG:

*

*replace your embedded <image> element by the decoded data url content. Your parent svg should look something like this:
 <!-- parent svg -->
 <svg xmlns="http://www.w3.org/2000/svg" >
     <!-- embedded svg decoded data url -->
     <svg xmlns="http://www.w3.org/2000/svg" height="50000" width="50000">
     <style>
         .gliffy-rte-text {
          }
     </style>
     </svg>
 </svg>

*Use SVGOMG "inline styles" and "style to attribute"parameter:

You should disable all other optimizing parameter, since they might strip to many other attributes.
Expected before result
    <svg viewBox="0 0 256 256" xmlns="http://www.w3.org/2000/svg">
        <style>
        circle{
            fill:none;
            stroke: orange;
            stroke-width:10;
          }
        </style>
        <circle cx="128" cy="128" r="100"/>
    </svg>

After
    <svg viewBox="0 0 256 256" xmlns="http://www.w3.org/2000/svg">
        <circle cx="128" cy="128" r="100" fill="none" stroke="orange" stroke-width="10"/>
    </svg>

A: Open the wrapper file in a browser. Right-click on the area containing the embedded SVG, and choose "Save (image) as...". If the wrapper contains multiple <image> tags, you will have to save them to separate files, but at least they will be in a form Inkscape can handle.
If you want to get them all together in one SVG file again, you will have to re-import them via the Inkscape import function. Take care to select 'Include as editable object', or you will end up right where you started:

The speculations above about CSS are unsubstantiated, btw. Inkscape will convert the content of a <style> element into inline style attributes, but otherwise handle them correctly. What happened is stated quite clearly in the above screenshot: data URLs embeded via an <image> tag will not be editable in Inkscape.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SVG not loading up in live server I've been working on a website and got to the SVG part and it just won't show up. I can drag it to the top of the tab and it shows up there but not on the live server website. Here is the HTML.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GR Official Site</title>
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link rel="stylesheet" href="main.css">
    <link href="https://fonts.googleapis.com/css2?family=Kumbh+Sans:wght@400;700&display=swap" rel="stylesheet">
    <link rel="shortcut icon" href="assets/images/favicon.png" />

            GR

                    Home

                    Warships [IN DEVELOPMENT]

                    Shop

                    News

                    Sign Up

Warships

The worlds next battle royale game.

                <button class="main__btn">Learn More</button>

Here is the CSS.
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    font-family: 'Kumbh Sans', sans-serif;
}

.navbar {
    background: #0024c7;
    height: 80px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1.2rem;
    position: sticky;
    top: 0;
    z-index: 999;
}

.navbar__container {
    display: flex;
    justify-content: space-between;
    height: 80px;
    z-index: 1;
    width: 100%;
    max-width: 1300px;
    margin: 0 auto;
    padding: 0 50px;
}

#navbar__logo {
    background-color: #28caf3;
    background-image: linear-gradient(to top, #28caf3, #93e5f3, #ffffff);
    background-size: 100%;
    -webkit-background-clip: text;
    -moz-background-clip: text;
    -webkit-text-fill-color: transparent;
    -moz-text-fill-color: transparent;
    display: flex;
    align-items: center;
    cursor: pointer;
    text-decoration: none;
    font-size: 2.3rem;
}

.fa-gem {
    margin: 0.5rem;
}

.navbar__menu {
    display: flex;
    align-items: center;
    list-style: none;
    text-align: center;
}

.navbar__item {
    height: 80px;
}

.navbar__links {
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    padding: 0 1rem;
    height: 100%;
}

.navbar__btn {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 1rem;
    width: 100%;
}

.button {
    display: flex;
    justify-content: center;
    align-items: center;
    text-decoration: none;
    padding: 10px 20px;
    height: 100%;
    width: 50%;
    border: none;
    outline: none;
    border-radius: 4px;
    background: #08657c;
    color: #ffffff;
}

.button:hover {
    background: #1216ff;
    transition: all 0.3s ease;
}

.navbar__links:hover {
    color: #28caf3;
    transition: all 0.3s ease;
}

@media screen and (max-width: 960px){
    .navbar__container {
        display: flex;
        justify-content: space-between;
        height: 80px;
        z-index: 1;
        width: 100%;
        max-width: 1300px;
        padding: 0;
    }

    .navbar__menu {
        display: grid;
        grid-template-columns: auto;
        margin: 0;
        width: 100%;
        position: absolute;
        top: -1000px;
        opacity: 0;
        transition: all 0.5s ease;
        height: 50vh;
        z-index: -1;
        background: #0024c7;
    }

    .navbar__menu.active {
        background: #0024c7;
        top: 100%;
        opacity: 1;
        transition: all 0.5s ease;
        z-index: 99;
        height: 50vh;
        font-size: 1.6rem;
    }

    #navbar__logo {
        padding-left: 25px;
    }

    .navbar__toggle .bar {
        width: 25px;
        height: 3px;
        margin: 5px auto;
        transition: all 0.3s ease-in-out;
        background: #ffffff;
    }

    .navbar__item {
        width: 100%;
    }

    .navbar__links {
        padding: 2rem;
        width: 100%;
        display: table;
    }

    #mobile-menu {
        position: absolute;
        top: 20%;
        right: 5%;
        transform: translate(5%, 20%);
    }

    .navbar__btn {
        padding-bottom: 2rem;
    }

    .button {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 80%;
        height: 80px;
        margin: 0%;
    }

    .navbar__toggle .bar {
        display: block;
        cursor: pointer;
    }

    #mobile-menu.is-active .bar:nth-child(2) {
        opacity: 0;
    }
    #mobile-menu.is-active .bar:nth-child(1) {
        transform: translateY(8px) rotate(45deg);
    }
    #mobile-menu.is-active .bar:nth-child(3) {
        transform: translateY(-8px) rotate(-45deg);
    }
}

/* Main Section.Styles */
.main {
    background-color: #415dd6;
}

.main__container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    align-items: center;
    justify-self: center;
    margin: 0 auto;
    height: 90vh;
    background-color: #415dd6;
    z-index: 1;
    width: 100%;
    max-width: 1300px;
    padding: 0 50px;

}

.main__container h2 {
    background-color: #cccccc;
    background-image: linear-gradient(to top, #cccccc, #eeeeee, #ffffff);
    background-size: 100%;
    -webkit-background-clip: text;
    -moz-background-clip: text;
    -webkit-text-fill-color: transparent;
    -moz-text-fill-color: transparent;
}

.main__content h1 {
    font-size: 4rem;
    background-color: #cccccc;
    background-image: linear-gradient(to top, #cccccc, #eeeeee, #ffffff);
    background-size: 100%;
    -webkit-background-clip: text;
    -moz-background-clip: text;
    -webkit-text-fill-color: transparent;
    -moz-text-fill-color: transparent;
}

.main__content p {
    margin-top: 1rem;
    font-size: 2rem;
    font-weight: 300;
    color: #f4f4f8;
}

.main__btn {
    font-size: 1rem;
    background-image: linear-gradient(to right, #0453ff, #049bff);
    padding: 14px 32px;
    border: none;
    border-radius: 4px;
    color: #006eff;
    margin-top: 2rem;
    cursor: pointer;
    position: relative;
    transition: all 0.35s;
    outline: none;
}

.main__btn a {
    position: relative;
    z-index: 2;
    color: #cccccc;
    text-decoration: none;
}

.main__btn:after {
    position: absolute;
    content: '';
    top: 0;
    left: 0;
    width: 0;
    height: 100%;
    background: #0453ff;
    transition: all 0.35s;
    border-radius: 4px;
}

.main__btn:hover {
    color: #ffffff;
}

.main__btn:hover:after {
    width: 100%;
}

.ws__img0--container {
    text-align: center;
}

#mobile__img {
    height: 80%;
    width: 80%;
}

Someone, please help me I know this is a lot of code but idc how long you take. I just need help.

A: Maybe because your page is not valid?
Error: The element a must not appear as a descendant of the button element.
From line 47, column 43; to line 47, column 67
ain__btn">Learn

Error: Stray end tag a.
From line 47, column 82; to line 47, column 85
n More</butt

A: I fixed it by turning the SVG into a PNG. I got this idea from a sensei at code ninjas.


text:
Q: AttributeError: 'rational_resampler_ccc' object has no attribute 'connect' GNUradio Help solve the problem with GNUradio
    Traceback (most recent call last):
      File "/home/pedro/DOPLOM/signal.py", line 166, in <module>
main()
  File "/home/pedro/DOPLOM/signal.py", line 142, in main
    tb = top_block_cls()
  File "/home/pedro/DOPLOM/signal.py", line 81, in __init__
    self.rational_resampler_xxx_1 = filter.rational_resampler_ccc(
  File "/usr/local/lib/python3/dist-packages/gnuradio/filter/rational_resampler.py", line 150, in __init__
    _rational_resampler_base.__init__(self, filter.rational_resampler_base_ccc,
  File "/usr/local/lib/python3/dist-packages/gnuradio/filter/rational_resampler.py", line 121, in __init__
    self.connect(self, self.resampler, self)
AttributeError: 'rational_resampler_ccc' object has no attribute 'connect'


text:
Q: Graphing a Parametric Equation I need to graph and show the work for this problem. The graph needs to include arrows on the curve to show the direction of motion and I need to label the t-values graphed.
$$c(t)=(2+4t, 3+2t)$$
So to start off do I need to take the parametric equation and put it in a y=f(x) form? I've never had to graph one of these before nor have I seen one graphed so I'm a bit lost. Thanks!

A: Probably the easiest way to do this is to choose a bunch of equally-spaced values of $t$ and compute, for each $t$, the coordinates $c(t)$.  Plot those points and connect them with a smooth curve or straight line, using arrows to show the forward motion.
For example, with $t=0$ you have $c(0)=(2,3)$ and with $t=1$ you have $c(1)=(6,5)$.  Plot those, and also $c(-2), c(-1), c(2), c(3)$, etc.

A: c(t) = x(t), y(t)
x(t)= 2+4t  => t=(x-2)/4
y(t)= 3+2t  => t=(y-3)/2
t = t
(x-2)/4 = (y-3)/2
2(x-2) = 4(y-3)
2x - 4 = 4y -12
x - 2 = 4y -6
x + 4 = 4y
y = (x+4)/4
Set values for your "new" function, and you will have the graph.


text:
Q: Transform nested array of objects Given the input array.
  let data = [
    {
      name: 'Name',
      countries: [
        {
          name: 'Country1',
          competitions: [
            {
              name: 'Competition1',
              matches: [
                { details: 'details' },
                { details: 'details' },
                { details: 'details' }
              ]
            },
            {
              name: 'Competition2',
              matches: [{ details: 'details' }]
            }
          ]
        },
        {
          name: 'Country2',
          competitions: [
            {
              name: 'Competition1',
              matches: [{ details: 'details' }]
            },
            {
              name: 'Competition2',
              matches: [{ details: 'details' }]
            },

            {
              name: 'Competition3',
              matches: [{ details: 'details' }, { detals: 'detail' }]
            }
          ]
        }
      ]
    },
    {
      name: 'Name2',
      countries: [
        {
          name: 'Country1',
          competitions: [
            {
              name: 'Competition1',
              matches: [{ details: 'details' }, { details: 'details' }]
            }
          ]
        }
      ]
    }
  ];

And desired output:
let sorted = [
    // For each Object in orginal array extract all matches and put it in new array.
    { name: 'Name', matches: [{}, {}, {}, {}, {}, {}, {}, {}] },
    { name: 'Name2', matches: [{}, {}] }
  ]

How can I transform data into sorted I can use nested 3 nested for loops and extract all matches into single array. But it does not give me desired output and I feel that nesting for loops is bad for resources and I'm certain that it can be done more concisely and after all I do not get expected output. I tried Object.assign creating new objects at starts etc etc.
Using for loop to get arr to store all matches from whole data array like so.
  for (var i = 0; i < data.length; i++) {
    for (var j = 0; j < data[i].countries.length; j++) {
      for (var l = 0; l < data[i].countries[j].competitions.length; l++) {
        for (
          var k = 0;
          k < data[i].countries[j].competitions[l].matches.length;
          k++
        ) {
          arr.push(data[i].countries[j].competitions[l].matches[k]);
        }
      }
    }

Is eyesore, and still leaves me with flat array of all matches which are no good.
Using ES6 and new goodies I manage to get closer to solution but leaves me with nested array of arrays that I can not seem to flatten.
  const d = data.map(i => {
    const inter = i.countries.map(e => e.competitions.map(z => z.matches));

    const final = inter.reduce((acc, next) => [...acc, ...next], []);

    return {
      name: i.name,
      matches: final
    };
  })

For educational purposes all solutions will be accepted no matter the performance at this point.
tl;dr How to transform data into sorted

A: You can to use reduce and just concat the matches
let result = data.map(v=>{
    let inter = v.countries.reduce((c,v)=> c.concat( v.competitions.map(z => z.matches).reduce((x,z) => x.concat( z ),[] ) ),[]);
    return {
        name : v.name,
        matches : inter
    }
});

Here is a snippet:

let data = [{
    name: 'Name',
    countries: [{
        name: 'Country1',
        competitions: [{
            name: 'Competition1',
            matches: [{
                details: 'details'
              },
              {
                details: 'details'
              },
              {
                details: 'details'
              }
            ]
          },
          {
            name: 'Competition2',
            matches: [{
              details: 'details'
            }]
          }
        ]
      },
      {
        name: 'Country2',
        competitions: [{
            name: 'Competition1',
            matches: [{
              details: 'details'
            }]
          },
          {
            name: 'Competition2',
            matches: [{
              details: 'details'
            }]
          },

          {
            name: 'Competition3',
            matches: [{
              details: 'details'
            }, {
              detals: 'detail'
            }]
          }
        ]
      },
    ]
  },
  {
    name: 'Name2',
    countries: [{
      name: 'Country1',
      competitions: [{
          name: 'Competition1',
          matches: [{
              details: 'details'
            },
            {
              details: 'details'
            },
            {
              details: 'details'
            }
          ]
        },
        {
          name: 'Competition2',
          matches: [{
            details: 'details'
          }]
        }
      ]
    }, ]
  }
];

let result = data.map(v => {
  let inter = v.countries.reduce((c, v) => c.concat(v.competitions.map(z => z.matches).reduce((x, z) => x.concat(z), [])), []);
  return {
    name: v.name,
    matches: inter
  }
});

console.log(result);

A: const sorted = data.map(o => {
  const name = o.name;
  let matches = [];
  o.countries.map(c => {
    return c.competitions.forEach(c => {
      c.matches.forEach(m => {
        matches.push(m);
      });
    });
  });
  return { name, matches };
});

Instead of using map, I created matches array, and while looping through every matches array from object, I'm just pushing the results into array. Here's a snippet:

let data = [
    {
      name: 'Name',
      countries: [
        {
          name: 'Country1',
          competitions: [
            {
              name: 'Competition1',
              matches: [
                { details: 'details' },
                { details: 'details' },
                { details: 'details' }
              ]
            },
            {
              name: 'Competition2',
              matches: [{ details: 'details' }]
            }
          ]
        },
        {
          name: 'Country2',
          competitions: [
            {
              name: 'Competition1',
              matches: [{ details: 'details' }]
            },
            {
              name: 'Competition2',
              matches: [{ details: 'details' }]
            },

            {
              name: 'Competition3',
              matches: [{ details: 'details' }, { detals: 'detail' }]
            }
          ]
        }
      ]
    }
  ];
const sorted = data.map(o => {
  const name = o.name;
  let matches = [];
  o.countries.map(c => {
    return c.competitions.forEach(c => {
      c.matches.forEach(m => {
        matches.push(m);
      });
    });
  });
  return { name, matches };
});
console.log(sorted);

A: Might be easier to filter during parsing:

let sorted = [], last = [], json = '[{"name":"Name","countries":[{"name":"Country1","competitions":[{"name":"Competition1","matches":[{"details":"details1"},{"details":"details2"},{"details":"details3"}]},{"name":"Competition2","matches":[{"details":"details4"}]}]},{"name":"Country2","competitions":[{"name":"Competition1","matches":[{"details":"details5"}]},{"name":"Competition2","matches":[{"details":"details6"}]},{"name":"Competition3","matches":[{"details":"details7"},{"detals":"detail8"}]}]}]},{"name":"Name2","countries":[{"name":"Country1","competitions":[{"name":"Competition1","matches":[{"details":"details9"},{"details":"details10"}]}]}]}]'

JSON.parse(json, (k, v) => k === 'details' ? last.push(v) :
  v.countries !== void 0 ? (sorted.push({ name: v.name, matches: last }), last = []) : 0)

console.log( sorted )


text:
Q: Storing the address of a pointer into memory For example, I have:
char* a = (char*) malloc(sizeof(char));
char* b = (char*) malloc(sizeof(char*));

How do I get the address of a into memory starting at address b?

A: Couldn't you just do a *b = a? Or am I misunderstanding the question?

A: Depends on what you need (it's not fully clear), you can do b = a, *b = &a (literally as you asked, the address of a into memory starting at address b), or *b = a.

A: If you want b to point to a pointer to char (as could be deduced by looking at your malloc statement, where you allocate space for one pointer to char), then b should actually be of type pointer to pointer to char, like this:
char*  a = (char*) malloc(sizeof(char));
char** b = (char**)malloc(sizeof(char*));

As far as I understood, what you want to achieve is to assign the address a is pointing to to the place b is pointing to? That would look like this then:
*b = a;

If you instead just want b to be a pointer to char (as you actually declared b), and want it to point to the same address as a, then do this:
char* a = (char*)malloc(sizeof(char));
char* b = a;

That makes b point to the same location as a; but then you also don't need to allocate space for b, because they simply point to the same address on the heap. You'll have to take care however, that you also only free the space pointed to by a and b once!
I'd also suggest reading up on the idea of pointers (e.g. here or here).

A: Let me preface this by saying that, since b is actually going to point to a char*, you should really declare and initialize it this way:
char** b = (char**) malloc(sizeof(char*));

using char** instead of char*. But if you already know that, and still want b to have type char* for some reason, then you'd just write this:
*((char**) b) = a;

which treats b as though it were a char**, so you can store a char* in it.


text:
Q: Parsing a string with multiple levels of key value pairs I need to write a part of the program which will work with a string, find in it some substrings and copy they to dictionary. Example of the string:
thestring ='\
#: somethings\nchars0 "substr0"\nchars1 "substr1"\n\n\
#: something\nchars0 "substr2"\nchars1 "substr3"'

so it have current substrings 'chars0' and 'chars1' which I know and some random substrings like 'substr0'...
But it is a small problem - on the start of the string anothoer structure:
'chars0 ""\nchars1 ""\n"words\\n"\n"else words\\n"\n ... '

and then structured string like above.
I know only number of this substrings with words, but I'm not interested in this subtrings, I need substrings only from structured part of the string.
If print the string, we get this:
chars0 ""
chars1 ""
"some words\n"
"else words\n"
...

#: something
chars0 "subtring"
chars1 "else substring"

...

How can I optimize search of it?
(I think that it is good to try find() string method or rfind() because of end of the string is structured)

A: A very basic way to parse this string might be
thestring ='\
#: somethings\nchars0 "substr0"\nchars1 "substr1"\n\n\
#: something\nchars0 "substr2"\nchars1 "substr3"'

for token in thestring.split('\n'):
  if "#" in token:
    handler.heading(token)
  elif "" == token:
    handler.section(token)
  else:
    handler.body(token)

print handler.dictOfDicts

This will print either
{'#: something': {'chars0 ': 'substr2', 'chars1 ': 'substr3'},
'#: somethings': {'chars0 ': 'substr0', 'chars1 ': 'substr1'}}

or
heading: #: somethings
key: chars0
value: substr0
key: chars1
value: substr1
section:
heading: #: something
key: chars0
value: substr2
key: chars1
value: substr3

depending on if handler is set to StringStructure() or StringPrinter(), respectively.  Where
class StringStructure:
  dictOfDicts = {}
  currentHeading = ''
  def heading( self, token ):
    self.currentHeading = token
    self.dictOfDicts[self.currentHeading] = {}
  def section( self, token ):
    pass
  def body( self, token ):
    key, value, junk = token.split('"')
    self.dictOfDicts[self.currentHeading][key] = value

class StringPrinter:
  dictOfDicts = ''
  def heading( self, token ):
    print 'heading: ' + token
  def section( self, token ):
    print 'section: ' + token
  def body( self, token ):
    key, value, junk = token.split('"')
    print 'key: ' + key
    print 'value: ' + value

This is brittle because it assumes you will always have two items in the body, two levels of keys, and won't produce the most meaningful error messages when the format of your string is wrong.


text:
Q: How to create an Alert Dialog in Actionscript 3 without the Flex Framework in a standalone AIR application designed to run on Windows I've got a project, written in Actionscript 3, built using Flash CS5.  In it, there are sections that require a microphone to be plugged in and the programmer who preceded me notified the user of the lack of microphone by throwing an Error.  This causes the program to stop running, a behavior which in undesirable.
The question: How to create a popup alert dialog in as pure as possible Actionscript. I've found the Alert class in mx.controls, but I can't find a way to add it to the project.  I found the Yahoo AlertManager class, but couldn't get it to work properly and it looks like the framework around it is larger than I need.
This is deployed on touchscreens as a standalone application on a Windows 7 Environment using AIR 2.5, Flash CS5, Actionscript 3.0.  I use FlashDevelop as the AS editor.

A: You'll have to make your own alert box, either by making NativeWindow instance and editing it, or (what I would recommend) making your own custom class that extends NativeWindow.
This is a simple generalized version of one that I made for one of my apps:
package
{
    import flash.display.*;
    import flash.geom.*;

    public class AlertWindow extends NativeWindow
    {

        public function AlertWindow(owningWindow:NativeWindow, windowTitle:String)
        {
            var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
            initOptions.maximizable = false;
            initOptions.minimizable = false;
            initOptions.resizable = false;
            initOptions.owner = owningWindow;
            initOptions.type = NativeWindowType.UTILITY;

            super(initOptions);

            title = windowTitle;
            alwaysInFront = true;
            stage.align = StageAlign.TOP_LEFT;
            stage.scaleMode = StageScaleMode.NO_SCALE;

            bounds = new Rectangle(owner.x + owner.width - (owner.width / 2) - 125, owner.y + owner.height - (owner.height / 2) - 75, 250, 150);
        }
    }
}

I whipped it up fairly quickly so it might not be as clean or efficient as it could be but it should be a good base to start on. Obviously you can add stuff like messages, buttons, event listeners, and anything else.
If you don't understand all of the code you should check out the NativeWindow and NativeWindowInitOptions documentation.


text:
Q: Task Scheduling / CRON Jobs on NestJS + Serverless / Lambda We are looking to deploy a NestJS application (using Express) to AWS Lambda (or similar) using the Serverless framework (or similar).
How should we handle scheduled tasks / cron jobs?
I notice in the NestJS documentation that NestJS has an official package that integrates node-cron.
Could you use this package in a serverless environment? If not, what is more appropriate?

A: If you're running the app in a serverless environment traditional CRON isn't going to be a good approach. You should instead look into using something like AWS Cloudwatch to trigger recurring events on a timer through a webhook/API endpoint. This could trigger a Lambda which sends a payload to your API with some secure headers set so that you can verify that the request should actually be executed
Alternatively, you can set your serverless lambda to be triggered by external events besides just HTTP as well, for example having Cloudwatch push a message onto EventBridge which in turn could safely trigger an execution of your lambda with some payload. It would be up to you to configure an additional entry point for this in your NestJS app though


text:
Q: Small program built with JavaFX and SceneBuilder, which doesn't run I've been helped so often by StackOverFlow, but I haven't ever thought, I would write here myself, especially because I struggle with the English language I litte. But I'll try because I'm working myself through some video course on JavaFX, but I haven't been able to move on for at least two days, because I'm not able to solve this problem on my own. It's about building a connection between a Java(FX) main class, a controller class and an intermediate fxml file.
So, I tried to a establish a stage and a scene like this:
package abcxyz;

import java.net.URL;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class TestSBMain extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        URL url = getClass().getResource("hallo.fxml");
        Parent root = FXMLLoader.load(url);
        Scene scene = new Scene (root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);}
}

As you see, I connected the start method with an fxml-file, which I built with the scene builder. Have a look, please:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0"
xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="abcxyz.TestController">
   <children>
      <Button fx:id="halloButton" layoutX="258.0" layoutY="187.0" mnemonicParsing="false" text="Hallo" />
   </children>
</AnchorPane>

This file, as you see, is linked to a controller class, which is supposed to control the established JavaFX-Button. Please be patient with me, when I show this one as well:
package abcxyz;

import java.net.URL;
import java.util.ResourceBundle;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;

public class TestController implements Initializable {
    @FXML
    private Button halloButton;

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {
        halloButton.setDisable(true);
    }

}

But I receive this error message, I haven't been able to come over for two days:
Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.lang.NullPointerException: Location is required.
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3230)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3194)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3163)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3136)
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3113)
    at javafx.fxml/javafx.fxml.FXMLLoader.load(FXMLLoader.java:3106)
    at abcxyz.TestSBMain.start(TestSBMain.java:16)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application abcxyz.TestSBMain

My program is hierarchized like this:
enter image description here
Can you see, what the probem might be? I would be very thankful for a solution or some small advices! Thank you so much in advance! I'm sorry for the length of my (first) post! :-)
All the best,
Christian


text:
Q: Scala: type inference issue I have:
sealed trait Par[A]{def foo = ???}
case class Unit[A](v: () => A) extends Par[A]
case class Map2[L, R, A](parLeft: Par[L],
                         parRight: Par[R],
                         map: (L, R) => A) extends Par[A]

my problem is that when I pattern match on p:Par[A] to do something like this:
def getSequentially: A = this match {
  case Par.Unit(f) => f()
  case Par.Map2(a, b, f) => f(a.getSequentially, b.getSequentially)
}

L and R are inferred to be Any in Intellij's type inspector and getSequentially calls are highlighted in red, warning: type mismatch, expected Nothing, actual Any, since f is expected to be of type: (Nothing, Nothing) => A. Although it actually runs and compiles.
I think I understand what the problem is and I should be able to solve it with existential types in the definition of Map2. Only problem is that the map parameter has a dependent type, so I don't know how to do that. Maybe I should do a variation of the AUX pattern?
My question is, firstly why it compiles and secondly, if there is a way of restructuring the type dependency so that it no longer issues a warning.

A: If you want to have existentials you can use typed patterns:
sealed trait Par[A]{
  def getSequentially: A = this match {
    case x: Par.Unit[A] => x.v()
    case x: Par.Map2[_, _, A] => x.map(x.parLeft.getSequentially, x.parRight.getSequentially)
  }
}

object Par {
  case class Unit[A](v: () => A) extends Par[A]
  case class Map2[L, R, A](parLeft: Par[L],
                           parRight: Par[R],
                           map: (L, R) => A) extends Par[A]
}

IntelliJ seems not to highlight this.


text:
Q: How to set interval option for timeslider with same min and maxdate using Ol-ext:Timeline control? I am trying to create a timeslider with Ol-extension timeline similiar to https://viglino.github.io/ol-ext/examples/storymap/map.control.timequake.html. All the sample codes have different min and maxDate with graduation option as day. The following code works
var tline = new ol.control.Timeline({
    graduation:'day',
    minDate: new Date('2020/5/1'),
    maxDate: new Date('2020/5/10')
  });
  map.addControl (tline);

However I need to create a timeslider with a 15 minute interval on a single day. I used the interval property  but nothing works. How to fix this?
 var tline = new ol.control.Timeline({
    interval:'15mn',
    minDate: new Date('2020/5/1'),
    maxDate: new Date('2020/5/1')
  });
  map.addControl (tline);


text:
Q: Binding An Observable Collection of Class Objects To a ListBox and UserControl (WPF) What I'm trying to do:
I'm binding a ListBox called "LBShortcuts" to a class called "ShortcutList", that both inherits ObservableCollection<T> and holds objects of the class Shortcut. I bind it by setting the ListBox's DataContext within the MainWindow's constructor. Then I have a UserControl called UCShortcut as a DataTemplate which binds a property within the Shortcut object. When I click a button on the main window, it should add a shortcut to the ObservableCollection, which should invoke the CollectionChanged event, which then should alert the data-bound ListBox to update its list, and then all of its items.
What is happening:
Absolutely nothing. When I try to add shortcuts to the list via a button on the window, it adds them to the list, but nothing shows up. I've even registered the MainWindow's object to the ObservableCollection.CollectionChanged event, but it seems like it doesn't fire, even when I explicitly invoke it. Because of that, nothing shows up in the list.
What I've tried:

*

*I tried to create a custom list class using the INotifyPropertyChanged and INotifyCollectionChanged interfaces.

*I tried to debug the binding process using System.Diagnostics.PresentationTraceLevel, and Setting it in the Immediate window. Can't remember where I went wrong, but it didn't work.

*I tried to change my debug options to show me everything about binding in the WPF application, but all it did was show me worrisome binding failures I had nothing to do with:

System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=IsInAppMenuExpanded; DataItem=null; target element is 'StackPanel' (Name='ButtonStackPanel'); target property is 'Visibility' (type 'Visibility')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=ShowLiveVisualTreeCommand; DataItem=null; target element is 'Button' (Name='ShowLiveVisualTree'); target property is 'Command' (type 'ICommand')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=IsInAppSelectionEnabled; DataItem=null; target element is 'ToggleButton' (Name='InAppSelection'); target property is 'IsChecked' (type 'Nullable`1')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=AreLayoutAdornersEnabled; DataItem=null; target element is 'ToggleButton' (Name='LayoutAdorners'); target property is 'IsChecked' (type 'Nullable`1')
System.Windows.Data Information: 10 : Cannot retrieve value using the binding and no valid fallback value exists; using default instead. BindingExpression:Path=IsTrackFocusedElementEnabled; DataItem=null; target element is 'ToggleButton' (Name='TrackFocusedElement'); target property is 'IsChecked' (type 'Nullable`1')

...I don't even have Toggle buttons in this application.

*

*I tried to isolate the binding by removing the DataTempate.

*I tried changing the UCShortcut's TextBlock.Text binding to {Binding BoundShortcut.Name, RelativeSource={RelativeSource AncestorType=UserControl}}

*I tried again using VS' databinding dialog box to get around the same idea: {Binding BoundShortcut.Name, ElementName=userControl, FallbackValue=Binding Invalid}
I'm really not sure what I'm doing wrong here. Based on everything I've read about this, this should be working. However...here I am. Help, please?
Details:
ListBox (LBShortcuts):
<Window xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase">
.
.
.
<ListBox x:Name="LBShortcuts" ItemsSource="{Binding}"
         Grid.Row="1" BorderBrush="{x:Null}" Background="{x:Null}" IsManipulationEnabled="True" AllowDrop="True"
         diag:PresentationTraceSources.TraceLevel="High">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <local:UCShortcut BoundShortcut="{Binding Shortcut}"/>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

ListBox code-behind:
        public MainWindow()
        {
            InitializeComponent();
            Shortcuts = new ShortcutList();
            Shortcuts.CollectionChanged += SaveList;
            LBShortcuts.DataContext = Shortcuts;
            SavingPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) +
              "\\FolderShortcuts.json";
            OpenList();
        }

ShortcutList class:
    public class ShortcutList : ObservableCollection<Shortcut>
    {
        public ShortcutList() : base()
        {
            shortcuts = new List<Shortcut>();
        }

        public ShortcutList(List<Shortcut> loadedList) : base()
        {
            shortcuts = new List<Shortcut>();
            foreach (Shortcut sc in loadedList)
            {
                Add(new Shortcut(this,sc.Directory,sc.Name));
            }
        }

        public void AddDirectory(string directory, string name)
        {
          DirectoryInfo di = new DirectoryInfo(directory);
          Shortcut s = new Shortcut(this, di);
          if (shortcuts.Where(x => x.Directory == di.FullName).Count() == 0)
          {
              Add(s);
          }
        }
    }

Shortcut class:
    [Serializable]
    public class Shortcut : INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;

        public string Directory { get; set; }
        private string name;

        //This must be a property before you can use it as a data binding path in the properties menu of the design page
        public string Name
        {
            get {return name; }
            set
            {
                if (name != value)
                {
                    name = value;
                    OnPropertyChanged();
                }
            }
        }

        [NonSerialized]
        public ShortcutList Parent;

        private void OnPropertyChanged([CallerMemberName] string member_name = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(member_name));
        }

        public Shortcut(){ }

        public Shortcut(ShortcutList parent, DirectoryInfo directory)
        {
            Parent = parent;
            Directory = directory.FullName;
            Name = directory.Name;
        }

        public Shortcut(ShortcutList parent, string directory,string name)
        {
            Parent = parent;
            Directory = new DirectoryInfo(directory).FullName;
            Name = name;
        }
    }

UCShortCut (UserControl)
XAML:
<Grid VerticalAlignment="Center">
    ...
    <TextBlock x:Name="TBkName" Text="{Binding Name, FallbackValue=Binding Invalid}"
      Padding="4" Foreground="{DynamicResource ForegroundColor}"/>
    ...
</Grid>

code-behind:
 public partial class UCShortcut : UserControl
    {
        public static readonly DependencyProperty ShortcutProperty;
        public Shortcut BoundShortcut
        {
            get{ return (Shortcut)GetValue(ShortcutProperty); }
            set{ SetValue(ShortcutProperty, value); }
        }

        static UCShortcut()
        {
            ShortcutProperty = DependencyProperty.Register("BoundShortcut",
              typeof(Shortcut), typeof(UCShortcut));
        }

        public UCShortcut()
        {
            InitializeComponent();
        }

        private void RenameShortcut(object sender, RoutedEventArgs e)
        {
            TBxName.Text = TBkName.Text;
            TBkName.Visibility = Visibility.Collapsed;
            TBxName.Visibility = Visibility.Visible;
            TBxName.Focus();
            TBxName.SelectAll();
        }

        private void ChangeName(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter || e.Key == Key.Escape)
            {
                if (e.Key == Key.Enter)
                {
                    BoundShortcut.Name = TBxName.Text;
                }
                TBkName.Visibility = Visibility.Visible;
                TBxName.Visibility = Visibility.Collapsed;
                TBxName.Text = string.Empty;
            }
        }

        private void InitBoundShortcut(object sender, RoutedEventArgs e)
        {
            BoundShortcut = (Shortcut)DataContext;
        }
    }


text:
Q: The command "jupyter lab" does not work as the file does not exist I installed Jupyter Lab but cannot launch it (jupyter lab) due to the error: Error executing Jupyter command 'lab': [Errno 2] No such file or directory.
However, it is installed, and is show as one of available subcommands (via jupyter lab):

Available subcommands: bundlerextension console kernelspec lab labextension
  labhub migrate nbconvert nbextension notebook qtconsole run serverextension
  troubleshoot trust

Why does it not work and is there something I'm missing here? jupyter notebook works without any problems. I also added jupyter serverextension enable --py jupyterlab --sys-prefix according to the documentation on Github, FYI.
My working environment:
jupyter notebook --version # 5.0.0
jupyter version # 4.3.0

A: @Blazard open the .profile in your home using VIM add the following path
export PATH=$PATH:/home/<user-name>/.local/bin

save it
$ source ~/.profile (Dont forget to do this)

A: I had the same problem. Installing it over PyCharm IDE solved the problem for me. I am using Windows as an OS. Installing packages over PyCharm works in general better for me than over Windows cmd.

A: @Blaszard could you try the following
/home/<your-user-name>/.local/bin/jupyter-lab

SOURCE
EDIT
Alternatively, you would have to add /home/<your-user-name>/.local/bin to your PATH variable. However, you should probably just try it manually first and see if that even works at all.

A: simple solution I found for my mac powerbook is:
go to a working directory in the terminal and then type jupyter lab.
IT WORKS,

A: We need to find jupyter-lab command. In my case on a mac it is in /opt/local/Library/Frameworks/Python.framework/Versions/3.9/bin/.
I'm using macports so my binaries are in /opt/local/bin. It's on my path:
> echo $PATH
.../opt/local/bin...

I have to create a symbolic link in this directory:
ln -s /opt/local/Library/Frameworks/Python.framework/Versions/3.9/bin/jupyter-lab jupyter-lab


text:
Q: RSA Extra Bit 129 instead off 128 I am using this function to change public key and encrypt data:
public byte[] EncryptData(byte[] data2Encrypt)
{
    string key = "109120132967399429278860960508995541528237502902798129123468757937266291492576446330739696001110603907230888610072655818825358503429057592827629436413108566029093628212635953836686562675849720620786279431090218017681061521755056710823876476444260558147179707119674283982419152118103759076030616683978566631413";
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024);

    BigInteger intk;
    BigInteger.TryParse(key, out intk);

    RSAParameters privateKey = new RSAParameters();
    byte[] expont = { 1, 0, 1 };
    byte[] modulus = intk.ToByteArray();

    Logger.log(Log_Type.ERROR, "Pierwszy bit: " + modulus[0]);
    privateKey.Exponent = expont;
    privateKey.Modulus = intk.ToByteArray();

    rsa.ImportParameters(privateKey);
    return rsa.Encrypt(data2Encrypt, false);
}

But it return me array with 129 length instead od 128 (What should be max lenght using 1024 bits i think). What can be a reason?

A: If you use BigInteger an additional bit is always placed before the
number. If your key has 1024 bits you get 1025 bits, so skip the
first byte if it is 0x00 (meaning a positive value)

A: I am not sure, that it should be even converted into BitInteger. RSA key what I am trying to get is similar to this function in C++
void Crypt::rsaSetPublicKey(const std::string& n, const std::string& e)
{
BN_dec2bn(&m_rsa->n, n.c_str());
BN_dec2bn(&m_rsa->e, e.c_str());

// clear rsa cache
if(m_rsa->_method_mod_n) { BN_MONT_CTX_free(m_rsa->_method_mod_n); m_rsa->_method_mod_n = NULL; }

}
Where 'n' is this key srting and 'e' is : "65537"
If it should not be a BigInteger, then what?

A: BigInteger produces signed little-endian numbers, while RSAParameters requires unsigned big-endian. You can still use BigInteger though, just convert its output to what RSAParameters is expecting.
byte[] modulus = intk.ToByteArray().Reverse().Skip(1).ToArray();

Reverse to make the number big-endian, and Skip(1) to skip the sign.


text:
Q: Magento SSL Checkout - not found I have a valid SSL certificate installed on a managed server. I enable ssl by going system->configuration->web and setting "Secure"-> Base Url: https://www.mydomain.com and changing "Use Secure URLs in Frontend": Yes.
When I try and checkout it redirects to https://www.mydomain.com/checkout/onepage/. This page cannot be found...
The thing is there is a secure directory on the server (public_ssl) and non secure (public html), should the public_ssl directory be empty? How is magento suppose to asccess files that aren't there?
I have tried copying over the index.php, .htaccess, skin, js & media folders/files to public_ssl, which works but then the media isn't updated when I upload a product image etc...
(I edited the index.php "MAGENTO_ROOT" global to find the appropriate files...)
Am I Missing something?

A: The best solution is to contact you hosting provider. They may be able to modify the way their ssl is configured (https://serverfault.com/questions/429634/restrict-apache-to-only-allow-access-using-ssl-for-some-directories) or use a symlink so that the content will be shared between public_ssl and your public html folder.
Also, for better site performance it's always best to host you magento website on a service provider who specializes in magento hosting.


text:
Q: How to set Excel sheet name with powershell variable? I'm trying to set an excel sheet name with Powershell using a variable but am getting this error:
Exception from HRESULT: 0x800A03EC
At line:14 char:1
+ $ws.Name = $RequestTitle
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

Here's a snippet of the code:
# create new excel object
$excel = New-Object -ComObject excel.application

# show the excel object
$excel.visible = $True

# add a workbook
$workbook = $excel.Workbooks.Add()

# create a variable referencing the first sheet of the wb
$ws= $workbook.Worksheets.Item(1)

# change the name of the sheet
$ws.Name = $NewSheetName

But when I do something like: $ws.Name = "some string" it works fine without an error. I've also tried using the $NewSheetName.ToString() method to no avail.
What is the best way to reference a variable to name a sheet? Any help would appreciated!

A: Using the statement like this will take care of it. Put quotes around the variable name.
# change the name of the sheet
$ws.Name = "$NewSheetName"

I dont know why but excel sheet name requires a string in quotes even when using a variable that's clearly a string.
Note
Tested with powershell v5 and Office 2013, Office 365, Code with $variable without quote works fine. Not sure what exactly is causing the issue where you are required to use double quotes around the variable name.


text:
Q: Basic networking: browsing to Rails site running on another machine I'm running a Rails site on computer A. I start the site with rails server and browse to it at http://localhost:3000. Computer B is on the same WIFI network. From computer B I can visit my site at http://192.x.y.z:3000 where the IPv4 address of computer A is obtained from ifconfig in the OS X Terminal.
How can I browse to my site (running on computer A) from computer B without using the wireless router? I'll still have WIFI enabled on both computers. However I don't want the computers to communicate through the additional WIFI router.
My current understanding is the WIFI router assigns IP addresses to the various devices on the network. In trying to answer my question I wondered who/what will assign IP addresses to the computers when the wireless router is removed.
My goal is to learn more about networking. I'm fine doing some low-level sockets programming if that's what it takes.

A: You can create an Ad-Hoc WiFi network between the two computers, which works without a router. The two will still try to get an IP address from a 3rd party, which will of course fail though. In this case they'll fall back on IP self-assignment and pick a random IP in the 169.x range. This will take a minute or so, but once it happened, you can access the other machine on that address. Manually setting a fixed IP on both machines is an option as well.


text:
Q: Which way around is the comparison done in DateRangeQuery? I have some code like this.
var filter = new DateRangeQuery
{
   Field = fieldName,
   GreaterThan = date
};

What I'm confused about is what way around is the comparison done?  Are we saying that the dates in the index should be greater than the date passed in or are we saying that the data passed in should be greater than the dates in the index?

A: The dates of the index must be greater than the query input.
PUT my_index/my_type/1
{
  "date": "2018-01-01"
}

PUT my_index/my_type/2
{
  "date": "2018-01-02"
}

GET my_index/_search
{
  "query": {
    "range": {
      "date": {
        "gt": "2017-01-01"
      }
    }
  }
}


text:
Q: App crashes on launch on iOS 6 but working fine on iOS 7 I developed an app in Xcode 5. Until now I only tested it on a device running iOS 7. I tried running it on another device with iOS 6 but it crashes on launch in the main function without any error message in the console. The deployment target is 6.0 and I've chosen Standard architectures(armv7, armv7s) in the Build Settings.
I also checked the code for methods available only for iOS 7. Could it be that I accidentally skipped one? As for as I know I should get an error message if it doesn't recognise the method.
I'm not a newbie on iOS development, but something is skipping my attention. Do you have any idea what it could be?
I would really appreciate your help. Thank you.
UPDATE:
This is it... Could it be something in the plist...?

I finally got to the bottom of this problem thanks to "OC Rickard". Writing 'bt' in the console, this was the output:

*

*thread #1: tid = 0x2503, 0x38a8b454 CoreFoundationCFDictionaryRemoveValue + 12, queue = 'com.apple.main-thread, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
frame #0: 0x38a8b454 CoreFoundationCFDictionaryRemoveValue + 12
frame #1: 0x36e58e28 GraphicsServicesRemoveFont + 740
frame #2: 0x36e58868 GraphicsServicesAddFontsFromCGFontAndPath + 332
frame #3: 0x36e58660 GraphicsServicesAddFontsFromURLOrPath + 156
frame #4: 0x36e59e12 GraphicsServicesInitialize_block_invoke_0 + 378
frame #5: 0x36e3a4b6 libdispatch.dylib_dispatch_client_callout + 22
frame #6: 0x36e403f6 libdispatch.dylibdispatch_once_f$VARIANT$mp + 42
frame #7: 0x36e57f7a GraphicsServicesInitialize + 78
frame #8: 0x36e57fc0 GraphicsServicesGSFontCreateWithName + 56
frame #9: 0x31c7cfea UIKitUINewFont + 58
frame #10: 0x31c7cf9a UIKit+[UIFont systemFontOfSize:traits:] + 18
frame #11: 0x31fa608c UIKit-[UIStatusBarServiceItemView _contentsImageFromString:withWidth:letterSpacing:forStyle:] + 124
frame #12: 0x31cd888a UIKit-[UIStatusBarServiceItemView _serviceContentsImageForStyle:] + 362
frame #13: 0x31cd84ac UIKit-[UIStatusBarServiceItemView updateContentsAndWidth] + 140
frame #14: 0x31cd823e UIKit-[UIStatusBarItemView initWithItem:data:actions:style:] + 306
frame #15: 0x31cd7f90 UIKit-[UIStatusBarLayoutManager _createViewForItem:withData:actions:] + 108
frame #16: 0x31c877de UIKit-[UIStatusBarLayoutManager _prepareEnabledItemType:withEnabledItems:withData:actions:itemAppearing:itemDisappearing:] + 134
frame #17: 0x31c8770e UIKit-[UIStatusBarLayoutManager prepareEnabledItems:withData:actions:] + 82
frame #18: 0x31f9e910 UIKit-[UIStatusBarForegroundView _setStatusBarData:actions:animated:] + 168
frame #19: 0x31c87662 UIKit-[UIStatusBarForegroundView setStatusBarData:actions:animated:] + 722
frame #20: 0x31cd7516 UIKit-[UIStatusBar _prepareToSetStyle:animation:] + 794
frame #21: 0x31c8978e UIKit-[UIStatusBar requestStyle:animationParameters:] + 558
frame #22: 0x31c894a8 UIKit-[UIStatusBar requestStyle:animated:] + 84
frame #23: 0x31cd2f6e UIKit-[UIApplication _createStatusBarWithRequestedStyle:orientation:hidden:] + 258
frame #24: 0x31cd2736 UIKit-[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 430
frame #25: 0x31c7ac38 UIKit-[UIApplication handleEvent:withNewEvent:] + 1004
frame #26: 0x31c7a6cc UIKit-[UIApplication sendEvent:] + 72
frame #27: 0x31c7a11a UIKit_UIApplicationHandleEvent + 6154
frame #28: 0x36e5d5a2 GraphicsServices_PurpleEventCallback + 590
frame #29: 0x36e5d1d2 GraphicsServicesPurpleEventCallback + 34
frame #30: 0x38b1d172 CoreFoundation__CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION + 34
frame #31: 0x38b1d116 CoreFoundation__CFRunLoopDoSource1 + 138
frame #32: 0x38b1bf98 CoreFoundation__CFRunLoopRun + 1384
frame #33: 0x38a8eebc CoreFoundationCFRunLoopRunSpecific + 356
frame #34: 0x38a8ed48 CoreFoundationCFRunLoopRunInMode + 104
frame #35: 0x31cd147c UIKit-[UIApplication _run] + 668
frame #36: 0x31cce2f8 UIKitUIApplicationMain + 1120
frame #37: 0x00085f96 iSpyLovemain(argc=1, argv=0x2fd98d20) + 110 at main.m:16
frame #38: 0x362fab20 libdyld.dylibstart + 4

I had a font declared in the plist file which had .dfont extension. Apparently iOS 6 didn't like this. Thank you "OC Rickard", and thanks to all of you guys for taking interest in my problem.


text:
Q: How can I define custom keyboard mappings to resize, move, and manage windows? I just returned to ubuntu (13.04) after a year using OS X exclusively. I love the improvements that have come to ubuntu and unity, and I'm glad to be back. There's just one thing, though...
Slate is a simple OS X tool that allows users to quickly create powerful keyboard macros and really take advantage of their screen space. I have to say I was spoiled by it. Even on a tiny laptop, my workflow was never interrupted by changing workspaces or leaving the keyboard to adjust a window, because perfect adjustment was a keystroke or two away. For example:
bind h:ctrl;alt;cmd resize -10% +0
# this increases the window's left width by 10%
bind h:shift;alt nudge -10% +0
# this moves the window left by 10%

You make a big config file, and like vim, tmux, and everything else, it just becomes muscle memory.
I can't seem to find a way to achieve anything close to this in linux or ubuntu. I've tried to make do with compiz window settings and the built-in stuff Ubuntu offers, but it's not even in the same realm. Although to be fair, this level of tuning isn't something most people care about.
Thanks, guys. :) Any feedback would be appreciated.

A: The best I've managed in Unity to bind the Compiz "grid" functions to Win+Left and Win+Right, and re-enable multiple workspaces. Unity lets you swap workspaces with Ctrl+Alt+[direction], and pull a window between workspaces with Ctrl+Alt+Shift+[direction]. The four default workspaces in unity are arranged in a "four corners" style, which I find makes them quite easy to keep track of. It works really, really well on a single monitor.
Unfortunately, Unity provides no good way to move a window between two monitors, and, as you pointed out, it's lacking in more granular window management options.
So, if you really want good window management, and you're alright with ditching Unity, I can't recommend xmonad strongly enough. It doesn't have Unity's UI polish, and customization can be tricky (you do all the scripting in Haskell), but once you're up and running, it's the absolute best keyboard-focused window manager I have ever used. Ever.
It has the resizing feature you mentioned built in. It also automatically resizes your windows as you open new ones, and puts one workspace on each monitor (rather than having a workspace "shared" between two monitors as in Unity or OSX).


text:
Q: Countdown timer in quiz C# I have a small quiz program that requires a timer countdown from 10 to 0, I set my time interval to 1000, what I wanted to achieve is the continuous countdown for every question lets say, question#1 as the user press start timer will begin, it will count down from 10 to 0, if the user did not provide an answer, and the timer count down reaches 0, it will move to question#2 automatically and then start again the countdown from 10 to 0, till the last question.
my code:
    public int ii;
    public frmExam()
    {
        InitializeComponent();
    }

     private void frmExam_Load(object sender, EventArgs e)
     {
        timer_quiz.Enabled = false;
        timer_quiz.Interval = 1000;
        ii = 10;
     }

    //button start
     private void bntCON_Click(object sender, EventArgs e)
     {
        timer_quiz.Start();
        Submit(); //---> 1st question
     }

     //timer will stop as it reach 0 then move to question# 2
     private void timer_quiz_Tick(object sender, EventArgs e)
     {
        if (ii > 0)
        {
            ii = ii - 1;
            lblCount.Text = "0"+ii.ToString();
        }
        else {

            Submit();
            timer_quiz.Stop();
            lblTym.Visible = true;
        }
     }

My problem how do I restart again my count down? If I place timer_quiz.Start(); inside else statement, the question# will move every tick of the of the timer instead of count down.


text:
Q: Why does resolved dependencies differ between Java 8 and Java 11? Given a very simple Maven project with a single pom-file containing a single dependency:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>maven-test</artifactId>
  <version>1.0-SNAPSHOT</version>

  <dependencies>
    <dependency>
      <groupId>org.apache.cxf.xjc-utils</groupId>
      <artifactId>cxf-xjc-runtime</artifactId>
      <version>3.3.0</version>
    </dependency>
  </dependencies>

</project>

When running mvn dependency:tree different results are given depending on Java version.
With Java 8:
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------------< org.example:maven-test >-----------------------
[INFO] Building maven-test 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ maven-test ---
[INFO] org.example:maven-test:jar:1.0-SNAPSHOT
[INFO] \- org.apache.cxf.xjc-utils:cxf-xjc-runtime:jar:3.3.0:compile
[INFO]    \- jakarta.xml.bind:jakarta.xml.bind-api:jar:2.3.2:compile
[INFO]       \- jakarta.activation:jakarta.activation-api:jar:1.2.1:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.982 s
[INFO] Finished at: 2020-06-22T15:05:56+02:00
[INFO] ------------------------------------------------------------------------

With Java 11:
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------------< org.example:maven-test >-----------------------
[INFO] Building maven-test 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ maven-test ---
[INFO] org.example:maven-test:jar:1.0-SNAPSHOT
[INFO] \- org.apache.cxf.xjc-utils:cxf-xjc-runtime:jar:3.3.0:compile
[INFO]    +- jakarta.xml.bind:jakarta.xml.bind-api:jar:2.3.2:compile
[INFO]    |  \- jakarta.activation:jakarta.activation-api:jar:1.2.1:compile
[INFO]    +- javax.annotation:javax.annotation-api:jar:1.3.1:compile           <-- This and below only with Java 11
[INFO]    +- javax.xml.ws:jaxws-api:jar:2.3.0:compile
[INFO]    |  +- javax.xml.bind:jaxb-api:jar:2.3.0:compile
[INFO]    |  \- javax.xml.soap:javax.xml.soap-api:jar:1.4.0:compile
[INFO]    \- javax.activation:activation:jar:1.1.1:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  1.261 s
[INFO] Finished at: 2020-06-22T15:05:51+02:00
[INFO] ------------------------------------------------------------------------

I would have expected the trees to be the same under the two Java versions.
Maven version is 3.6.0.
Why do the resolved dependencies differ between the Java versions?

A: The reason why the dependency tree differs between the Java versions is found in the dependency:
<dependency>
  <groupId>org.apache.cxf.xjc-utils</groupId>
  <artifactId>cxf-xjc-runtime</artifactId>
  <version>3.3.0</version>
</dependency>

This in turn has xjc-utils as its parent:
<parent>
    <groupId>org.apache.cxf.xjc-utils</groupId>
    <artifactId>xjc-utils</artifactId>
    <version>3.3.0</version>
</parent>

In this POM file, we find the dependencies that are excluded when building with Java 8:
<profile>
    <id>java9-plus</id>
    <activation>
        <jdk>[9,)</jdk>
    </activation>
    <dependencies>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>javax.xml.ws</groupId>
            <artifactId>jaxws-api</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>
        </dependency>
    </dependencies>
 </profile>

This pretty much speacks for itself, the dependencies will only be included if Java 9 or above is used, as stated in this range: <jdk>[9,)</jdk>. The documentation for the tag states:

Specifies that this profile will be activated when a matching JDK is detected. For example, 1.4 only activates on JDKs versioned 1.4, while !1.4 matches any JDK that is not version 1.4.

This activation profile makes sure these dependencies are included when Java 11 is used:
[INFO]    +- javax.annotation:javax.annotation-api:jar:1.3.1:compile
[INFO]    +- javax.xml.ws:jaxws-api:jar:2.3.0:compile
[INFO]    |  +- javax.xml.bind:jaxb-api:jar:2.3.0:compile
[INFO]    |  \- javax.xml.soap:javax.xml.soap-api:jar:1.4.0:compile
[INFO]    \- javax.activation:activation:jar:1.1.1:compile

More info about activation can be found in the official Maven documentation:

Activations are the key of a profile. The power of a profile comes from its ability to modify the basic POM only under certain circumstances. Those circumstances are specified via an activation element.

Together with another example of activation based on Java version:
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                      https://maven.apache.org/xsd/maven-4.0.0.xsd">
  ...
  <profiles>
    <profile>
      <id>test</id>
      <activation>
        <activeByDefault>false</activeByDefault>
        <jdk>1.5</jdk>
        <os>
          <name>Windows XP</name>
          <family>Windows</family>
          <arch>x86</arch>
          <version>5.1.2600</version>
        </os>
        <property>
          <name>sparrow-type</name>
          <value>African</value>
        </property>
        <file>
          <exists>${basedir}/file2.properties</exists>
          <missing>${basedir}/file1.properties</missing>
        </file>
      </activation>
      ...
    </profile>
  </profiles>
</project>

A: Dependency tree mojo trims lower level dependencies if the dependency is already present higher in the tree.
We can use verbose flag (-Dverbose) to show the excluded dependencies.
To find a specific artifact : mvn dependency:tree -Dverbose -Dincludes=[groupId]:[artifactId]:[type]:[version]
Please visit Maven Dependency Tree to know more.


text:
Q: Is it correct to use Kafka consumer pool? Time to time, I need to read records from specific partition with specific offset of same topic.
I can create new kafka consumer for each time. However, I can create pool of consumers and use it in this way:
List<KafkaConsumer> consumers = new ArrayList<>();

// acquire consumer
KafkaConsumer consumer = consumers.get(0);
TopicPartition topicPartition = new TopicPartition("my-topic", 42);
consumer.assign(List.of(topicPartition));
consumer.seek(topicPartition, 13);

ConsumerRecords records = consumer.poll(0);
// process records
// .....

// release consumer
consumer.unsubscribe();

Should I make consumer pool? Or it is not effective, and I should create new consumer for each using.

A: You need just one consumer. Just unsubscribe and reassign it to another TopicPartition.
String topic = "my-topic";
int partition = 42;
int offset = 13;
boolean running = true;

while(running) {
    TopicPartition topicPartition = new TopicPartition(topic, partition);
    consumer.assign(List.of(topicPartition));
    consumer.seek(topicPartition, offset);

    ConsumerRecords records = consumer.poll(0);
    // process records
    // .....

    // release consumer
    consumer.unsubscribe();
    // Change topic, partition, offset as needed
}


text:
Q: Django CreateView form can't submit My views:
class AddSuiteView(CreateView):
    model = TestSuite
    form_class = TestSuiteForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        my_TestCase = TestCase.objects.all()
        context['my_testcase'] = my_TestCase
        return context
    def get_success_url(self):
        return reverse("integratedTest:testSuite")

My form.py:
class TestSuiteForm(forms.ModelForm):
    class Meta:
        model = TestSuite
        fields = ( 'name', 'test_case_list', 'created_by' )

My model is:
class TestSuite(models.Model):
    name = models.CharField(max_length=200)
    test_case_list = models.CharField(max_length=200, validators=[validate_comma_separated_integer_list], default = "1")
    created_by = models.CharField(max_length=200, default = "anyone")
    create_datetime = models.DateTimeField("TestSuite created on", auto_now = True)

class TestCase(models.Model):
      name = models.CharField(max_length=200)
       .....

My html is a bit complex:
<form method="post">
{% csrf_token %}

Create Test Suite:

  Name:
  <input type="text" id="id_name" name="name" required>

  test_case_list(double click to add):

  <select size=10 name="test_case_list_select_l" id="id_test_case_list_select_l" class="multiselect" multiple="multiple" >
  {%for case in my_testcase %}
    <option value="{{case.name}}" >{{case.name}}</option>
  {%endfor %}
  </select>

  test case selected(double click to remove):

  <select size=10 name="test_case_list_select_r" id="id_test_case_list_select_r" class="multiselect" multiple="multiple" >
  </select>
  <input type="hidden" id="id_test_case_list" name="test_case_list" value="">

⇧
  <input type="button" id="addTestcaseByOne" value="++" onclick="addTestcaseByOne">

⇩
  <input type="button" id="decreaseTestcaseByOne" value="--" onclick="decreaseTestcaseByOne">

  created_by:
  <input type="text" id="id_created_by" name="created_by" ">

  <input type="submit" value="Save">
</form>

Details: Upper list selection(name="test_case_list_select_l") is a full list. Double clicking options in upper list can add a same named one to the lower list(name="test_case_list_select_r") and the hidden input(name="test_case_list") get a new value. Hopefully, the hidden input will update the field test_case_list
The code seems good to me, but unfortunately it can't save. After input everything and click save the button, the page never redirect and model TestSuite have no new record. The selected list becomes empty immediately instead.

P.S. My form.html is coming from the Django tutorial:
<form method="post">
{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save">
</form>

I add an additional button to test the value to be submitted.
<input type="submit" value="test" onclick="testButton()">

script as:
function testButton(){
        valu = $('#id_test_case_list').val()
        alert("valu:" + valu)
    }

After select some cases, the first click button shows valu is the correct strings as I expected. But the selected list is cleared immediately after the button click. The repeatedly clicking of testButton also displays valu as blank.
I resolved this issue after I modified the model from test_case_list = models.CharField(max_length=200, validators=[validate_comma_separated_integer_list], default = "1")
to
test_case_list = models.CharField(max_length=200, default = "1")

by which I deleted the validators=[validate_comma_separated_integer_list].
I forgot it's not comma_separated_integer_list but comma_separated_string_list, I didn't know if there's any comma_separated_string_list

A: action="/your-name/" is missing in your form tag.
<form action="/your-route" method="post">
.
.
.
<button type="submit">Submit</button>
</form>


text:
Q: CSS: Dock element to bottom of page and its top to bottom of upper element? I need to glue an element to the bottom and to the top, but I want to keep a dynamic space from the top that another element goes in, I want the top to be that element size + some space.
How is this possible (Pure CSS preferred)?
Here is an example:
HTML:

Hello and welcome to my demo!

    I want this area to be glued to the footer + 10px space
    And additionally, glued to the element on top of itself + 10px
    The slider can disappear, which should result in the content
    to grow and reach the heaader.

    All rights reserved.

CSS:
.center
{
    width: 200px;
    margin-left: auto;
    margin-right: auto;
    right: 0px;
    left: 0px;
}

#header
{
    background: green;
    color: white;
    height: 50px;
    position: fixed;
    top: 0px;
}

#slider
{
    height: 60px;
    position: fixed;
    top: 60px;
}
#slider img
{
    max-width: 100%;
}

#content
{
    background: beige;
    height: 50px;
    bottom: 10px;
}

footer
{
    background: blue;
    color: white;
    height: 50px;
    position: fixed;
    bottom:0px;
}

A: not sure with css but js you can try something like this:
document.getElementById('header').style.top = document.getElementById('newelement').style.height;

Right with the new element insert.

A: The only way to do a CSS-only solution today would be to give % heights on all the elements.
At some point in the future, hopefully, we will all be able to use the new CSS for grid layouts to accomplish exactly what you need.

A: This might be useful for you:
Create a
 outside main-content div and give it a position:relative.


text:
Q: Error while installing the node modules in Jenkins I have a job in Jenkins that runs the protractor tests. During some bug fix, I removed the node_modules by using the shell command rm -rf node_modules/.
Now I am trying to install the node_modules again by using the command npm install. During this installation, for every module it is installing I can see the comment as 'The package has been renamed to open'. I am not sure why is it coming up.
Once the installation is done, on the execution of the command 'webdriver-manager update --standalone false --gecko false' , it is throwing an error saying the module 'rimraf' is not available, which is a bit strange as I can see that is already installed.
What could be the issue ? How can I overcome this problem?
I tried clearing cache to make sure that it is not influenced by cache. checked the node_modules folder to make sure that the names of all the modules are correct and not open. Checked with all the possible commands to install the node modules.
11:44:51 npm WARN deprecated acorn-dynamic-import@4.0.0: The package has been renamed to `open`
11:44:51 npm WARN deprecated app-root-path@2.2.1: The package has been renamed to `open`
11:44:51 npm WARN deprecated arraybuffer.slice@0.0.7: The package has been renamed to `open`
11:44:51 npm WARN deprecated blob@0.0.5: The package has been renamed to `open`
11:44:51 npm WARN deprecated browser-resolve@1.11.3: The package has been renamed to `open`
11:44:51 npm WARN deprecated util@0.10.4: The package has been renamed to `open`
11:44:51 npm WARN deprecated buffer-more-ints@1.0.0: The package has been renamed to `open`
11:44:51 npm WARN deprecated cached-path-relative@1.0.2: The package has been renamed to `open`
11:44:51 npm WARN deprecated circular-json@0.5.9: The package has been renamed to `open`
11:44:51 npm WARN deprecated code-block-writer@7.3.1: The package has been renamed to `open`
11:44:51 npm WARN deprecated command-exists@1.2.8: The package has been renamed to `open`
11:44:51 npm WARN deprecated data-uri-to-buffer@2.0.1: The package has been renamed to `open`
11:44:51 npm WARN deprecated diff@3.5.0: The package has been renamed to `open`
11:44:51 npm WARN deprecated fastparse@1.1.2: The package has been renamed to `open`
11:44:51 npm WARN deprecated clone@1.0.4: The package has been renamed to `open`
11:44:51 npm WARN deprecated engine.io-parser@2.1.3: The package has been renamed to `open`
11:44:51 npm WARN deprecated https-proxy-agent@2.2.1: The package has been renamed to `open`
11:44:51 npm WARN deprecated buffer@5.2.1: The package has been renamed to `open`
11:44:51 npm WARN deprecated crc@3.8.0: The package has been renamed to `open`
11:44:51 npm WARN deprecated ini@1.3.5: The package has been renamed to `open`
11:44:51 npm WARN deprecated generate-function@2.3.1: The package has been renamed to `open`
11:44:51 npm WARN deprecated isbinaryfile@3.0.3: The package has been renamed to `open`
11:44:51 npm WARN deprecated jasmine-core@2.8.0: The package has been renamed to `open`
11:44:51 npm WARN deprecated opn@6.0.0: The package has been renamed to `open`
11:44:51 npm WARN deprecated make-error@1.3.5: The package has been renamed to `open`
11:44:51 npm WARN deprecated merge2@1.2.3: The package has been renamed to `open`
11:44:51 npm WARN deprecated debug@3.1.0: The package has been renamed to `open`
11:44:51 npm WARN deprecated http-proxy-agent@2.1.0: The package has been renamed to `open`
11:44:52 npm WARN deprecated nice-try@1.0.5: The package has been renamed to `open`
11:44:52 npm WARN deprecated istanbul-lib-report@1.1.5: The package has been renamed to `open`
11:44:52 npm WARN deprecated @types/node@6.14.6: The package has been renamed to `open`
11:44:52 npm WARN deprecated adm-zip@0.4.13: The package has been renamed to `open`
11:44:52 npm WARN deprecated qjobs@1.2.0: The package has been renamed to `open`
11:44:52 npm WARN deprecated regenerate@1.4.0: The package has been renamed to `open`
11:44:52 npm WARN deprecated css-selector-tokenizer@0.7.1: The package has been renamed to `open`
11:44:52 npm WARN deprecated basic-auth@2.0.1: The package has been renamed to `open`
11:44:52 npm WARN deprecated morgan@1.9.1: The package has been renamed to `open`

11:47:35 + npm run e2e -- --suite=validateObjects --baseUrl=*******
11:47:36
11:47:36 > solaris@1.0.0 pree2e /var/jenkins_home/workspace/Solaris Protractor tests - IFD Test
11:47:36 > webdriver-manager update --standalone false --gecko false
11:47:36
11:47:36 module.js:478
11:47:36     throw err;
11:47:36     ^
11:47:36
11:47:36 Error: Cannot find module 'rimraf'
11:47:36     at Function.Module._resolveFilename (module.js:476:15)
11:47:36     at Function.Module._load (module.js:424:25)
11:47:36     at Module.require (module.js:504:17)
11:47:36     at require (internal/module.js:20:19)
11:47:36     at Object.<anonymous> (/var/jenkins_home/workspace/Solaris Protractor tests - IFD Test/node_modules/protractor/node_modules/webdriver-manager/built/lib/binaries/android_sdk.js:4:16)
11:47:36     at Module._compile (module.js:577:32)
11:47:36     at Object.Module._extensions..js (module.js:586:10)
11:47:36     at Module.load (module.js:494:32)
11:47:36     at tryModuleLoad (module.js:453:12)
11:47:36     at Function.Module._load (module.js:445:3)
11:47:36

A: I searched that error and a package called opn which is now deprecated came up, check out the author message. I am guessing this is due to your package-lock.json file referencing older versions of packages which are still calling the original opn package.
Would it be acceptable for you to remove the package-lock.json and try npm install once more?

A: Thanks for your inputs.
I got the issue solved and the reason is quite simple.
figured out that the node versions are different from Jenkins and the workspace and hence this issue has occurred. on using the node version from Jenkins, I am able to execute the tests.
Hope this helps someone.


text:
Q: Cassandra 3.11 UDF operating system stack overflow I'm using Cassandra 3.11 on RHEL. I defined a UDF exactly as described here.
CREATE OR REPLACE FUNCTION maxOf(current int, testvalue int)
CALLED ON NULL INPUT
RETURNS int
LANGUAGE java
AS $$return Math.max(current,testvalue);$$;

I'm able to create the UDF. But when I run the following query:
SELECT id,val1,val2,maxOf(val1,val2) FROM test WHERE id IN(1,2,3);

I get the following error:
com.datastax.driver.core.exceptions.FunctionExecutionException: execution of 'srm.maxof[int, int]'
failed: java.lang.RuntimeException: java.lang.StackOverflowError: operating system stack overflow

I have already set enable_user_defined_functions: true in cassandra.yaml on all nodes.
Here's a snippet from system.log that includes JVM -X parameters:
-XX:+UseThreadPriorities, -XX:ThreadPriorityPolicy=42, -XX:+HeapDumpOnOutOfMemoryError, -Xss512k, -XX:StringTableSize=1000003, -XX:+AlwaysPreTouch, -XX:-UseBiasedLocking, -XX:+UseTLAB, -XX:+ResizeTLAB, -XX:+UseNUMA, -XX:+PerfDisableSharedMem, -Djava.net.preferIPv4Stack=true, -XX:+UseParNewGC, -XX:+UseConcMarkSweepGC, -XX:+CMSParallelRemarkEnabled, -XX:SurvivorRatio=8, -XX:MaxTenuringThreshold=1, -XX:CMSInitiatingOccupancyFraction=75, -XX:+UseCMSInitiatingOccupancyOnly, -XX:CMSWaitDuration=10000, -XX:+CMSParallelInitialMarkEnabled, -XX:+CMSEdenChunksRecordAlways, -XX:+CMSClassUnloadingEnabled, -XX:+PrintGCDetails, -XX:+PrintGCDateStamps, -XX:+PrintHeapAtGC, -XX:+PrintTenuringDistribution, -XX:+PrintGCApplicationStoppedTime, -XX:+PrintPromotionFailure, -XX:+UseGCLogFileRotation, -XX:NumberOfGCLogFiles=10, -XX:GCLogFileSize=10M, -Xms8192M, -Xmx8192M, -Xmn2048M

This only happens when using the IBM JRE. Works fine with the Oracle JRE.
Here's the stack trace in debug.log:
java.lang.RuntimeException: java.lang.StackOverflowError
    at org.apache.cassandra.cql3.functions.UDFunction.async(UDFunction.java:453) ~[apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.functions.UDFunction.executeAsync(UDFunction.java:398) ~[apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.functions.UDFunction.execute(UDFunction.java:298) ~[apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.selection.ScalarFunctionSelector.getOutput(ScalarFunctionSelector.java:61) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.selection.Selection$SelectionWithProcessing$1.getOutputRow(Selection.java:592) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.selection.Selection$ResultSetBuilder.getOutputRow(Selection.java:430) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.selection.Selection$ResultSetBuilder.build(Selection.java:417) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.statements.SelectStatement.process(SelectStatement.java:763) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.statements.SelectStatement.processResults(SelectStatement.java:400) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:378) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:251) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.statements.SelectStatement.execute(SelectStatement.java:79) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.QueryProcessor.processStatement(QueryProcessor.java:217) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:248) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.QueryProcessor.process(QueryProcessor.java:233) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.transport.messages.QueryMessage.execute(QueryMessage.java:116) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:517) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.transport.Message$Dispatcher.channelRead0(Message.java:410) [apache-cassandra-3.11.0.jar:3.11.0]
    at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105) [netty-all-4.0.44.Final.jar:4.0.44.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:357) [netty-all-4.0.44.Final.jar:4.0.44.Final]
    at io.netty.channel.AbstractChannelHandlerContext.access$600(AbstractChannelHandlerContext.java:35) [netty-all-4.0.44.Final.jar:4.0.44.Final]
    at io.netty.channel.AbstractChannelHandlerContext$7.run(AbstractChannelHandlerContext.java:348) [netty-all-4.0.44.Final.jar:4.0.44.Final]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:522) [na:1.8.0]
    at org.apache.cassandra.concurrent.AbstractLocalAwareExecutorService$FutureTask.run(AbstractLocalAwareExecutorService.java:162) [apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.concurrent.SEPWorker.run(SEPWorker.java:109) [apache-cassandra-3.11.0.jar:3.11.0]
    at java.lang.Thread.run(Thread.java:795) [na:2.9 (09-01-2017)]
Caused by: java.lang.StackOverflowError: null
    at java.lang.String.substring(String.java:2637) ~[na:2.9 (09-01-2017)]
    at java.lang.Class.getNonArrayClassPackageName(Class.java:1531) ~[na:2.9 (09-01-2017)]
    at java.lang.Class.getPackageName(Class.java:1546) ~[na:2.9 (09-01-2017)]
    at java.lang.J9VMInternals$2.run(J9VMInternals.java:252) ~[na:2.9 (09-01-2017)]
    at java.security.AccessController.doPrivileged(AccessController.java:647) ~[na:1.8.0]
    at java.lang.J9VMInternals.checkPackageAccess(J9VMInternals.java:250) ~[na:2.9 (09-01-2017)]
    at org.apache.cassandra.cql3.functions.ThreadAwareSecurityManager.isSecuredThread(ThreadAwareSecurityManager.java:210) ~[apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.cql3.functions.ThreadAwareSecurityManager.checkPackageAccess(ThreadAwareSecurityManager.java:259) ~[apache-cassandra-3.11.0.jar:3.11.0]
[Previous 5 lines repeat many times]
    at java.lang.J9VMInternals$2.run(J9VMInternals.java:254) ~[na:2.9 (09-01-2017)]
    at java.security.AccessController.doPrivileged(AccessController.java:647) ~[na:1.8.0]
    at java.lang.J9VMInternals.checkPackageAccess(J9VMInternals.java:250) ~[na:2.9 (09-01-2017)]
    at org.apache.cassandra.cql3.functions.UDFunction$$Lambda$277.00000000154A7350.call(Unknown Source) ~[na:na]
    at java.util.concurrent.FutureTask.run(FutureTask.java:277) ~[na:1.8.0]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1160) ~[na:1.8.0]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) ~[na:1.8.0]
    at org.apache.cassandra.concurrent.NamedThreadFactory.lambda$threadLocalDeallocator$0(NamedThreadFactory.java:81) ~[apache-cassandra-3.11.0.jar:3.11.0]
    at org.apache.cassandra.concurrent.NamedThreadFactory$$Lambda$12.0000000013A22FB0.run(Unknown Source) ~[na:na]
    ... 1 common frames omitted

Is there some configuration I'm missing? Do I need to increase some stack size parameter?

A: UDFs are by default disabled since Cassandra 3.0. To enable them, you need to set enable_user_defined_functions: true in cassandra.yaml file.


text:
Q: Configure Logger Programmatically I want to configure my java.util.logging.Logger programmatically. According to the Oracle Docs, it seems possible.
However this example shows something is wrong here:
public static void main(String[] args) {
    Logger logger = Logger.getLogger("org.acme.project");
    logger.setLevel(Level.SEVERE);
    logger = null;

    System.gc();

    logger = Logger.getLogger("org.acme.project");
    logger.warning("You shouldn't see this warning!");
    logger.severe("But this error!");
}

If you run the code, you'll see both messages. However if you remove logger = null; or System.gc(); you'll only see the correct second one, which proves the garbage collector just removes the configured logger leaving Logger.getLogger(String) with creating a new (default) one.
To "solve" this, I could just hold a reference to that particular logger somewhere, but I don't think that's a good idea.
So how do I define a logger programmatically?

A:
To "solve" this, I could just hold a reference to that particular logger somewhere, but I don't think that's a good idea.

In releases prior to JDK6u18 the LogManager held strong reference to the logger. After that patch, the java.util.logging.Logger.getLogger() method points the reader towards holding a strong reference:

Note: The LogManager may only retain a weak reference to the newly created Logger. It is important to understand that a previously created Logger with the given name may be garbage collected at any time if there is no strong reference to the Logger. In particular, this means that two back-to-back calls like getLogger("MyLogger").log(...) may use different Logger objects named "MyLogger" if there is no strong reference to the Logger named "MyLogger" elsewhere in the program.

A common idiom is to use:
private static final String CLASS_NAME = Foo.class.getName();
private static final Logger logger = Logger.getLogger(CLASS_NAME);

The reason you define the CLASS_NAME too is that you'll use it for the log tracing methods or the logp methods
Also, tools like FindBugs will detect this lost logger pattern as:

LG: Potential lost logger changes due to weak reference in OpenJDK (LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE)

A: The Javadoc for Logger#getLogger references your problem:
https://docs.oracle.com/javase/7/docs/api/java/util/logging/Logger.html#getLogger%28java.lang.String%29

Note: The LogManager may only retain a weak reference to the newly created Logger. It is important to understand that a previously created Logger with the given name may be garbage collected at any time if there is no strong reference to the Logger. In particular, this means that two back-to-back calls like getLogger("MyLogger").log(...) may use different Logger objects named "MyLogger" if there is no strong reference to the Logger named "MyLogger" elsewhere in the program.

In turn Logger#getLogger calls LogManager#addLogger and its documentation also encourages you to hold a reference:
https://docs.oracle.com/javase/7/docs/api/java/util/logging/LogManager.html#addLogger%28java.util.logging.Logger%29

The application should retain its own reference to the Logger object to avoid it being garbage collected. The LogManager may only retain a weak reference.


text:
Q: WPF Bottomless DataGrid keeps expanding downward I've got this Grid which contains a TabControl with a number of TabItem.
Each TabItem loads a UserControl.
<Grid>
    <TabControl>
        <TabItem>
            <local:UsersControl/>
        </TabItem>
    </TabControl>
</Grid>

In this specific UserControl I placed a Grid with nested a DockPanel, left side for menu, right for content.
On the right side are loaded a Border containing a single UserControl relative to the selection on the menu on the left.
<Grid>
    <DockPanel>
        <Border>
            <UserControl Content="{Binding MainDock, UpdateSourceTrigger=PropertyChanged}"/>
        </Border>
    </DockPanel>
</Grid>

Finally, the UserControl consists of a StackPanel which contains a TextBlock and a ScrollViewver with inside a DataGrid.
<StackPanel>
    <TextBlock/>
    <ScrollViewer>
        <DataGrid>
            <!-- datagrid stuff -->
        </DataGrid>
    </ScrollViewer>
</StackPanel>

The problem consist in the latest StackPanel being bottomless and expanding well over the bottom of the window application, which never activate the ScrollViewer hiding part of the grid data, when there are enough rows.
Any idea how to solve this?


text:
Q: Saved 9800 WLC file cuts off configuration I am having an issue where my script logs into a Cisco WLC 9800, sends the commands "show run" and then saves it to a file, but the file cuts off a big chunk of the config.  I verified with a debug that the whole configuration is pulled from the command, just can't figure out why it is not working.  I have no issue pulling a full "show run" from a Cisco 4500 switch.
Here is my script:
device = {
   'device_type': 'cisco_ios',
   'ip': 'IP',
   'username': 'username',
   'password': 'password',
    }
##opening IP file
ipfile = open("C:\XXXX\switch-ips.txt")
print("Script to take backup of devices, Please enter your credentials")
device['username'] = input("User name: ")
device['password'] = getpass.getpass()

##taking backup
for line in ipfile:
    try:
       device['ip'] = line.strip("\n")
       print("\n\nConnecting to Device ", line)
       net_connect = netmiko.ConnectHandler(**device)
       net_connect.enable()
       time.sleep(1)
       print("Reading the hostname")
       hostname = (net_connect.send_command('show run | i host').split()[1])
       print(hostname)
       print("Reading the running config ")
       output = net_connect.send_command('show run')
       time.sleep(2)
       filename = r'C:\\Users\\XXXX\\Script Results\\' + hostname + '-' + today + ".txt"
       saveconfig = open(filename, 'w+')
       print("Writing Configuration to file")
       saveconfig.write(output)
       saveconfig.close()
       time.sleep(2)
       net_connect.disconnect()
       print("Configuration saved to file", filename)
   except:
       print("Access to " + device['ip'] + " failed, backup did not taken")
       continue
ipfile.close()


text:
Q: UNIX Copy/Move files in same directory preserving timestamp Following is the scenario. There are multiple files in a directory created by users belonging to same unix group.
Unix Group: Prod.
User in Prod Unix Group: User1 User2 User3.
All 3 users have same privileges.
Scenario 1
If user3 wants to become owner of the files created by user1 and user2 by preserving datetime stamp  what is the command user3 needs to execute?
Scenario 2
Can user copy/move the same file in same directory by preserving datetimestamp? What is the command for it?
Scenario3:
I tried touch command for the file created by User1. Ownership is changed however timestamp is updated too. Is there a way that timestamp remains the same using touch command?
Thanks.

A: Only root can change ownership of files, so user3 will need to be able to use sudo to change ownership of files belonging to user1 and user2.
mv will always preserve all metadata, including modification time and user and group ownership. cp -p will try to preserve all these, but as stated above you can't create files with owner other than yourself, so user and group ownership of files copied with cp -p won't be preserved if you're not already the owner.
touch is designed to change the modification time. I do not see how using touch can change the ownership, I would like to see steps how to reproduce what you saw. However you can use touch --reference=filename filename to preserve the modification time, but it would be useless as it would actually not do anything.