text:
Q: How can i apply Chebyshev's inequality to this case? I have the a dataframe which includes heights. The data can not go below zero. That's why i can not use standard deviation as this data is not a normal distribution. I can not use 68-95-99.7 rule here because it fails in my case. Here is my dataframe, mean and SD.
0.77132064
0.02075195
0.63364823
0.74880388
0.49850701
0.22479665
0.19806286
0.76053071
0.16911084
0.08833981

Mean: 0.41138725956196015
Std: 0.2860541519582141

If I get 2 std, as you can see the number becomes negative.
-2 x std calculation = 0.41138725956196015 - 0.2860541519582141 x 2 = -0,160721044354468

I have tried using percentile and not satisfied with it to be honest. How can i apply Chebyshev's inequality to this problem? Here what i did so far:
np.polynomial.Chebyshev(df['Heights'])

But this returns numbers not a SD level i can measure. Or do you think Chebyshev is the best choice in my case?
Expected solution:
I am expecting to get a range like 75% next height will be between 0.40 - 0.43 etc.

EDIT1: Added histogram
To be more clear, I have added my real data's histogram

EDIT2: Some values from real data
Mean: 0.007041500928135767
Percentile 50: 0.0052000000000000934
Percentile 90: 0.015500000000000047
Std: 0.0063790857035425025
Var: 4.06873389299246e-05

Thanks a lot

A: You seem to be confusing two ideas from the same mathematician, Chebyshev. These ideas are not the same.
Chebysev's inequality states a fact that is true for many probability distributions. For two standard deviations, it states that three-fourths of the data items will lie within two standard deviations from the mean. As you state, for normal distributions about 19/20 of the items will lie in that interval, but Chebyshev's inequality is an absolute bound that is met by practically all distributions. The fact that your data values are never negative does not change the truth of the inequality; it just makes the actual proportion of values in the interval even larger, so the inequality is even more true (in a sense).
Chebyshev polynomials do not involve statistics, but are simply a series (or two series) of polynomials, commonly used in calculating approximations for computer functions. That is what np.polynomial.Chebyshev involves, and therefore does not seem useful to you at all.
So calculate Chebyshev's inequality yourself. There is no need for a special function for that, since it is so easy (this is Python 3 code):
def Chebyshev_inequality(num_std_deviations):
    return 1 - 1 / num_std_deviations**2

You can change that to handle the case where k <= 1 but the idea is obvious.
In your particular case: the inequality says that at least 3/4, or 75%, of the data items will lie within 2 standard deviations of the mean, which means more than 0.41138725956196015 - 2 * 0.2860541519582141 and less than than 0.41138725956196015 + 2 * 0.2860541519582141 (note the different signs), which simplifies to the interval
[-0.16072104435446805, 0.9834955634783884]

In your data, 100% of your data values are in that interval, so Chebyshev's inequality was correct (of course).
Now, if your goal is to predict or estimate where a certain percentile is, Chebyshev's inequality does not help much. It is an absolute lower bound, so it gives one limit to a percentile. For example, by what we did above we know that the 12.5'th percentile is at or above -0.16072104435446805 and the 87.5'th percentile is at or below 0.9834955634783884. Those facts are true but are probably not what you want. If you want an estimate that is closer to the actual percentile, this is not the way to go. The 68-95-99.7 rule is an estimate--the actual locations may be higher or lower, but if the distribution is normal than the estimate will not be far off. Chebyshev's inequality does not do that kind of estimate.
If you want to estimate the 12.5'th and 87.5'th percentiles (showing where 75 percent of all the population will fall) you should calculate those percentiles of your sample and use those values. If you don't know more details about the kind of distribution you have, I don't see any better way. There are reasons why normal distributions are so popular!

A: It sounds like you want the boundaries for the middle 75% of your data.
The middle 75% of the data is between the 12.5th percentile and the 87.5th percentile, so you can use the quantile function to get the values at the locations:
[df['Heights'].quantile(0.5 - 0.75/2), df['Heights'].quantile(0.5 + 0.75/2)]
#[0.09843618875, 0.75906485625]

A: As per What does it mean when the standard deviation is higher than the mean? What does that tell you about the data? - Quora, SD is a measure of "spread" and mean is a measure of "position". As you can see, these are more or less independent things. Now, if all your samples are positive, SD cannot be greater than the mean because of the way it's calculated, but 2 or 3 SDs very well can.
So, basically, SD being roughly equal to the mean means that your data are all over the place.
Now, a random variable that's strictly positive indeed cannot be normally distributed. But for a rough estimation, seeing that you still have a bell shape, we can pretend it is and still use SD as a rough measure of the spread (though, since 2 and 3 SD can go into negatives, they lack any physical meaning here whatsoever and so are unusable for the sake of our pretention):

E.g. to get a rough prediction of grass growth, you can still take the mean and apply whatever growth model you're using to it -- that will get the new, prospective mean. Then applying the same to mean±SD will give an idea of the new SD.
This is very rough, of course. But to get any better, you'll have to somehow check which distribution you're dealing with and use its peak and spread characteristics instead of mean and SD. And in any case, your prediction will not be any better than your growth model -- studies of which are anything but conclusive judging by e.g. https://onlinelibrary.wiley.com/doi/pdf/10.1111/j.1365-3040.2005.01490.x (not a single formula there).


text:
Q: Error collect2: error: ld returned 1 exit status in ESPhome on RP pico w I'm having an issue with configuring the BME280 sensor. It keeps giving me the following error: collect2: error: ld returned 1 exit status. I really don't know what's wrong with it.
esphome:
  name: raspberry-pi-pico-w--2
  friendly_name: Raspberry Pi Pico w - 2

rp2040:
  board: rpipico
  framework:
    # Required until https://github.com/platformio/platform-raspberrypi/pull/36 is merged
    platform_version: https://github.com/maxgerhardt/platform-raspberrypi.git

# Enable logging
logger:

# Enable Home Assistant API
api:
  encryption:
    key: "MlSWE56GvIvD5jLsGN9/GbyDcd4Xhga7sWVZCHko2+M="

ota:
  password: "bfdfe6650c2121f904a56194af707ae4"

wifi:
  ssid: Stoupik
  password: password

i2c:
  sda: 00
  scl: 01
  scan: true
  id: bus_a

sensor:
  - platform: bme280
    address: 0x77
    temperature:
      name: "Teplota"
      id: bme280_temperature
    pressure:
      name: "Tlak"
      id: bme280_pressure
    humidity:
      name: "Vlhkost"
      id: bme280_humidity
    update_interval: 60s

I have tried to repeat it and make changes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Approximating a discontinuous by a smooth function The discontinuous function I want to approximate is defined as $x \mapsto g(x) : \mathbb{R}_+\mapsto \mathbb{R}_-$ with $g(x) := -x\mathbb{1}_{x < b}$ where $b > 0$ is some given real number.
I want to approximate this function on the whole nonnegative real line by a smooth function, $f$. $f$ has to satisfy $f(0,p) = 0$ for every $p$. Here $p$ is some real-valued parameter. So $f(\cdot,p)$ can be considered a family of functions indexed by $p$. This approximation should be such that for every $\varepsilon > 0$ I should be able to find a $p$ with
$$\sup_{x\geq 0} \lvert f(x,p) - g(x)\rvert < \varepsilon$$
Can such an approximation exist? If yes, can someone give a few examples?

A: No. Such an approximation is impossible.
Consider the point $x = b$.
Let $\epsilon \in (0,b/8)$ be arbitrary. For every $p$, by continuity, there exists a $\delta \in (0,b/4)$ such that for every $y\in (b-\delta,b+\delta)$, we have
$$ |f(b,p) - f(y,p)| < \frac{b}{8} $$
On the other hand, we have that
\begin{align} b - \delta/2 &= | g(b+\delta/2) - g(b-\delta/2) |\\ &\leq |g(b+\delta/2) - f(b+\delta/2,p)| + \\ &\qquad |f(b+\delta/2,p) - f(b-\delta/2,p)| + |f(b-\delta/2,p) - g(b-\delta/2)| \end{align}
by triangle inequality, which implies that
$$ 4 \epsilon < \frac{b}{2} < | g(b+\delta/2) - f(b+\delta/2,p) | + |f(b-\delta/2,p) - g(b-\delta/2)| $$
In fact, the proof above shows that for any continuous function $h$, the inequality
$$ \sup_{x\geq 0} |h(x) - g(x)| > \frac{b}{4} \tag{1}$$
always holds; and hence the inequality you want cannot be true.

Note, equation (1) is far from sharp. In fact, one can show that for any $\eta > 0$ there is an analogue of (1) with the right hand side replaced by $b/2 - \eta$.


text:
Q: How can I use the same name for singular and plural form in Ember? I have a type media. I would like to use that name for both the singular and the plural forms. but I am struggling to figure out how to do so. I imaging it is by adjusting Ember.Inflector but I have sent every variation at it that I can think of with no luck.
Note: I am currently stuck on Ember 1.13, and upgrading it really isn't feasible right now.


text:
Q: Displaying content of the Link Layer Header Are there any debian Linux programs whose commands I can call in a C program, that express a packet's metadata (e.g. protocol, packet length, source and destination ports)? I would use readFrom and sockaddr* structure but I want to be able to receive TCP traffic as well.
Is there any way of using tcpdump to create the string containing this information?
Also, is there anything conceptually wrong in the expression or content of this question?

A: You can use packet capturing library like PCAP in your C program. You can capture whole packet and analyse its contents. You can even apply packet filtering.
As far as reading is concerned, you can read data from socket just like any other device or file with read system call by giving socket's file descriptor.

A: There are various alternatives you can use:
1-PCAP as mentioned by Jewel Thief. Example code:
int datalink;
char *device;
pcap_t *pd;
int snaplen = MAX_MSG_LEN;
#define CMD "tcp and dst port %d"

void open_pcap()
{
    uint32_t localnet;
    uint32_t netmask;
    char cmd[300];
    char errbuf[PCAP_ERRBUF_SIZE];
    struct bpf_program fcode;

    device = pcap_lookupdev(errbuf);
    if (device == NULL)
    {
        printf("ERROR-1: open_pcap:%s\n", errbuf);
        exit(3);
    }

    printf("DEVICE: %s\n", device);

    pd = pcap_open_live(device, snaplen, 0, 500, errbuf);

    if (pd == NULL)
    {
        printf("ERROR-2-%s\n", errbuf);
        exit(4);
    }

    if (pcap_lookupnet(device, &localnet, &netmask, errbuf) < 0)
    {
        printf("ERROR-3-%s\n", errbuf);
        exit(5);
    }

    snprintf(cmd, sizeof(cmd), CMD, 80);

    if (pcap_compile(pd, &fcode, cmd, 0, netmask) < 0)
    {
        printf("ERROR-4-%s\n", pcap_geterr(pd));
        exit(6);
    }

    if (pcap_setfilter(pd, &fcode) < 0)
    {
        printf("ERROR-5-%s\n", pcap_geterr(pd));
        exit(7);
    }

    datalink = pcap_datalink(pd);

    if (datalink < 0)
    {
        printf("ERROR-6-%s\n", pcap_geterr(pd));
        exit(8);
    }

    printf("DATALINK: %d\n", datalink);
}

int getNext(char *msg)
{
    struct pcap_pkthdr hdr;
    char *ptr = NULL;

    while(ptr == NULL)
    {
        ptr = (char *)pcap_next(pd, &hdr);
    }

    printf("LEN: %d - CAPLEN: %d\n", hdr.len, hdr.caplen);
    memcpy(msg, ptr, hdr.caplen);

    return hdr.caplen;
}

2-You can use packet sockets
#include <sys/socket.h>
#include <linux/if_packet.h>
#include <net/ethernet.h> /* the L2 protocols */

packet_socket = socket(AF_PACKET, int socket_type, int protocol);

3-You can call command tcpdump with a shell if you don't want to code and this is enough for your needs (look at man for parameters)


text:
Q: php isn't processed correctly Thanks in advance for your help, I am pretty sure you can solve my problem.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>title</title>

    <?php
      echo '
hello world
';
    ?>

Previous Code example does display
hello world
'; ?>

instead of the expected
hello world

This was run local with xampp V3.2.2 on a win10 OS and Chrome browser.
I hope I'm not the fiftieth person to ask this just because I couldn't google it correctly.
Thanks for your help.


text:
Q: Syntax error when querying for nodemon version after installation i am trying to work with nodemon, but it's not working after the install. pls help
nodemon Installation snippet:
abhishek@Abhisheks-MacBook-Air ~ % sudo npm i -g nodemon
Password:
/Users/abhishek/.nvm/versions/node/v8.2.1/bin/nodemon -> /Users/abhishek/.nvm/versions/node/v8.2.1/lib/node_modules/nodemon/bin/nodemon.js
+ nodemon@2.0.20
updated 1 package in 1.996s

Error when tried checking nodemon  version:
abhishek@Abhisheks-MacBook-Air ~ % nodemon -v
/Users/abhishek/.nvm/versions/node/v8.2.1/lib/node_modules/nodemon/node_modules/chokidar/index.js:941
  const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
                                                                ^^^

SyntaxError: Unexpected token ...
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:533:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/abhishek/.nvm/versions/node/v8.2.1/lib/node_modules/nodemon/lib/monitor/watch.js:6:16)

node and npm versions:
abhishek@Abhisheks-MacBook-Air ~ % node -v
v8.2.1
abhishek@Abhisheks-MacBook-Air ~ % npm -v
5.3.0


text:
Q: Why do I get compiler warnings with generics? My code is:
import java.util.*;

public class A {
public static void main(String[] args){
    List<String> list = new ArrayList();
    list.add("1"); //ok   line 1
    list.add(1); //error  line 2
}

When I run this code Java gives me an error and I know why, but even when I only use line 1 the compiler warns me. Why do I get this warning?  I don't understand what is the difference between my first example and this code:
import java.util.*;

public class A {
    public static void main(String[] args){
        List<String> list = new ArrayList<String>(); // <-- notice the second <String>
        list.add("1"); //ok   line 1
        list.add(1); //error  line 2
    }
}

A:
When I run this code Java gives me an error and I know why, but even when I only use line 1 the compiler warns me. Why do I get this warning?

When you use your code, compiler will give you a warning like
List<String> list = new ArrayList();

ArrayList is a raw type. References to generic type ArrayList should be parameterized

It says that you have to provide a parameterized type for your ArrayList as well.
List<String> list = new ArrayList<String>();

EDIT:
As sugguested by @newacct: if you are using Java 7, you could use empty angular brackets (<>) when instantiating your Collection like:
List<String> list = new ArrayList<>();

From the Java 7 documentation:

You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context.

A: Code 2 won't compile because you cannot add an int (or Integer) to a list with Strings, but you already knew that.
Speaking of code 1, there can be several reasons that the compiler will warn you, depending on what compiler you are using and what settings that compiler is using. Here are some options:

*

*In construction of parameterized objects, you must also specify the parameter. In this piece of code: List<String> list = new ArrayList(), the construction of the ArrayList object does not have a parameter, which is, on the other hand, given in the reference. The compiler suggests that you use List<String> list = new ArrayList<String>() instead.

*You are using redundant type arguments. When using the code List<SomeType> list = new ArrayList<SomeType>();, you have twice specified that the parameter should be of type SomeType. The compiler suggests that you use the diamond inference (new ArrayList<>()). That suggestion is used since Java version 1.7.

I guess your compiler is warning you about the first option above. However, my compiler does not give any warnings when testing your code.

A: This might help to understand the concept of generics: why use generics.
If you change your code as follows, there will be no errors and warnings:
import java.util.*;
public class A{

public static void main(String[] args){
    List<Object> list = new ArrayList<Object>();
    list.add("1"); //ok   code 1
    list.add(1); //error  code 2

}
}

A: You have a List of type String so you cant put in Integers.


text:
Q: Создание миграций в EF Core В общем, есть либа, где описаны модели, маппинг и контексты.
Выполняю команду:

Add-Migration InitialCreate

И меня студия посылает нафиг, говоря, что файл должен быть исполняемым.
Ок, подключаю сборку в консольное приложение и выполняю снова эту команду, но меня снова посылают...
No DbContext was found in assembly 'ConsoleApp3'. Ensure that you're using the correct assembly and that the type is neither abstract nor generic.

Хотя в сборке есть 2 DbContext.
Подскажите, какой правильный алгоритм создания миграций в моем случае?

A: Попробуйте явно указать исполняемый проект и проект в котором содержаться миграции:
Add-Migration InitialMigration -Project ClassLibrary1 -StartupProject ConsoleApp3

А вообще, должно работать и Add-Migration InitialMigration если у вас в настройках проекта стоит ConsoleApp3 как проект для запуска, а в Package Manager Console вы выбрали Default Project вашу библиотеку.


text: Q: How to set status of test step by groovy dispatch script? I have dispatch script which checking content of response and validate it. I want to, this script set status of chosen test step in chosen test case as 'OK' or 'FAILED'. I googled solutions but none of them work, and my knowledge is insufficient at this time to solve the problem. Any ideas?


text:
Q: при нажатии Start создавался new.Date (будет начальное время) ,при нажатии Stop (добавлялось в таблицу начальное время, конечное время? У меня есть кнопка "Start" при нажатии на нее, должен создаваться объект var dateBegin = new Date();, но не добавляться в таблицу. После того, как нажму кнопку "stop", должен создаваться объект var dateEnd = new Date(); и добавляться в таблицу объект dateBegin и dateEnd, т.е начальное время и конечное.
Все работает, только при нажатии на кнопку Stop, в таблицу добавляется два одинаковых значения времени, а надо, чтобы было начальное время и конечное.
Как это сделать?

<!doctype html>

<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="styles/style.css">

                    <input class="form-control" ng-model="text" placeholder = "What are you working on?" />

                                        <select  class="inputProject" ng-model="project">
                                        <option value="{{item.key}}" ng-disabled="item.key==project" ng-repeat="item in items">{{item.value}}</option>
                                    </select>

                    <input class="secundomer" ng-model="timer" placeholder = "0 Sec" />

                    <button class="btn btn-start" ng-click="addItem1(dateBegin)">Start</button>
                    <button class="btn btn-stop" ng-click="addItem(text,project,dateBegin,dateEnd)">Stop</button>

                    {{item.purchase}}
                    {{item.value}}
                    {{item.dateBegin}}
                    {{item.dateEnd}}
                    {{item.date}}

A:
$scope.addItem = function (text, project,,dateBegin,dateEnd,date) {

Синтаксическая ошибка.

var visible = true;
function addItem(text,project,date) {
    if(visible) {
        document.getElementById('btn btn-stop' ).style.display = 'none';
        visible = false;
    } else {
        document.getElementById('btn btn-stop' ).style.display = 'block';
        visible = true;
    }
}

А это и всё, что с ним связано, удали.


text:
Q: Dart check num is Double or Integer In dart, as I am a newbie using extension, I want to make a simple extension to check value is double.
extension numberExtension on num{
  bool get isInteger => (this % 1) == 0;
  bool get isDouble =>double.tryParse(this) != null;
}

here isInteger is correct, but for isDouble I get this error:

The argument type 'num' can't be assigned to the parameter type
'String'

Problem is this in isDouble getter!?

A: Replace
double.tryParse(this) != null
with
this is double

A: Assuming anything that is not an Integer is a Float or a Double;
Why not implement isDecimal instead, something like:
extension numberExtension on num {
  bool get isInteger => (this % 1) == 0;
  bool get isDecimal => (this % 1) != 0;
}

OR
extension numberExtension on num {
  bool get isInteger => this is int;
  bool get isDecimal => !(this is int);
}

Note that we could directly use "this is double" above,
but the "!(this is int)" check is simply more change-compatible,
because it would even work if Dart ever adds some new num sub-type.

Update; looking into docs tells us that:

*

*If compiled into JavaScript, there is no real int type, only doubles without decimal.

*Dart does not seem to support 32-bit float, but has 64-bit double at least.

*int is always 64-bit (just like double), but bitwise and/or shift operators truncate it into 32-bit (losing data or percision).

A: Your original approach:

extension numberExtension on num {
  bool get isInteger => (this % 1) == 0;
  bool get isDouble =>double.tryParse(this) != null;
}

doesn't work because your extension is on num, so this is a num. double.tryParse expects to parse a String.
Why don't you just check if the object is an int or double directly?
extension numberExtension on num {
  bool get isInteger => this is int;
  bool get isDouble => this is double;
}

Of course, the extension is not very useful since x.isDouble is not much more convenient to use than using x is double directly, and the latter has the benefit of allowing automatic type-promotion to occur.
(Also, for Dart for the web, where int and double types are both backed by JavaScript numbers, numbers can be reported as both int and double, but using heuristics like % 1 and double.tryParse won't help with that.)


text:
Q: What's pyperclip's interaction with sudo? Info:

*

*Ubuntu 16.04

*python 3.5

*pyperclip 1.5.27

So I was trying to install pyperclip using pip; pip install pyperclip which failed with the error:
Command "python setup.py egg_info" failed with error code -11 in /tmp/pip-build-########/pyperclip/

Looked it up, found error code 11 was mostly commonly caused because of some of a module being compiled in C? Not sure if that's right, but most people used:
sudo -H pip install pyperclip

Which worked fine for me, it installed. I then checked to see if it had gone through with:
python -c 'import pyperclip'

Which failed, with a 'module not found' error. After pip freeze, I tried to install it again (with sudo), but as it was already installed, that didn't work, so I tried sudo -H pip install -U pyperclip, which also didn't work because I had the latest version.
After scratching my head for a while, I tied sudo -H pip freeze. Suddenly, pyperclip=1.5.27 was listed. It clicked around then. sudo -H python -c 'import pyperclip'... didn't work.
So now I'm really confused.
So clearly, something in pip install pyperclip needs sudo, despite being python being unable to run pyperclip with it. What's going on here? What can I do to work around it?
Slightly more information for a work around: I'm implementing a password script that just adds the desired password to the clipboard from a encrypted file on my computer, locked with a master password. Mostly for fun, but also so I can use a large number of passwords that all would take inhuman memory to know.


text:
Q: list of event handelers I want to create a dictionary  of event handlers , or something like dictionary of method with key
and use it in method that accept key , when this function be called I search using the key and fire the event or the method
any idea

A: You can create a dictionary of EventHandler:
Dictionary<string, EventHandler> eventHandlers   // using a string or whatever you like for a key

And invoke like so:
eventHandlers[key].Invoke();

A: It's documented on MSDN: How to: Use a Dictionary to Store Event Instances (C# Programming Guide).


text:
Q: Htaccess rule for a rewrite with parameters So my current URL is: https://example.com/uDoc?id=xx
Using the rewrite, I'd like it to be https://example.com/display?id=xx&type=doc
The real problem is, that because I also have a rule(RewriteRule (.*) $1.php [L]) for silently adding the .php (uDoc?id=xx -> uDoc.php?id=xx, without it, it would result in a 404 error).
Which is somewhat interfering with the current answer given.
I have fiddled around with various htaccess rules, but I got no good results :(
I'd really appreciate it if someone could help me, when it comes to htaccess rules, I'm totally giving up...

A: You can use this rule in your root .htaccess:
RewriteEngine On

RewriteRule ^uDoc/?$ display?type=doc [L,QSA,NC]

QSA flag ensures your existing query string i.e. id=xx is carried over to new URI.


text:
Q: Why the increase in starting value of $n$ when taking derivative of power series? Why is the starting value of $n$ increased by $1$ when taking derivative of power series?
i.e.:
$f(x) = \sum_\color{red}{n=0}^{\infty} c_{n} x^{n}$
$f'(x) = \sum_\color{red}{n=1}^{\infty} nc_{n} x^{n-1}$

A: The first term is $c_0x^0 = c_0$, so is constant, so its derivative is zero. If you prefer, you could re-index:
$$f'(x) = \sum\limits_{n=0}^\infty(n+1)c_{n+1}x^n,$$ but that's slightly more writing, so most people don't.

A: Let $$f(x)=a_0+a_1x+a_2x^2+a_3x^3+...=\sum_{n=0}^\infty a_nx^n.$$
Then
$$\begin{align}
f'(x)&=\frac{d}{dx}\left(a_0+a_1x+a_2x^2+a_3x^3+...\right)\\
&=\frac{d}{dx}a_0+\frac{d}{dx}a_1x+\frac{d}{dx}a_2x^2+\frac{d}{dx}a_3x^3+...\\
&=a_0\frac{d}{dx}1+a_1\frac{d}{dx}x+a_2\frac{d}{dx}x^2+a_3\frac{d}{dx}x^3+...\\
&=a_0\cdot0+a_1\cdot1+a_2\cdot2x+a_3\cdot3x^2+...\\
&=0+1a_1+2a_2x+3a_3x^2+...\\
&=a_1x^{0}+2a_2x^{1}+3a_3x^2+...\\
&=\sum_{n=1}^{\infty}na_nx^{n-1}.
\end{align}$$


text:
Q: Javascript (MEAN Stack) - Dev Mode - why timestamp stored by Node.js shows different than the time of my laptop Kindly help with displaying correct datetime stamp.
E.g. Time on my Laptop: 02-Oct-2021 11:14am  (this is in India)
Time stored by Node and Displayed in Angular 2021-10-02T05:44:09.022Z,  i.e. 06:30 behind my time.
And this is being executed in dev mode on localhost, so it should display my laptop's time right?
Here is the code in the Node.js while saving one comment.
  const comment = {
    comment: remarks,
    userName: user.userName,
    commentBy: user.employeeName,
    commentedOn: new Date()
  }

  clientDoc.commentsArr.push(comment)
  await clientDoc.save();

and here is the code in Angular template.

        Existing Comments:

            {{i + 1}}. {{e.commentBy}} ( {{e.commentedOn}} ) :

              Edit

            {{e.comment}}

And here is the timestamp stored in MongoDb
2021-10-02T05:44:09.022+00:00

I need to sort this both for the dev mode, as well as when I deploy this code on VPS - which is also in India.

A: This happens because MongoDB always stores the timestamp in UTC.
Try below code:
var record = db.data.findOne();
var localNow = new Date( record.date.getTime() -  ( record.offset * 60000 ) );

For more reference, you can also check the MongoDB official Doc here


text:
Q: How to integrate a modal dialog I want to show AJAX error messages for form validation and want these messages centered on the screen. I was advised to use a modal window for this. I have the following code but I'm not sure how to do this. I know that I need to call the modal in the success function but unfortunately that's about the extent of my JQ knowledge.
This is my JQ script where the modal should be integrated
  success: function(data){
    ...
    if(data.success == 0){
      $(div).addClass('ajax-error');
    }

This is the modal code. This code is currently set up to work with a hyperlink that activates the window but I don't need that. The window should be invoked automatically upon error in the code above.
  $('a[name=modal]').click(function(e) {
    e.preventDefault();

    var id = $(this).attr('href');

    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    $('#mask').css({'width':maskWidth,'height':maskHeight});

    $('#mask').fadeIn(1000);
    $('#mask').fadeTo("slow",0.8);

    var winH = $(window).height();
    var winW = $(window).width();

    $(id).css('top',  winH/2-$(id).height()/2);
    $(id).css('left', winW/2-$(id).width()/2);

    $(id).fadeIn(2000);
  });

  $('.window .close').click(function (e) {
    e.preventDefault();

    $('#mask').hide();
    $('.window').hide();
  });

  $('#mask').click(function () {
    $(this).hide();
    $('.window').hide();
  });

A: I would check out the jQuery Model Dialog Plugin.
The documentation is a bit sparse, but the demo page and your friends Firefox and FireBug will paint a pretty complete picture.
It has the AutoClose feature you want.
The plugin applies an opaque mask and has DIV styles such as "dialog-header," "dialog-title," and "dialog-close" to allow you to style the appearance.


text:
Q: Calling all childs of a Parent class in python Lets say we have a parent class like the following
class P():
    @staticmethod
    def sth():
        pass

And I create several child classes that define the sth() method, something like the following
class P_a(P):
    @staticmethod
    def sth():
        #Implementation a

class P_b(P):
    @staticmethod
    def sth():
        #Implementation b

class P_c(P):
    @staticmethod
    def sth():
        #Implementation c

How would I call the sth() method of all the child classes?
At the moment, I'm just adding the classes to a list and, based on a for loop, calling the sth() method on all of them. Because that method is implemented in every class, all of them understand it and know if they should take care of the task or not (Not sure if this is the best way of doing this tho)
Is it there a way of basically calling the sth() method of all the classes that inherit from class P?

A: Try this:
class P:
    subclasses = []

    def __init_subclass__(cls, *args, **kwargs) -> None:
        P.subclasses.append(cls)

    @staticmethod
    def sth():
        print("Base Implementation")

    @classmethod
    def call_all_sth(cls):
        cls.sth()
        for klass in cls.subclasses:
            klass.sth()

class P_a(P):
    @staticmethod
    def sth():
        print("Implementation a")

class P_b(P):
    @staticmethod
    def sth():
        print("Implementation b")

class P_c(P):
    @staticmethod
    def sth():
        print("Implementation c")

P.call_all_sth()

Output is:
Base Implementation
Implementation a
Implementation b
Implementation c


text:
Q: R How to remap letters in a string I'd be grateful for suggestions as to how to remap letters in strings in a map-specified way.
Suppose, for instance, I want to change all As to Bs, all Bs to Ds, and all Ds to Fs.  If I do it like this, it doesn't do what I want since it applies the transformations successively:
"abc" %>% str_replace_all(c(a = "b", b = "d", d = "f"))

Here's a way I can do what I want, but it feels a bit clunky.
f <- function (str) str_c( c(a = "b", b = "d", c = "c", d = "f") %>% .[ strsplit(str, "")[[1]] ], collapse = "" )

"abc" %>% map_chr(f)

Better ideas would be much appreciated.
James.
P.S.  Forgot to specify.  Sometimes I want to replace a letter with multiple letters, e.g., replace all As with the string ZZZ.
P.P.S.  Ideally, this would be able to handle vectors of strings too, e.g., c("abc", "gersgaesg", etc.)

A: We could use chartr in base R
chartr("abc", "bdf", "abbbce")
#[1] "bdddfe"

Or a package solution would be mgsub which would also match and replace strings with number of characters greater than 1
library(mgsub)
mgsub("abbbce",  c("a", "b", "c"), c("b", "d", "f"))
#[1] "bdddfe"

mgsub("abbbce",  c("a", "b", "c"), c("ba", "ZZZ", "f"))
#[1] "baZZZZZZZZZfe"

A: Maybe this is more elegant? It will also return warnings when values aren't found.
library(plyr)
library(tidyverse)
mappings <- c(a = "b", b = "d", d = "f")

str_split("abc", pattern = "") %>%
  unlist() %>%
  mapvalues(from = names(mappings), to = mappings) %>%
  str_c(collapse = "")

# The following `from` values were not present in `x`: d
# [1] "bdc"


text:
Q: Inserting a node in an xml file I would like to insert a node in an xml file using Java DOM. I am actually editing a lot of contents of a dummy file in order to mofidy it like the original.
I would want to add an open node and close node in between the following file;
            <?xml version="1.0" encoding="utf-8"?>
            <Memory xmlns:xyz="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:abc="http://www.w3.org/2001/XMLSchema" Derivative="ABC"
            xmlns="http://..">

       ///////////<Address> ///////////(which I would like to insert)

            <Block ---------
            --------
            -------
            />

      ////////// </Address> /////////(which I would like to insert)

            <Parameters Thread ="yyyy" />
            </Memory>

I hereby request you to let me know how to I insert  --  in between the xml file?
Thanks in advance.!
What I have tried doing is;
            Element child = doc.createElement("Address");
    child.appendChild(doc.createTextNode("Block"));
    root.appendChild(child);

But this gives me an output like;
        <Address> Block </Address> and not the way i expect :(

And now, what I have tried is to add these lines;
            Element cd = doc.createElement("Address");
            Node Block = root.getFirstChild().getNextSibling();
        cd.appendChild(Block);
        root.insertBefore(cd, root.getFirstChild());

But still, this is not the output which i am looking for. I got this output as
               ---------

A: What you want is probably:
Node parent = block.getParentNode()
Node blockRemoved = parent.removeChild(block);
// Create address
parent.appendChild(address);
address.appendChild(blockRemoved);

This is the standard way to re-attach a node in another place under W3C DOM.

A: Here:
DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = b.parse(...);

// Parent of existing Block elements and new Address elemet
// Might be retrieved differently depending on
// actual structure
Element parent = document.getDocumentElement();
Element address = document.createElement("address");

NodeList nl = parent.getElementsByTagName("Block");
for (int i = 0; i < nl.getLength(); ++i) {
    Element block = (Element) nl.item(i);
    if (i == 0)
        parent.insertBefore(address, block);
    parent.removeChild(block);
    address.appendChild(block);
}

// UPDATE: how to pretty print

LSSerializer serializer =
    ((DOMImplementationLS)document.getImplementation()).createLSSerializer();
serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
LSOutput output =
    ((DOMImplementationLS)document.getImplementation()).createLSOutput();
output.setByteStream(System.out);
serializer.write(document, output);

A: I assume you are using the W3C DOM (e.g. http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html ). If so try
insertBefore(address, block);


text:
Q: How to trigger keydown event only for alphanumeric and special characters in Angular7? I have a keydown event and I want it to be triggered when I press alphanumeric or special characters like #$@.
  <input type="text" style="width: 70%;" [(ngModel)]= "textMessage" (keydown) ="sendTypingEvent()" >

I want to restrict the event NOT to be triggered at all for keys such as enter, escape (esc), shift, alt, tab, backspace and command (meta), arrows and f keys (f1 though f12).
Is there a way to set up a REGEX pattern at the HTML?
<input (keydown.a)="..."> --expect to trigger

I can have the event triggered and filter the key at the function call as shown below. However, trying to
see if there are any other options.
sendTypingEvent(event) {
  if (event.key === "Enter" || event.key ==='esc' .... ) {
    console.log("skip this event");
  }

}

A: Here are two ways to restrict keydown event -

*

*you allow the alphanumeric key press only

sendTypingEvent(event){
        if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 65 && event.keyCode <= 90)){
            console.log("input was 0-9");
            console.log("input was a-z");
            return true;
        }

        return false;
    }

*You can restrict specific keys

sendTypingEvent(event){
        if ((event.keyCode >= 112 && event.keyCode <= 123) || event.keyCode == 16){
            console.log("Disabled f11 to f12, shift keys");
            return false
        }
}

Get Keycode for this website -
https://keycode.info/

A:

document.getElementById("myinput").addEventListener("input", function(event) {
  if (/[!'^+%&/()=?_\-~`;#$½{[\]}\\|<>@,]/gi.test(event.data)) {
    console.log(event.data) // or
    // your operation
  }
})
<input id="myinput" type="text" style="width: 70%;">

In your case, you should edit your trigger function as below, it will show only special characters on console
sendTypingEvent(event) {
  if (/[!'^+%&/()=?_\-~`;#$½{[\]}\\|<>@,]/gi.test(event.key)) {
    console.log(event.key);
  }
}


text:
Q: How to choose the minimum value in one array that does not appear in the other using one line? nearest_distance_table = [1,4,5,9,10,14,15]
nodes_explored = [2,10,14]

I want to assign a variable next to the minimum value of nearest_distance_table that is NOT in nodes_explored.
Is there a one-liner using min() to do this? I know how to do this using a for loop, but is there a way to do it with one line with min()?
Using a for-loop:
minimum = float("inf")
for I in nearest_distance_table:
    if I < minimum and I not in nodes_explored:
        minimum = I
print(I)

A: You might use comprehension as follows
nearest_distance_table = [1,4,5,9,10,14,15]
nodes_explored = [2,10,14]
minimum = min(i for i in nearest_distance_table if i not in nodes_explored)
print(minimum)

output
1

A: You can convert the lists to sets:
lowest = min(set(nearest_distance_table).difference(nodes_explored))

Note that this will not work if you want to preserve duplicate values. For example,
nearest_distance_table = [2, 2, 4]
nodes_explored = [2]

will give 4 as the answer as the two 2s will be collapsed into a single value and then removed. This is the same behaviour as in your example.


text:
Q: Detect if a swf is running in an Android application's web view? Is it possible to detect, from within Flash, if the currently-running swf is executing from within a web view embedded within an Android application?

A: this is easily accomplished by checking the user agent of the browser .
i goggled it for you and found a topic about it .. lol i guess you just needed to know the the browser has a user agent  .
http://active.tutsplus.com/tutorials/actionscript/quick-tip-detect-the-browser-and-user-agent-with-as3/


text:
Q: How will EAP start listening to server port in Camel Context XML? OK, this might be a stupid question,
How the will EAP/ Karaf listen to 8484. Do I need to configure all ports that I'm use in Server Configuration.
<cxf:rsServer id="rsServer" address="http://localhost:8484/customerservice">

A: JBoss Fuse (Karaf) will start an instance of Jetty listening to port 8484, no need to configure it anywhere.
Different bundles will automatically re-use that instance, if listening on the same port. Jetty will be stopped after you stop the bundle.
I can't say for EAP.
I don't remember at the moment, you may or may not need to install the following features:
features:install camel-http
features:install camel-jetty


text:
Q: Linear Gradient with Round corners I am creating a background image using linear gradients. How to to add round corners for each linear gradient.
Please provide solution without any changes in html (cant use more than one div)

.myStyle {

  height:500px;
  width: 900px;

  background-image:
    linear-gradient(lightgrey , blue),
    linear-gradient(lightgrey , blue),
    linear-gradient(lightgrey , blue),
    linear-gradient(lightgrey , blue);

  background-repeat: no-repeat;

  background-size:
    100px 40px,
    500px 60px,
    250px 50px,
    250px 60px;

  background-position:
    0 0,
    0 80px,
    0 160px,
    0 220px;
}

A: Not really sure what is your goal but if you want gradient with solid color to have radius you can build it using multiple linear-gradient and radial gradient.
Here is an example where I am using CSS variable to easily define the position, size and radius. This is one of your gradient. You need to repeat the code for all the gradient and adjust the different values.

.box {
  --w:200px; /*Gradient width*/
  --h:100px; /*Gradient height*/
  --r:10px;  /*Gradient radius*/
  --x:50px;  /*Gradient position x*/
  --y:40px;  /*Gradient position y*/
  --c:grey;  /*Gradient color*/
  margin:0;
  height:100vh;
  background:
    radial-gradient(farthest-side,var(--c) 98%,transparent 100%) var(--x)  var(--y) / calc(2*var(--r)) calc(2*var(--r)),
    radial-gradient(farthest-side,var(--c) 98%,transparent 100%) calc(var(--x) + var(--w) - 2*var(--r)) var(--y) / calc(2*var(--r)) calc(2*var(--r)),
    radial-gradient(farthest-side,var(--c) 98%,transparent 100%) var(--x) calc(var(--y) + var(--h) - 2*var(--r)) / calc(2*var(--r)) calc(2*var(--r)),
    radial-gradient(farthest-side,var(--c) 98%,transparent 100%) calc(var(--x) + var(--w) - 2*var(--r)) calc(var(--y) + var(--h) - 2*var(--r)) / calc(2*var(--r)) calc(2*var(--r)),

    linear-gradient(var(--c),var(--c)) calc(var(--x) + var(--r)) var(--y) / calc(var(--w) - 2*var(--r)) var(--h),
    linear-gradient(var(--c),var(--c)) var(--x) calc(var(--y) + var(--r)) / var(--w)  calc(var(--h) - 2*var(--r));
  background-repeat:no-repeat;

  width:300px;
  height:200px;
  display:inline-block;
  border:1px solid;
}

A: The cleanest might actually be to use svg for this instead of css-gradients.
You'll load it as a data-uri in the background-image property.
To make the rounded corner, you can use the rx and ry attributes of the <rect> element.
To make the gradients, you can use svg's <linearGradient> elements.

.mystyle {
  height: 900px;
  width: 500px;
  background-image: url("data:image/svg+xml,<svg xmlns='http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg' width='500' height='900' viewBox='0 0 500 900'><defs><linearGradient id='blue-grad' gradientTransform='rotate(90)'><stop stop-color='lightgrey' offset='0%'/><stop stop-color='blue' offset='100%'/></linearGradient></defs><rect x='0' y='0' width='100' height='40' rx='15' fill='url(%23blue-grad)'/><rect x='0' y='80' width='500' height='60' rx='15' fill='url(%23blue-grad)'/><rect x='0' y='160' width='250' height='50' rx='15' fill='url(%23blue-grad)'/><rect x='0' y='220' width='250' height='60' rx='15' fill='url(%23blue-grad)'/></svg>");
  background-size: cover;
  background-repeat: no-repeat;
}

/*
  SVG Image unminified:

<svg xmlns="http://www.w3.org/2000/svg" width="500" height="900">
  <defs>
    <linearGradient id="blue-grad" gradientTransform="rotate(90)">
      <stop stop-color="lightgrey" offset="0%"/>
      <stop stop-color="blue" offset="100%"/>
    </linearGradient>
  </defs>
  <rect x="0" y="0" width="100" height="40" rx="15" fill="url(#blue-grad)"/>
  <rect x="0" y="80" width="500" height="60" rx="15" fill="url(#blue-grad)"/>
  <rect x="0" y="160" width="250" height="50" rx="15" fill="url(#blue-grad)"/>
  <rect x="0" y="220" width="250" height="60" rx="15" fill="url(#blue-grad)"/>
</svg>
*/

A: Maybe try this approach instead of making one div output multiple gradient boxes?

.myStyle {
  width:150px;
  height:100px;
  background:linear-gradient(black,purple);
  border-radius:20px;
}


text:
Q: How do you organise your files/folders?
Possible Duplicate:
Organized Dictionary structure?

I would like to know how do you organise your files/folder for downloads, documents, pictures, movies, etc
I have 3 drives as follows:

*

*1TB NAS Drive for media share (Movies, Pictures, Downloads)

*1 internal drive for OS

*1 internal drive for documents, downloads, pictures etc.

what does your folders structure look like? My hard drives is unorganized, what is recommended to organize it?

A: i organize by category, type, name, then date
for example:
  videos
tv shows    movies
--------------------
sci-fi      sci-fi
drama       comedy
mystery     intenational
cartoon     classics

    music
genre   genre    genre
------------------------
artist  artist   artist
  |       |        |
album   album    album

A: This probably falls outside the allowable questions FAQ, but others can decide that.
Two approaches come to mind.  Categories/tagging and the Google  way.
By Categories I simply mean sorting things.  Movies, pictures, documents.  Then Action, Adventure or picture subject/date.  All very "normal".
By the Google way, I simply mean drop it all in one bucket and index it.  Find everything by searching.  Gmail made limited use of labels when first launched.  To find anything, you searched.  Since Vista/Win7 made searching ubiquitous on my desktop, I almost always use it to find things.
What are you most comfortable with?  Maybe a blend of the two.


text:
Q: SSL certificate information I was doing some research, but nothing answers my question.
Given url address (https://www.google.com) how do I get information about SSL certificate, when I have almost no tools to do so?
What I am able to do:
Send GET / POST (Patch, delete) request to certain url with no possibility to use ports.
apply header and parameters to request.
Receive response with header.
Well. thats it.
I (have to) use Deluge as language, with no posibilities using external libraries.
What are my options on getting information about Certificate (Start Date, Expiration Date, Organization, etc) using these tools?
Thanks


text:
Q: Изменение размера виджета в зависимости от изменения размера окна приложения Подскажите как сделать так, чтобы размер виджета менялся вместе с размером окна?
В данном случае я пытаюсь изменять размер виджета взяв в качестве размера размеры окна. Но при запуске программы, если я меняю размер окна, размер виджета не меняется.
self.verticalWidget.setGeometry(QtCore.QRect(20, 30, Dialog.width(), Dialog.height()))

main.py
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(900, 900)

        self.verticalWidget = QtWidgets.QWidget(Dialog)
        self.verticalWidget.setGeometry(QtCore.QRect(20, 30, Dialog.width(), Dialog.height()))
        self.verticalWidget.setObjectName("verticalWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.Welcome = QtWidgets.QLabel(self.verticalWidget)
        font = QtGui.QFont()
        font.setPointSize(24)
        self.Welcome.setFont(font)
        self.Welcome.setObjectName("Welcome")
        self.verticalLayout.addWidget(self.Welcome)
        self.Explanation = QtWidgets.QLabel(self.verticalWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.Explanation.setFont(font)
        self.Explanation.setObjectName("Explanation")
        self.verticalLayout.addWidget(self.Explanation)
        self.buttonBox = QtWidgets.QDialogButtonBox(self.verticalWidget)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.verticalLayout.addWidget(self.buttonBox)

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.Welcome.setText(_translate("Dialog", ""))
        self.Explanation.setText(_translate("Dialog", ""))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

A: Добавьте этот виджет в менеджер компоновки, созданный для главного окна.
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(900, 900)

        self.verticalWidget = QtWidgets.QWidget(Dialog)
        self.verticalWidget.setGeometry(QtCore.QRect(20, 30, Dialog.width(), Dialog.height()))
        self.verticalWidget.setObjectName("verticalWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")

        self.Welcome = QtWidgets.QLabel(self.verticalWidget)
        font = QtGui.QFont()
        font.setPointSize(24)
        self.Welcome.setFont(font)
        self.Welcome.setObjectName("Welcome")
        self.verticalLayout.addWidget(self.Welcome)

        self.Explanation = QtWidgets.QLabel(self.verticalWidget)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.Explanation.setFont(font)
        self.Explanation.setObjectName("Explanation")
        self.verticalLayout.addWidget(self.Explanation)

        self.buttonBox = QtWidgets.QDialogButtonBox(self.verticalWidget)
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.verticalLayout.addWidget(self.buttonBox)

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.Welcome.setText(_translate("Dialog", "Welcome"))
        self.Explanation.setText(_translate("Dialog", "Explanation"))

# +++ vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
class Dialog(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self):
        super().__init__()

        self.setupUi(self)

        self.layout = QtWidgets.QHBoxLayout(self)               # !!! +++
        self.layout.addWidget(self.verticalWidget)              # !!! +++

style = '''
#verticalWidget {
    background-color: #4B8673;
}
#Explanation {
    color: #F6FBF4;
}
'''

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)

    app.setStyleSheet(style)                     # +++

    w = Dialog()
    w.show()
    sys.exit(app.exec_())

# +++ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


text:
Q: ValueError: With n_samples=0, test_size=0.2 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters I wrote a text classification program. When I run the program it crashes with an error as seen in this screenshot:

ValueError: With n_samples=0, test_size=0.2 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters.

Here is my code:
from sklearn.model_selection import train_test_split
from gensim.models.word2vec import Word2Vec
from sklearn.preprocessing import scale
from sklearn.linear_model import SGDClassifier
import nltk, string, json
import numpy as np

def cleanText(corpus):
    reviews = []
    for dd in corpus:
        #for d in dd:
        try:
            words = nltk.word_tokenize(dd['description'])
            words = [w.lower() for w in words]
            reviews.append(words)
            #break
        except:
            pass
    return reviews

with open('C:\\NLP\\bad.json') as fin:
    text = json.load(fin)
    neg_rev = cleanText(text)

with open('C:\\NLP\\good.json') as fin:
    text = json.load(fin)
    pos_rev = cleanText(text)

#1 for positive sentiment, 0 for negative
y = np.concatenate((np.ones(len(pos_rev)), np.zeros(len(neg_rev))))

x_train, x_test, y_train, y_test = train_test_split(np.concatenate((pos_rev, neg_rev)), y, test_size=0.2)

The data I am using is available here:

*

*Bad;

*Good
How would I go about fixing this error?

A: Got the same error: ValueError: With n_samples=0, test_size=0.2 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters.
In my case the path to the data was invalid. Check if paths to the loaded files exists or if the variables reading the files hold any data.

A: Got the same error: ValueError: With n_samples=0, test_size=0.2 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters. The error occurs because of that the Data file is not found. In case you are using jupyter notebook you cannot used the Dataframe for defining X and y. So, using the dataframe to define x and y the problem is solved. In other case, it occurs due to it can't find the data. So check in the given path the data is exist.

A: I think below code snippets can help you in solving the issue.
ad_data=pd.read_csv("advertising.csv")from sklearn.model_selection import train_test_split
x=ad_data[['Daily Time Spent on Site', 'Age', 'Area Income','Daily Internet Usage', 'Male']]
y=ad_data['Clicked on Ad']
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)

A: In my case the path was correct but I was using bert for text classification that is when I noticed the shape of the X and y variable  I was having only one sentence in input data so the model_selection was unable to split it so when I reshaped it into multiple sentences and it worked

A: I was facing the same problem. In my case, the problem was with the wrong file extension. I resolved this error just by changing the file extension. Thus, for this error: ValueError: With n_samples=0, test_size=0.2 and train_size=None, the resulting train set will be empty. Adjust any of the aforementioned parameters, file extension can also be checked.


text:
Q: Filter list view with url parameter. Strange behavior in Internet Explorer (SharePoint 2013) I have a link opening the listview AllItems.aspx with specific filter parameter in the url which works fine.
But if the user tries to change the filter of the prefiltered column, e.g. by selecting "Include Descendants" or "Clear Filters from [ColumnName]" I get a strange behavior in Internet Explorer.
While it works in Firefox and the url parameters get changed, in Internet Explorer a set of (strange encoded) parameters will be added after the initial url paramters.
The added paramters beginning with #InplviewHash will not be processed by the borwser and for the user nothing changes.
Example
Firefox
Initial URL:
/Lists/Articles/AllItems.aspx?FilterField1=Topics&FilterValue1=232&FilterOp1=In&FilterLookupId1=1&FilterData1=0%2C10da0eac-592c-4025-adf6-809c14811432
After selecting "Include Descendants":
/Lists/Articles/AllItems.aspx?FilterField1=Topics&FilterValue1=232%2C86&FilterOp1=In&FilterLookupId1=1&FilterData1=1%2C10da0eac-592c-4025-adf6-809c14811432&View={07B3C7B1-6A96-4007-A165-EACED7E8C3AC}
Internet Explorer
Initial URL:
/Lists/Articles/AllItems.aspx?FilterField1=Topics&FilterValue1=232&FilterOp1=In&FilterLookupId1=1&FilterData1=0%2C10da0eac-592c-4025-adf6-809c14811432
After selecting "Include Descendants":
/Lists/Articles/AllItems.aspx?FilterField1=Topics&FilterValue1=232&FilterOp1=In&FilterLookupId1=1&FilterData1=0%2C10da0eac-592c-4025-adf6-809c14811432#InplviewHash07b3c7b1-6a96-4007-a165-eaced7e8c3ac=CascDelWarnMessage%3D1-FilterField1%3DTopics-FilterValue1%3D232-FilterLookupId1%3D1-FilterOp1%3DIn-FilterData1%3D0%2C10da0eac--592c--4025--adf6--809c14811432
Does anyone have experiences with this behavior and knows how to solve it.
Seems like this happens only in Internet Explorer, but I didn't test it in Chrome.
Thanks for help!

A: The new page added in layouts folder "inplview.aspx". When paging, sorting or filtering happens there is an AJAX call to the inplview.aspx and it returns a JSON based result set. That is the rows of the defined list view webpart. The "inplview.aspx" generates the "inplviewhash" tag and appends it with "#" in url.

A: After Ruslan Dayanov's hint I have now the answer for this case.
Predefined filter parameter in the url should not set as valid query string parameter like AllItems.aspx?FilterField1=Topics&... because they will not be replaced while filtering via AJAX and always have a higher priority than the filter parameter, which are set by SharePoint logic and appended with "#" in url.
While the parameter after "?" remain the same, inplview.aspx will always return a result based on these parameter and ignores other parameters after "#"
Solution:
Based on the given URL examples, the initial url shoud be:
/Lists/Articles/AllItems.aspx#InplviewHash07b3c7b1-6a96-4007-a165-eaced7e8c3ac=CascDelWarnMessage%3D1-FilterField1%3DTopics-FilterValue1%3D232-FilterOp1%3DIn-FilterLookupId1%3D1-FilterData1%3D0%2C10da0eac--592c--4025--adf6--809c14811432

A: This blog will explain the how inplview parameter works in SharePoint 2013 Custom List View Web Part Refresh


text:
Q: Координаты открытия контекстного меню MVVM При открытии контекстного меню на Canvas нужно сохранять координаты меню в MainVM.
Через события это делается просто:
Xaml:
<Canvas ContextMenuOpening="Canvas_OnContextMenuOpening" />

Code-behind:
    class MainVM : ViewModelBase
    {
        public static Point ContextMenuPoint {get; set;}
    }

    //.....

    private void Canvas_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
    {

        MainVM.ContextMenuPoint.X = e.CursorLeft;
        MainVM.ContextMenuPoint.Y = e.CursorTop;
    }

Как сделать тоже самое, но через команды?


text:
Q: "Program is not a recognized executable" error in Eclipse I'm trying to debug a C++ programme in Eclipse Indigo. The project is using autotools/configure (and the respective plugin) as build system.
After successful build I right-clicked on the binary in the project browser and chose "Debug As". Then I used the file browser to select the binary. Clicking on "Debug" then opens a dialog which just says "program is not a recognized executable".
Any ideas?

A: I found the answer: the binary parsers configured in eclipse were the wrong ones. Adding the correct binary parser under Project --> Properties --> C/C++ Build --> Settings solves he problem.

A: If you're using libtool in your project, what looks like the binary may actually be a wrapper script used to set LD_LIBRARY_PATH and stuff like that before executing the real binary (which is stored in the .libs directory). This may be what causes Eclipse to fail, but I'm not sure how you should go about fixing that.
There seem to be a bit of documentation about Eclipse CDT and libtool on the internet which may have the infos you need though: http://www.freerdp.com/wiki/doku.php?id=eclipse#debug_configuration

A: From OSX snow leopard on, gcc seems to build 64 bit executables by default. And those won't be recognized from Eclipse in return. To solve the error, you've got to explicitly set your architecture to i386.
Enter your project properties and add the command line option "-arch i386″ for each C++ Linker, C++ Compiler and C Compiler. After a clean build, you should be clear to debug again. In Linker options make sure to NOT set it up as -Xlinker option.
Original Source


text:
Q: How to determine remote link speed? I'm on a non-manageable switched 1 GbE network with mixed 100 MbE and 1 GbE hosts.
Is it possible to tell if a certain host has a certain link speed without looking at the status LEDs of the switch and without access to the hosts?

A: If by 'no access', you mean 'no ip level access whatsoever', then no. If you merely mean 'without logging in', you could use SNMP. IF-MIB::ifSpeed is the metric to look for.


text:
Q: Pre fill list item selected by list item value in jquery I'm new to JQuery. In my App I have the following:
My HTML code is here..

        ALL

        1+

        2+

        3+

        4+

        5+

<input type="hidden" id="hdn_list" value=""></input>

My CSS code is here..
.selected{background-color:green;}

My JQuery code for getting the selected list value is here..
$(document).ready(function () {
    $('#list li a').click(function () {
        var new = $(this).attr("value");
        $("#hdn_list").value = new;          //passing the new selected values to hidden control
        $('#list li a').removeClass('selected');
        $(this).addClass('selected');
        return false;
    });
});

When i am clicking the submit button it is redirected to next page.. if i back to this page again it must pre fill the selected value using that hidden control(#hdn_list) value and the css style also must apply that selected value.. how to do this through jquery/javascript? thanks in advance.

A: Use event.preventDefault() in jquery. it's stop the default action
$(document).ready(function () {
    $('#list li a').click(function (event) {
      event.preventDefault();
        var new = $(this).attr("value");
        $("#hdn_list").value = new;          //passing the new selected values to hidden control
        $('#list li a').removeClass('selected');
        $(this).addClass('selected');

    });
});

A: Try this
 $(document).ready(function () {
    $('#list li a').click(function (e) {
        var nvalue = $(this).attr("value");
        localStorage.setItem("menu", nvalue);
        $("#hdn_list").val(nvalue); //passing the new selected values to hidden control
        $('#list li a').removeClass('selected');
        $(this).addClass('selected');
        e.preventDefault();
    });
      var retrievedObject = localStorage.getItem('menu');
      if (retrievedObject != null) {
        $('ul li a').removeClass("selected")
        $('ul li a[value="' + retrievedObject +'"]').addClass('selected');
      } else {
        $('ul li a:eq(0)').addClass('selected');
      }
});

DEMO


text:
Q: Plotly: Slider animation don't move in applicaion with animated word cloud I was trying to plot animated word cloud using plotly. When the output is plot (html) I can see all the word cloud in animated way (one by one using play botton). The problem is with the slider, which doesn't move at all.
The input data are 2 lists of 4 elements: the first list are 4 diferents wikipedia texts storaged in my_test = [text1, text2, text3, text4], and the second list is year = ["1952", "1962", "1967", "1972"].
The code is:
    from wordcloud import WordCloud, STOPWORDS
    import plotly.graph_objs as go
    from plotly.offline import plot

    import plotly.offline as py

    py.init_notebook_mode()

    def plotly_wordcloud(text):
        wc = WordCloud(width = 500,
                       height = 300,
                       margin=0,
                       stopwords = set(STOPWORDS),
                       max_words = 2000,
                       max_font_size = 100,
                       min_font_size = 10)
        wc.generate(text)

        word_list=[]
        freq_list=[]
        fontsize_list=[]
        position_list=[]
        orientation_list=[]
        color_list=[]

        for (word, freq), fontsize, position, orientation, color in wc.layout_:
            word_list.append(word)
            freq_list.append(freq)
            fontsize_list.append(fontsize)
            position_list.append(position)
            orientation_list.append(orientation)
            color_list.append(color)

        # get the positions
        x=[]
        y=[]
        for i in position_list:
            x.append(i[0])
            y.append(i[1])

        # get the relative occurence frequencies
        new_freq_list = []
        for i in freq_list:
            new_freq_list.append(i*100)
        new_freq_list
        return x,y,word_list,freq_list,fontsize_list,color_list,new_freq_list

    my_text = [text1,text2,text3,text4]
    years = ["1952", "1962", "1967", "1972"]

    fig_dict = {
        "data": [],
        "layout": {},
        "layout.update": {},
        "frames": []
    }

    sliders_dict = {
        "active": 0,
        "yanchor": "top",
        "xanchor": "left",
        "currentvalue": {
            "font": {"size": 20},
            "prefix": "Year:",
            "visible": True,
            "xanchor": "right"
        },
        "transition": {"duration": 300, "easing": "cubic-in-out"},
        "pad": {"b": 10, "t": 50},
        "len": 0.9,
        "x": 0.1,
        "y": 0,
        "steps": []
    }

    fig_dict["layout"] = {"width":1000, "height":600}
    fig_dict["layout"]["xaxis"] = {"showgrid":False, "showticklabels":False, "zeroline":False}
    fig_dict["layout"]["yaxis"] = {"showgrid":False, "showticklabels":False, "zeroline":False}
    fig_dict["layout"]["hovermode"] = "closest"
    fig_dict["layout"]["title"] = "Issues by Month"
    fig_dict["layout"]["sliders"] = {
                                    "args": ["transition", {"duration": 300,
                                                        "easing": "cubic-in-out"}],
                                    "initialValue": "1952",
                                    "plotlycommand": "animate",
                                    "values": years,
                                    "visible": True
                                    }
    fig_dict["layout"]["updatemenus"] = [
                                {"buttons": [
                                    {"args": [None, {"frame": {"duration": 500, "redraw": False},
                                    "fromcurrent": True, "transition": {"duration": 300,
                                                                    "easing": "quadratic-in-out"}}],
                                     "label": "Play",
                                     "method": "animate"
                               },
                                {
                                  "args": [[None], {"frame": {"duration": 0, "redraw": False},
                                  "mode": "immediate",
                                  "transition": {"duration": 0}}],
                                  "label": "Pause",
                                  "method": "animate"
                                }
                                ],
                                 "direction": "left",
                                 "pad": {"r": 10, "t": 87},
                                 "showactive": False,
                                 "type": "buttons",
                                 "x": 0.1,
                                 "xanchor": "right",
                                 "y": 0,
                                 "yanchor": "top"
                                 }]

    first_time = True
    for texto,year in zip(my_text,years):
        x,y,word_list,freq_list,fontsize_list,color_list,new_freq_list = plotly_wordcloud(str(texto))

        if first_time == True:
            first_time = False
            data = go.Scatter(x=x,
                           y=x,
                           textfont = dict(size=new_freq_list,
                                       color=color_list),
                           name=year,
                           mode='text',
                           text=word_list
                          )
            fig_dict["data"].append(data)

        fig_dict["frames"].append(go.Frame(data=[go.Scatter(
                            x=x,
                            y=y,
                            textfont = dict(size=new_freq_list,
                                       color=color_list),
                            name=year,
                            mode='text',
                            text=word_list
                            )]))
        slider_step = {"args": [[year],
                                {"frame": {"duration": 300, "redraw": False},
                                 "mode": "immediate",
                                 "transition": {"duration": 300}}
                                ],
                                "label": year,
                                "method": "animate"}
        sliders_dict["steps"].append(slider_step)

    fig_dict["layout"]["sliders"] = [sliders_dict]

    fig = go.Figure(fig_dict)
    plot(fig)


text:
Q: Tailwind grid_template_columns How can we set individual column width in Tailwind?
For example in vanilla CSS I would
.grid-container {
  display: grid;
  grid-template-columns: 20% 80%;
}

1

2

But, in Tailwind if you apply width to the columns, it breaks the grid.

A: There is a way to set arbitrary values for columns, I know this question is old but I thought I would share. I'm new to tailwinds myself but I thought maybe someone else might find this helpful:

This method also works for setting fixed widths:

In this example the first column will have a fixed width of 200px and the other column would size in auto.

A: To set column width, you either use Grid Column Start / End or simple straight forward Width
working demo on tailwind play

1

2

1

2

A: it's fairly simple. In grid CSS you can tell each element of the grid in which column or row it should start (See grid-column-start) or end (see grid-column-end) and even how many columns it should span.
With tailwind this is very simple (See Grid column)
col-start-x
col-end-x
col-span-x
With this said, in your case it would be (assuming a 5 column grid)

1

2

A: Basically, what tailwindcss does is a repeat(n, 1fr), so thats why our friends in other comments tell you to make a 10 grid and then make colspans.
I found my self in that situation many times to and, when I need only 2 columns with, in your case 80% 20%, I do it in the


text:
Q: Prove that angular momentum commute with the hamiltonian of a central force
I'm trying to prove that $$[\hat{L}_i,\hat{H}]=0$$ for $\hat{H}$ the hamiltonian of a central force $$\hat{H}=\frac{\hat{p}^2}{2m}-\frac{\alpha}{r}.$$

I'm getting this:
$$[\hat{L}_i,\hat{H}]=[\hat{L}_i,\frac{\hat{p}^2}{2m}-\frac{\alpha}{r}] = [\hat{L}_i , \frac{\hat{p}^2}{2m}] - [\hat{L}_i , \frac{\alpha}{r}].$$
Already prove that the first one is zero (it's a known result too), but the second one, I dont know what to do with it, there is no way for me. I was doing something like this:
$$[\hat{L}_i , \frac{\alpha}{r}] = [\epsilon_{ijk} r_j p_k , \frac{\alpha}{r}] = \epsilon_{ijk}r_j [p_k ,\frac{\alpha}{r}] + \epsilon_{ijk} [r_j , \frac{\alpha}{r}]p_k.$$
Obviously, the last term is zero, but the other one, I do something that has no sense to be zero. Have any idea for this? I'm I doing wrong? All of this is to prove that Laplace-Runge-Lenz operator commute with hamiltonian of a central force.

A: Indeed, as you state, $[\hat{L_i},\hat{p^2}]$ and $\epsilon_{ijk}[r_j, \frac{\alpha}{r}]p_k$ are both zero, so we need only consider the commutator:
$$\epsilon_{ijk}\ r_j\ [p_k, \frac{\alpha}{r}]$$
Giving this a test function, we obtain:
$$\epsilon_{ijk}\ r_j\ [p_k, \frac{\alpha}{r}]\ f = \alpha  r_j \epsilon_{ijk}\ [\ p_k(\frac{f}{r}) - \frac{1}{r}p_k(f)\ ]$$
The first term on the RHS can be written:
$$p_k(\frac{f}{r}) = -i\hbar[\frac{1}{r}\frac{\partial f}{\partial r_k}-\frac{r_k\ f}{r^3}]$$
Thus we can now write the commutator as (writing out $p_i$ as $-i\hbar\frac{\partial}{\partial r_i}$):
$$\epsilon_{ijk}\ r_j\ [p_k, \frac{\alpha}{r}]\ f = -i\hbar \alpha \epsilon_{ijk} r_j\ [\frac{1}{r}\frac{\partial f}{\partial r_k} - \frac{r_k\ f}{r^3}-\frac{1}{r}\frac{\partial f}{\partial r_k}]$$
Two of the terms cancel, leaving:
$$\epsilon_{ijk}\ r_j\ [p_k, \frac{\alpha}{r}]\ f = i\hbar \alpha \epsilon_{ijk} r_j\ \frac{r_k\ f}{r^3}$$
If we now sum over the repeated indices, and utilising the antisymmetric property of the Levi-Civita symbol, we obtain:
$$\epsilon_{ijk}\ r_j\ [p_k, \frac{\alpha}{r}]\ f = \frac{i\hbar \alpha}{r^3}[r_jr_k-r_kr_j]=0 $$
Thus, the commutator is zero as expected and indeed, $[\hat{L_i},\hat{H}] = 0$ for all of the components of $L$ (as one would expect; the angular momentum vector is conserved under the action of a central force).

A: Not sure this is what you want, BUT your statement is entirely equivalent to H being invariant under rotations and this is trivial. Why do you need to go through the explicit analysis of commutators? All you need is to remind that $\bf{p}$ is a vector, i.e.
$[L_i, p_j] = i \hbar \epsilon_{ijk} p_k$. From this, rotational invariance of H is manifest. Extension to Lenz vector is also made easy exploiting the underlying $SO(4)$ invariance of Kepler ( or 3d isotropic harmonic oscillator ) problem.


text:
Q: MapperScannerConfigurer config cause illegalArgumentException <bean id="movieMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
    <property name="mapperInterface" value="com.kevinz.ms.mapper.MovieMapper"></property>
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

when I combine the spring and mybatis to do a search on DAO, this configuration is workingthen I tried the MapperScannerConfigurer to scan all the mappers in com/kevinz/ms/mapper/, there is
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.kevinz.ms.mapper"></property>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

I got the exception

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to
  read candidate component class: file
   [E:\workspace\ssm\build\classes\com\kevinz\ms\mapper\MovieMapper.class];
      nested exception is java.lang.IllegalArgumentException

Does anyone know how to fix it?

A: I solved it,I used jdk 1.8,so I update to the spring-framework 4.0 and it works...


text:
Q: C++ convert from derived class to base class with different template number I'm trying to assign a Derived class to a Base class using pointers, the problem is that the two classes have a different number of template:
Base
pcl::Feature< PointInT, PointOutT >
Derived
pcl::FeatureFromNormals< PointInT, PointNT, PointOutT >

as you can see from the inheritance diagram the two classes are father and child.
But when i try to assign the Derived class to a pointer of the Base class i only obtain this error:
error: cannot convert 'pcl::FeatureFromNormals<pcl::PointXYZRGBA, pcl::Normal, pcl::FPFHSignature33>*' to 'pcl::Feature<pcl::PointXYZRGBA, pcl::Normal>*' in initialization

Is it possible to assign a Derived class to Base class with different number of Template?

A: The issue has nothing to do with different number (and the order) of template parameters, you're just using the wrong base class type.
As the document said,
pcl::FeatureFromNormals< PointInT, PointNT, PointOutT >

public derived from
pcl::Feature< PointInT, PointOutT >

for your case,
pcl::FeatureFromNormals<pcl::PointXYZRGBA, pcl::Normal, pcl::FPFHSignature33>

's base class should be
pcl::Feature<pcl::PointXYZRGBA, pcl::FPFHSignature33>

not
pcl::Feature<pcl::PointXYZRGBA, pcl::Normal>


text:
Q: Tiling  elements without mosaic I like using mosaic because when a user increases the size of their browser, it will automatically move around to find the best possible fit. 5 columns can resize to four columns quite nicely. I'd like an effect similar to this, but without the "move to find best fit".
Right now I'm using a table to store some data, each cell of size 300x250. The problem arises when a user increases the size of the page, since cells are rigid and will not reduce column size to compensate, and I end up with cells outside the width of the page, necessitating scrolling.
How can I achieve this effect? To summarize:

*

*start with for example 5 columns that span the width of the page

*if the user zooms in to the point where an element would go beyond the width of a page, make it into four columns instead

*if the user zooms out, have it go back to five columns (but cap it at five)

Is there an easy method to get this tiling scheme? Here's an image to illustrate:

A: That's how display: inline-block elements are laid out. Combine with min-width if you want them to be uniform rather than dictated by their actual content.
Example: Live Copy
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Example</title>

1

2

3

4

5

Note that some old versions of IE don't like you to take an element (like div) that defaults to display: block and make it inline-block instead. If you need to support them, use an element (like span) that defaults to inline-block instead.


text:
Q: Azure DevOps FileTransform task variables in yaml I have a problem using Azure DevOps FileTransform@1 task in my pipeline to substitute variables in json file. Nothing is done.
My yaml is:
variables:
  - name: MyVariable
    value: TheValue
steps:
  - task:FileTransform@1
    inputs:
      folderPath: ./**.zip
      fileType: json
      targetFiles: '**/appsettings.*.json'

Any ideas?

A: The issue was in the variables declarations:
Use
variables:
  MyVariable: TheValue

Instead of:
variables:
  - name: MyVariable
    value: TheValue

In the second form, you define a list of variables and not an object like in first form. The task FileTransform is unable to get the name of the variables from a list to substitute in json file.
I was using the list form to create variable with conditional value:
variables:
  - group: AWS
  - name: AWS_AccessKey
    ${{ if eq(parameters['DeployEnvironment'], 'Development') }}:
      value: $(AWS_ACCESSKEY.Development)
    ${{ if eq(parameters['DeployEnvironment'], 'PreProd') }}:
      value: $(AWS_ACCESSKEY.PreProd)
    ${{ if eq(parameters['DeployEnvironment'], 'Production') }}:
      value: $(AWS_ACCESSKEY.Production)

I didn't find how to use the "object" form for variables and use condition for values.


text:
Q: ASP.NET Core 5 Razor file compilation fails with two SDK installed for lower SDK Using Visual Studio 2019, .NET Core 5 and .NET Core 6 SDK installed.
Verified running under development environment.
Create, run a ASP.NET Core 5 project using the watch configuration shown below or the IIS file changes are not recognized.
From Startup.cs in the ASP.NET Core 5 project
public void ConfigureServices(IServiceCollection services)
{
    var builder = services.AddRazorPages();

    if (Env.IsDevelopment())
    {

        builder.AddRazorRuntimeCompilation();
    }
}

Create, run a ASP.NET Core 6 project using dotnet watch run, make changes in Visual Studio 2019 or from Visual Studio Code changes are recognized.
Went back to the ASP.NET Core 5 project using dotnet cli shown below, still will not recognize changes.
dotnet watch run -f net5.0 --project ValidationSample.csproj

launchSettings.json
{

  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:6776",
      "sslPort": 44308
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation"
      }
    },
    "Watch": {
      "commandName": "Executable",
      "workingDirectory": "$(ProjectDir)",
      "executablePath": "dotnet.exe",
      "commandLineArgs": "watch run -f net5.0",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebApplication2": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation"
      }
    }
  }
}

Questions

*

*Is it not possible to have Razor file compilation in a ASP.NET Core 5 project with .NET Core 5 Framework and .NET Core 6 Framework  installed?

*If I uninstalled the .NET Core 6 SDK, would I need to remove .NET Core 5 SDK and reinstall .NET Core 5 SDK or not?

In closing, I have searched for anyone with a similar situation but all I found where developers with issues getting Razor file compilation to work, nothing for two SDKs.
Update 12/27/2021

*

*Uninstalled .NET Core 6 SDK, tried again, no change recognized.

*Tried using LiveSharp, tried again, looked promising, no changes recognized.

Starting to feel like a firewall rule which I have contacted our engineers to see what they think.


text:
Q: alternate php redirection method that works with output preceding it so apparently if you do this:
<?php
echo 'something';
header("Location: http://something/");
?>

it will not work because there is an output preceding the header...
is there any other alternative php redirection method that works straight from php without installing anything and in which it will still work even if there's an output preceding it so that I don't have to worry about making sure that there is no output before, etc...

A: not, unless you do something in javascript or html tags in the page that you output itself
if preceding output is a problem
you can also use output buffering, see ob_start, ob_get
to get around that

A: There is no other way to do a php redirect, but you can fool it to still work even with code prior. You would buffer the content and only output it if there is no redirect or reaches the end of the script. Note: this may be resource heavy in some cases.
ob_start()
....CONTENT...
ob_end_flush();

A: There are no ways in PHP except using header()... before output is sent (headers be already sent)...
You can either use meta refresh in HTML that is set at zero seconds, or javascript.
But I wouldn't recommend javascript as some will have it disabled.

A: You could use a meta refresh tag.

A: You understand why this is impossible, right?
As soon as you echo "something" you have sent content to the client, and as part of that client headers were already sent. You can't retroactively modify headers you already sent, and you can't make two responses to one HTTP request.
ob_start() and ob_end_flush() will buffer the output instead of sending it to the client, which will allow you to get around this problem, BUT
a better solution would be to:
separate your logic code from your template so that you don't write anything to the screen until you already know you aren't going to redirect.


text:
Q: How to check a log of stored procedure calls? Is there some type of logging in SQL Server (or some way to enable simple logging) that would allow me to check if a stored procedure was called, when it was called, and what parameters were passed and returned?  I have seen some addon scripts for this but wasn't sure if this was built into SQL Server?

A: It isn't built in
You need to set up a profiler trace or add code to your stored procedures to log

A: There is not much built in for this. If you are using recent versions of SQL Server (your question is not very precise on this point), you can look at the DMV sys.dm_exec_procedure_stats, but it will not have individual calls, just aggregates.
If you are interested in a particular stored procedure, you could run a very targeted server-side trace server-side trace. (Sorry, since Quest decided to kill SQLServerPedia, I can't find the original post I referenced).
I wrote an article about building your own logging and adding it to n stored procedures:

*

*Simple process to track and log SQL Server stored procedure use
You could easily expand that to include the parameters called.

A: You can do this with the SQL Server Profiler tool:
http://msdn.microsoft.com/en-us/library/ms187929.aspx


text:
Q: How can I install Windows 10 (including System Reserve) to Disk 1 instead of Disk 0? I'm trying to install Windows 10 to Disk 1, which is sort of working.  I get C: and the main file system on Disk 1.  However, a "System Reserve" partition is created on Disk 0.  Also, it seems that the MBR is installed on Disk 0 as well, as I have to tell the bios to boot off of Disk 0 instead of Disk1.
How do I install Windows 10 entirely on Disk 1?  I want Windows to leave Disk 0 alone entirely.

A: You can achieve this by simply disconnecting all other disk when installing Windows. Some computers also allow to disable certain SATA ports, meaning you don't need to open your computer,


text:
Q: send shipping options to paypal from rails application i can't send shipping options to paypal with rest api sdk
This is @payment.error.inspect
{
  "name"=>"VALIDATION_ERROR",
  "details"=>[
    {
      "field"=>"payer.payer_info.phone",
      "issue"=>"This field currently not supported in this request" },
    {
      "field"=>"payer.payer_info.first_name",
      "issue"=>"Not valid to specify this field in a request" },
    {
      "field"=>"payer.payer_info.last_name",
      "issue"=>"Not valid to specify this field in a request" },
    {
      "field"=>"payer.payer_info.email",
      "issue"=>"This field currently not supported in this request" },
    {
      "field"=>"payer.payer_info.shipping_address",
      "issue"=>"Not valid to specify this field in a request" }
  ],
  "message"=>"Invalid request - see details",
  "information_link"=>"https://developer.paypal.com/webapps/developer/docs/api/#VALIDATION_ERROR",
  "debug_id"=>"2139ec6f8c916"
}

when i do:
shipping_address = {
  recipient_name: self.order.fullname,
  type: self.order.address_type,
  line1: self.order.street1,
  line2: self.order.street2,
  city: self.order.city,
  country_code: self.order.country_code,
  postal_code: self.order.zip,
  state: self.order.state,
  phone: self.order.phone_number }
payer_info = {
  email: self.order.email,
  first_name: self.order.fullname.split(" ").first,
  last_name: self.order.fullname.split(" ").last,
  phone: self.order.phone_number,
  shipping_address: shipping_address }

self.payment = Payment.new({
  :intent =>  "sale",
  :payer =>  {
    :payment_method =>  "paypal",
    :payer_info => payer_info },
  :redirect_urls => {
    :return_url => return_url,
    :cancel_url => cancel_url },
  :transactions =>  [{
    :item_list => {
      :shipping_address => shipping_address,
      :items => self.order.order_items.map do |item|
        {
          :name => _("T-shirts %{size} size") % {size: item.size},
          :sku => "item",
          :price => self.order.campaign.price_for_size(item.size),
          :currency => "HKD",
          :quantity => item.count,
          :amount => item.price
        }
      end},
    :amount =>  {
      :total =>  self.order.price,
      :currency =>  "HKD" },
    :description =>  _("This is the payment transaction description.") }]})

self.payment.create
self.payment.error.inspect

i'm use paypal-rest-sdk and need to send information about buyer to paypal for precomplete fields with address and buyer information.
how to send to paypal shipping address and payer_info ?

A: When your payment_method is "paypal", the payer_info object is pre-filled. payer_info only needs to be submitted when payment_method is credit_card


text:
Q: ATI driver installation I am using ubuntu 14.04, kindly assist how to install drivers for my ATI Radeon graphics card [Mobility Radeon HD 5650/5750 / 6530M/6550M].
I read some documentation on the given site but I am not sure if I really need to do all this.
http://www.securethelock.com/2014/04/20/installing-configuring-amdati-drivers-ubuntu-14-04-trusty-tahr/

A: The documentation in your link is for installing the closed source drivers. I have a HD5650 and it works just fine with the open source drivers. There is nothing you need to do since these are the default drivers on the system.
Normally the closed source driver should give better 3D support ( the open source drivers have come a long way and are pretty good at this point ) and better support for the latest graphics cards. In case of the HD5600 series I see absolutely no need to install closed source drivers.


text:
Q: MySQL: selecting rows by two of three primary keys I am searching for exactly the opposite of what Jonathan was searching in this example:
How to select multiple rows by multi-column primary key in MySQL?
Having 3 columns as a primary key (the 3rd is a date), I want to select all of them without the most recent one. And if there is no second entry for a combination of the first two primary values, I don't want to select it at all. Think of it as a kind of versioning. The table-structure contains more columns than those three and i want to select the whole rows.
Looks something like that:
{ID1 | ID2 | DATE} | more columns ...

Pseudocode:
SELECT * FROM table WHERE (first and second primary value are the same and exist more than once) AND NOT MAX(date)

:D
I want to output the data of all previous versions of the row, not including the most recent one.
Thanks in advance for any suggestions!

A: Break down the problem into steps:
Pseudo logic:

*

*Get a data set with the records we want to exclude

*now exclude that data set from the entire set

Step 1: Get a dataset of only those records having a max data for ID1, ID2
SELECT ID1, ID2, Max(date) date
           FROM Table
           GROUP BY ID1, ID2

Step 2: Now use that data set to identify/eliminate the records you don't want.. a not exists is likely the fastest.
Faster...
SELECT A.*
FROM TABLE A
WHERE NOT EXISTS
(SELECT 1
 FROM (SELECT ID1, ID2, Max(date) date
       FROM Table
       GROUP BY ID1, ID2) B
 WHERE A.ID1 = B.ID1
   and A.ID2 = B.ID2
   and A.Date = B.Date)

or as a self outer join on a subset, slower but gives you access to additional details on subset if needed.  (not much use in this example but could be useful in other circumstances)
The left join to the data set shows those that match on the max date, so all other records would be null, which is the data set you're after...
SELECT A.*
FROM TABLE A
LEFT JOIN (SELECT ID1, ID2, Max(date) date
           FROM Table
           GROUP BY ID1, ID2) B
  on A.ID1 = B.ID1
 and A.ID2 = B.ID2
 and A.Date = B.Date
WHERE B.ID1 is null


text:
Q: Import a python class of non packaged module, and run in it's own thread This Stack Overflow answer details how to use importlib to import a module, and inspect to find the contained class by name.
While this works when using spec.loader.exec_module(module) to execute the module, 'MyClass' cannot be found in module when running exactly the same code in a thread, like so: threading.Thread(target=spec.loader.exec_module, args=[module])
I have set up a working example that can be run to see this effect demonstrated in a simple way, simply copy the following into two files and execute the first one.
File 1:
# test1.py

import importlib.util
import inspect
import threading

my_file = 'thread_test'
path = "thread_test.py"

spec = importlib.util.spec_from_file_location(my_file, path)
module = importlib.util.module_from_spec(spec)

# Comment out one of the following snippets to test each version:

# OPTION 1:
# Non-Threaded Version, Works:
spec.loader.exec_module(module)

# OPTION 2:
# Threaded Version, Doesn't work (Causes cls to not be found in the following loop):
# thread = threading.Thread(target=spec.loader.exec_module, args=[module])
# thread.start()

cls = None
for member in inspect.getmembers(module):
    if member[0] == 'MyClass':
        cls = member[1]

cls.color = 'blue'

cls().PrintColor()

File 2:
# thread_test.py

class MyClass:
    color = None

    def PrintColor(self):
        print(self.color)

Why doesn't the module contain MyClass when executed in it's own thread, yet it it does then executed in the same thread?

A: You have only started the Thread, but you have to join it and wait until it has run: thread.join(). Otherwise the module wont be imported correctly.
Full example:
import importlib.util
import inspect
import threading

my_file = 'thread_test'
path = "thread_test.py"

spec = importlib.util.spec_from_file_location(my_file, path)
module = importlib.util.module_from_spec(spec)

# Comment out one of the following snippets to test each version:

# OPTION 1:
# Non-Threaded Version, Works:
# spec.loader.exec_module(module)

# OPTION 2:
# Threaded Version, Doesn't work (Causes cls to not be found in the following loop):
thread = threading.Thread(target=spec.loader.exec_module, args=[module])
thread.start()
thread.join()

cls = None
for member in inspect.getmembers(module):
    if member[0] == 'MyClass':
        cls = member[1]

cls.color = 'blue'

cls().PrintColor()

Result:
blue

A: After discussing with others I have come to the following solution.
The problem can be solved by running the loading of the module and class in it's own thread. Essentially just starting the thread sooner.
So we put it all into the following function like so:
# Run this in it's own thread
def my_function(module, class_name):
    spec.loader.exec_module(module)

    # Get class
    for member in inspect.getmembers(module):
        if member[0] == class_name:
            my_class = member[1]
        if my_class is None:
            my_print("Error: Could not find class " + class_name + '!')
            return

    # Set properties
    my_class.color = 'blue'

    # Execute code
    cls().PrintColor()

Import:
spec = importlib.util.spec_from_file_location(file, path)
module = importlib.util.module_from_spec(spec)

Then simply execute this function in it's own thread:
# Start thread
thread = threading.Thread(target=my_function, args=[module, class_name])
thread.start()


text:
Q: GARCH model prediction I was analyzing a GARCH(1,1) process. In particular, let's say that I have a process ${y_t}$, with $t \in {1,2,...,T}$. I have created a GARCH process that can be written as:
$\sigma_t^2 = \omega + \alpha y_{t-1}^2 + \beta \sigma_{t-1}^2$,
with $t \in{1,2,...,T}$. After that, I maximize the Log Likelihood of the model, obtaining the three parameters, namely $\hat{\alpha}, \hat{\beta}, \hat{\omega}$.
Now I would like to use these estimated parameters for forecasting volatility. In particular, I can get
$\sigma_{T+1}^2 = \hat{\omega} + \hat{\alpha} y_{T}^2 + \hat{\beta} \sigma_{T}^2$
that is, I can get the estimated volatility at $(T+1)$. It is not clear in my mind how can I get, for example, $\sigma_{T+2}^2$. According to the formulation above, I shall use $y_{T+1}^2$, but my series stops at $T$. How can I get the forecasted value $y_{T+1}$?
I have found in literature that for a GARCH(1,1) and $k>2$
$\mathbb{E}_t[\sigma_{t+k}^2] = \sum_{i=0}^{k-2} (\hat{\alpha}+\hat{\beta})^i\hat{\omega} + (\hat{\alpha}+\hat{\beta})^{k-1}\sigma_{T+1}^2$
Thus I can use the forecasted value for $\sigma_{t+k}^2$ and, inverting the formulation of GARCH(1,1), get the forecasted value of $y_{T+1}$.

A: Assuming you have a model of the type $y_t = \sigma_t\varepsilon_t$, with $\sigma_t^2 = \omega + \alpha y_{t-1}^2 + \beta\sigma_{t-1}^2$, that would make your $y_t$ have the martingale-difference property with respect to its history before time $T$. In other words, optimal predictions of $y_{T+h}$, for $h\geq1$, are zero. This is because
$$\mathbb{E}[y_t\mid\mathcal{F}_{T-1}] = \mathbb{E}[\sigma_t\varepsilon_t\mid\mathcal{F}_{T-1}] = \sigma_t\mathbb{E}[\varepsilon_t\mid\mathcal{F}_{T-1}] = \sigma_t\mathbb{E}[\varepsilon_t] = 0$$
Now, based on your history $t\in\{1, 2,\ldots,T\}$, an approximate forecast of $y_{T+1}$ also functions as an estimate of the squared volatility at time $T+1$, given by
$$ \hat{\sigma}_{T+1}^2 = \hat{\mathbb{E}}[y_{T+1}^2\mid\mathcal{F}_{T}] = \omega + \alpha y_{T}^2 + \beta\hat{\sigma}_{T}^2 $$
If you look at this as a recursive scheme for one-step ahead volatility forecasting, then you can also look at $h>1$ steps ahead with the information available at $T$. Both $y_{T+h}$ and $\sigma_{T+h}$ are random variables, and their predictions coincide:
$$ \mathbb{E}[y_{T+h}^2\mid\mathcal{F}_T] = \mathbb{E}[\sigma_{T+h}^2\mid\mathcal{F}_T]  = \omega + \alpha\mathbb{E}[y_{T+h-1}^2\mid\mathcal{F}_T] + \beta\mathbb{E}[\sigma_{T+h-1}^2\mid\mathcal{F}_T]$$
$$= \omega + (\alpha+\beta)\mathbb{E}[y_{T+h-1}^2\mid\mathcal{F}_T]$$
Working backwards, this leads to a general formula which only needs $y_T^2$ and $\sigma_T^2$:
$$ \mathbb{E}[y_{T+h}^2\mid\mathcal{F}_T] = \omega\sum_{k=0}^{h-1}(\alpha+\beta)^k + (\alpha+\beta)^{k-1}(\alpha y_{T}^2 +\beta\sigma_T^2) $$

In my answer I have quoted heavily -- almost verbatim, in fact -- from the book Quantitative Risk Management, by McNeil, Frey, and Embrechts. Chapter 4.4.1 in particular offers a lot of good explanations that might help you better understand some of the mechanics.


text:
Q: Example of non-decomposable ideal An ideal $I$ of a commutative unital ring $R$ is called decomposable if it has a primary decomposition.

Can you give an example of an ideal that is not decomposable?

All the examples I can think of are decomposable. Thanks.

A: Zero ideal in $C[0,1]$ is not decomposable.
More generally,

If $X$ is an infinite compact Hausdorff space then the zero ideal of $C(X)$, the ring of real valued continuous functions on $X$, is not decomposable.

Proof : First let us note that every maximal ideal of $C(X)$ is of the form $M_x=\lbrace f \in C(X) : f(x)=0\rbrace$, for some $x \in X$. Note that, if the zero ideal of $C(X)$ were decomposable, then there
would be only finitely many minimal prime ideals of $C(X)$. This certainly
sounds strange since every maximal ideal $M_x$ of $C(X)$ contains a minimal
prime ideal as every maximal ideal is also prime ideal. Hence to show that the zero ideal of $C(X)$ is not decomposable it is enough to show that if $x\not= y\in X$ then any two minimal prime ideals
$P_1\subseteq M_x, P_2\subseteq M_y$ are different: Since $X$ is Hausdorff and normal, there is an open set $U$
such that $x\in U$ and $y\not\in\overline{U}$. By Urysohn's lemma there are$ f,g\in C(X)$
such that $f(U) = 0, f(y) = 1, g(x) = 1,$ and $g(X \setminus U) = 0.$ So $fg = 0$. Therefore $fg \in P_1$ but $g \not\in P_1$, because $g(x)\not=0$, hence $f \in P_1$. But $f \not\in P_2$, because $f(y)\not=0$. Hence $P_1\not=P_2$.