text:
Q: Are rational varieties simply connected? Is it true that every smooth rational variety X is simply connected? How is the proof?
Would it be still true if X has mild (for example orbifold) singularities?

A: I decided to rewrite the answer so it is more clear.
Smooth complex rational projective varieties are indeed simply-connected as is explained in the first answer to the question. My point is that from this fact it follows immediately that normal complex rational projective varieties are always simply-connected. Here is a proof.
Proof. Let $X$ be an normal complex projective variety and $X'\to X$ be a resolution of singularities. Then we have a homomorphism $\pi_1(X')\to \pi_1(X)$. I claim that is is surjective. In order to see this one just needs to know that every loop on $X$ can be lifted to $X'$ and this is true since all the fibres of $X'\to X$ are connected since $X$ is normal.
So if $X$ is rational then $X'$ is smooth rational and $\pi_1(X)=\pi_1(X')=0$

A: Yes! (I assume it was implicit in your question that the variety be projective?)
More generally: any smooth, complex, rationally connected projective variety is simply connected. See Debarre's book ("Higher dimensional algebraic geometry").
Alternatively, take a look at Debarre's Bourbaki talk ("Varietes rationnellement connexes"). The idea is that a rationally connected variety has no holomorphic forms, so by Hodge theory the structure sheaf $\mathcal{O}_X$ is acyclic, implying $\chi(X,\mathcal{O}_X) = 1$. If $f : Y \to X$ is a connected etale cover, then $Y$ is again rationally connected, so by the same argument $\chi(Y,\mathcal{O}_Y) = 1$, so $\deg{f} = 1$. So $X$ is simply connected.
In positive characteristic the Hodge theory fails, so the argument as such doesn't stand, but you may still get the simple connectedness as a consequence of the fibration theorem of Graber-Harris-Starr-de Jong. See the mentioned Bourbaki expose.

A: In characteristic zero you do not neen rational. It is enough rationally connected.
Let $X$ be a smooth, projective, rationally connected variety over a field of characteristic zero. Then

*

*Any finite étale cover of $X$ is trivial;

*$X$ is simply connected.

You can find this, for instance, in O. Debarre "Higher-Dimensional Algebraic Geometry", Corollary 4.18.

A: Every proper, normal, rational variety over an algebraically closed field is simply connected. Dmitri explains this via the smooth case and resolution of singularities, but this is true in any characteristic: see SGA 1, XI, Cor. 1.2.
EDIT: As Dmitri and Vesselin observe, the "proof" in SGA1 is sketchy, to say the least. One can argue as follows: if $X$ is our variety, there is a birational morphism $U\to X$ where $U=\mathbb{P}^n\smallsetminus Z$ and $Z$ has codimension $\geq2$ in $\mathbb{P}^n$. By the purity theorem, $U$ is simply connected. So any étale covering of $X$ is generically trivial (because its pullback on $U$ is trivial), hence trivial since $X$ is normal.
In fact, this proves that if $X$ and $Y$ (both proper and  normal) are birationally equivalent, and $Y$ is regular and simply connected, then $X$ is simply connected. But this does not answer Vesselin's final question.

A: In positive characteristic, the (étale) fundamental group of a rationally connected variety is finite (Kollár, Inventiones Math., 1993, EuDML).
And this happens: Let us assume that the base field has characteristic $p$,
where $p\neq 5$ and $p\not\equiv 1\pmod 5$. Then, the hypersurface
with equation $X_0^5+\dots+X_3^5=0$ in $\mathbf P^3$ is unirational;
so is its quotient by the obvious action of $\mu_5$ (a surface of general type
known as the Godeaux surface), which
is therefore an unirational variety with fundamental group $\mathbf Z/5$.
However, Ekedahl has proved that this group is prime to the characteristic.
I discussed that in my Bourbaki Seminar talk, «Points rationnels et groupes fondamentaux, applications de la cohomologie $p$-adique», Astérisque 294, p. 125-146, Numdam, arXiv:math/0303052.


text:
Q: sum of differences between two rows in mysql
Above is a table and i need to get the total distance covered by tyre.
Looking for a way to get the difference the sum to get the total distance covered.
Each the total distance if gotten by sum of difference between "removal" AND "insert" action sharing.
The end results should be 1100+300 = 1400

A: If there always are just one 'insert' and one 'removal' row per tyre and position, you can use conditional aggregation to compute the distance covered by tuple, and then add another level of aggregation at tyre level:
select tyreId, sum(distance_covered) distance_covered
from (
    select
        tyreId,
        position,
        sum(case action when 'removal' then distance else - distance end) distance_covered
    from mytable
    where action in ('insert', 'removal')
    group by tyreId, position
)t
group by tyreId

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the "standard conditions" for existence and uniqueness of solutions for a dynamical system? I am reading
http://www.cds.caltech.edu/~murray/courses/cds101/fa02/caltech/mls93-lyap.pdf
There's a specific passage where the authors introduce Lyapunov stability and equilibrium points.

They say "standard conditions." What are these? Is the list provided in the passage complete or are there more conditions?

A: If the conditions mentioned are satisfied, then the solution of the differential equation exists and is unique. However, there are cases where these conditions are not satisfied, and still the solution is unique. Thus, $\text{given conditions} \implies \text{uniqueness}$, but not vice versa.


text:
Q: BPMN 2.0 Repeat Activity on a Fixed Date I have a question related on example:
We have an activity X which has to be executed every 10th day of the month and produce a report as output. How do I build a BPMN model to reflect this?

A: The answer here really depends on what BPM tool you are using and the defined capabilities of that tool. Generally, you would create a process with a timed start event such that the process only initiates every 10th day of the month. Then, activity X would execute, it builds a report, and finally outputs that report as the process output.
If a start event that can recognize the 10th day of the month is not available, I would create that same process, but instead give it a message start event. Then, I would create a separate process that runs daily. In this process, I would simply check if the current date is the 10th day of the month. If so, fire a message to kick off that first process. If not, end.


text:
Q: Repeat forever but report each x seconds I'm trying to benchmark how many times a function is able to run in, say 10 seconds using this code:
import time

window = 10

while True:
    n = 0
    while time.time() % window:
        test()      # which really runs only a fragment of a second
        n = n + 1
    print "n: %s" % n

But test() keeps running over and over without me seeing any output (way longer than 10 seconds).  I understand that the time.time() % window is probably naive but I can't come up with the right way.
Could anybody push me in the right direction?  I'd like to avoid "real benchmarking tools" in favor of learning how to do it.

A: time.time() is returning a floating point representation of the time.
When you modulus it, you'll almost never have it return exactly 0.
Consider using: int(time.time()) % window

Heads up though: you'll want a sleep at the end of your loop to prevent running the outer loop multiple times per "benchmark".  You can avoid this by benchmarking time-per-X-iterations instead of iterations-per-X-time.

Rough example of time-per-X-iterations:
window = 1000
start = time.time()
n = 0

while True:
    test()
    n = n + 1

    if n % window == 0:
        print "Average: %f/sec" % ( n / (time.time() - start) )

A: This does what I wanted (plus avoids the modulo jeopardy):
import time

def testFor(w, fn):
    n = 0
    start = time.time()
    while (time.time() - start) < w:
        fn()
        n = n + 1
    return n

window = 10

while True:
    n = testFor(window, test)
    print "n: %s" % n


text:
Q: Can i Do object reflection in C# I have two classes, Dog and Cat
class Dog
{
    public void speak() {
         System.out.println("Woof!");
    }
}
class Cat
{
    public void speak() {
         System.out.print("Meow!");
    }
}

In my main, I take the name as String, either "Cat", or "Dog".
public static void main(String [] args)
{
    Scanner sc = new Scanner(System.in);
    String name = sc.next();
    Class<?> cls = Class.forName(name);
    Object object = cls.newInstance();
}

Can i do this in C#??

A: Line by line it would be:
public static void Main(string[] args)
{
    string name = Console.ReadLine();

    // The second true will ignore case
    var cls = Type.GetType("Animals." + name, true, true);

    var @object = Activator.CreateInstance(cls);
}

with the various animals like:
namespace Animals
{
    public class Dog
    {
        public void speak()
        {
            Console.WriteLine("Woof!");
        }
    }

    public class Cat
    {
        public void speak()
        {
            Console.WriteLine("Meow!");
        }
    }
}

I've added a namespace to make it a "more complete" example: in .NET you can have your code *outside" any namespace, but normally you'll use a namespace. I'm prepending it to the name of the class obtained from the console ("Animals." + name).
Note that this code is quite useless, because without a base interface/class, you can't easily make them speak() (you can go full reflection/dynamic from this point onward to do it but it is "bad")
Bad way with dynanic:
dynamic @object = Activator.CreateInstance(cls);
@object.speak();

(note that I'm not supporting what you are doing, it is bad in multiple ways)


text:
Q: What is the effect of the reflection coefficient? I know that the reflection coefficient is the ratio of the backwards wave with the forward wave in terms of the characteristic and load impedances. But what does this mean? Does this represent a loss in energy in the line? Is the backwards wave creating a loss in the forward wave? How does this ratio affect the line?

A: A reflection coefficient is defined at the junction between two media, usually transmission lines, of different impedance.
At the junction, the power travelling along the first line is split into some power travelling forward into the second line, and some power reflected back along the first.
As such, there is no power dissipation at the line junction. However, the fraction of incident power that gets reflected is no longer available to the second line. It depends on what is driving the first line whether that power eventually gets dissipated or not. A generator with any sort of resistive output impedance will dissipate that power.

A: A radio receiver with 3dB reflection coefficient will exhibit (at least) a 3dB worse SNR signal-noise-ratio; often such large S11 will not be usable, because of competitive reasons (consider a cellsite with frequent dropped-service behaviors, such that subscribers switch to another service provider).
In extremely wide-band systems, often connected to large parabolic dishes that vacuum up all the energy across all bands, the reflection coefficient is tolerated (and even removed with computer calibration during direction-finding monopulse behaviors)

A: In the comments to your question, you said:

like a wave being pulled back and forth where the water in the middle kinda keeps swaying back and forth but staying there

This is a very good way to visualize what is happening, and is called a standing wave. It occurs, because two waves - one coming from the source and one reflected - interfere. The envelope of such a wave has voltage maxima and minima  in regular intervals.
As you correctly stated, the reflection coefficient describes the amplitude ratio of these waves. Another way of expressing the same effect is the "voltage standing wave ratio" (VSWR), which relates the maximum and minimum envelope voltage on the line. VSWR and refelction coefficient can be directly converted into each other.
Note that the reflection coefficient can be a complex number, in which case its argument (angle against real axis) describes that a phase shift occures in the moment of reflection. This happens for example if the line is terminated with a reactive load.
In practice, reflection is undesireable in RF circuits in most cases. Most importantly, it means that not all available power is transmitted to a the load: Consider an antenna catching a few picowatts (or less), and the reciever amplifier reflects that power right back - wasting our precious signal! The power is not dissipated per se, but it is no longer usable for our application.
Other typical implications include:

*

*reduced signal-to-noise ratio (SNR)

*worse antenna performance

*instability or even oscillation in amplifiers

To avoid these problems, impedance matching networks are used. They are LC or transmission line networks that can present the correct impedance to a line as to minimize reflection over a certain range of frequencies.


text:
Q: Can't figure out why my function is not treating a passed value as needed Here's my code:
carats <- pull(diamonds %>% distinct(carat) %>% arrange(carat))

get_price_by_category <- function(dataset, x, y) {
    print(c(x, typeof(x)))
    dataset %>% filter(carat == x) %>% print()
}

carats %>% walk(get_price_by_category, dataset = diamonds, y= "price")

When I run it, I get these results:
[1] "0.2"    "double"
# A tibble: 0 x 10
# … with 10 variables: carat <dbl>, cut <ord>, color <ord>, clarity <ord>,
#   depth <dbl>, table <dbl>, price <int>, x <dbl>, y <dbl>, z <dbl>
[1] "0.21"   "double"
# A tibble: 0 x 10
# … with 10 variables: carat <dbl>, cut <ord>, color <ord>, clarity <ord>,
#   depth <dbl>, table <dbl>, price <int>, x <dbl>, y <dbl>, z <dbl>
[1] "0.22"   "double"
# A tibble: 0 x 10
# … with 10 variables: carat <dbl>, cut <ord>, color <ord>, clarity <ord>,
#   depth <dbl>, table <dbl>, price <int>, x <dbl>, y <dbl>, z <dbl>
[1] "0.23"   "double"
# A tibble: 0 x 10
# … with 10 variables: carat <dbl>, cut <ord>, color <ord>, clarity <ord>,
#   depth <dbl>, table <dbl>, price <int>, x <dbl>, y <dbl>, z <dbl>
...

So, obviously, my function recognizes the value being passed, and the variable type is equivalent to the type of the column it's being filtered on. But, just as obviously, it's not treating it as needed in the filter(carat == x) function.
If I change the code by changing walk() to a for() loop and passing the value of carat explicitly:
carats <- pull(diamonds %>% distinct(carat) %>% arrange(carat))

get_price_by_category <- function(dataset, x, y) {
    print(c(x, typeof(x)))
    dataset %>% filter(carat == x) %>% print()
}

for (c in carats) {
    get_price_by_category(diamonds, c, y= "price")
}

the results are the same.
If, however, I leave the for() loop, but change the code in my function to reference c instead of x (even when I leave it as x in the parameter list), I get the desired result:
carats <- pull(diamonds %>% distinct(carat) %>% arrange(carat))

get_price_by_category <- function(dataset, x, y) {
    print(c(c, typeof(c)))
    dataset %>% filter(carat == c) %>% print()
}

for (c in carats) {
    get_price_by_category(diamonds, c, y= "price")
}

Result:
[1] "0.2"    "double"
# A tibble: 12 x 10
   carat cut       color clarity depth table price     x     y     z
   <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
 1   0.2 Premium   E     SI2      60.2    62   345  3.79  3.75  2.27
 2   0.2 Premium   E     VS2      59.8    62   367  3.79  3.77  2.26
 3   0.2 Premium   E     VS2      59      60   367  3.81  3.78  2.24
 4   0.2 Premium   E     VS2      61.1    59   367  3.81  3.78  2.32
 5   0.2 Premium   E     VS2      59.7    62   367  3.84  3.8   2.28
 6   0.2 Ideal     E     VS2      59.7    55   367  3.86  3.84  2.3
 7   0.2 Premium   F     VS2      62.6    59   367  3.73  3.71  2.33
 8   0.2 Ideal     D     VS2      61.5    57   367  3.81  3.77  2.33
 9   0.2 Very Good E     VS2      63.4    59   367  3.74  3.71  2.36
10   0.2 Ideal     E     VS2      62.2    57   367  3.76  3.73  2.33
11   0.2 Premium   D     VS2      62.3    60   367  3.73  3.68  2.31
12   0.2 Premium   D     VS2      61.7    60   367  3.77  3.72  2.31
[1] "0.21"   "double"
# A tibble: 9 x 10
  carat cut       color clarity depth table price     x     y     z
  <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1  0.21 Premium   E     SI1      59.8    61   326  3.89  3.84  2.31
2  0.21 Very Good E     VS2      63.2    54   386  3.82  3.78  2.4
3  0.21 Premium   E     VS2      60.5    59   386  3.87  3.83  2.33
4  0.21 Premium   E     VS2      59.6    56   386  3.93  3.89  2.33
5  0.21 Premium   D     VS2      61.6    59   386  3.82  3.78  2.34
6  0.21 Premium   D     VS2      60.6    60   386  3.85  3.81  2.32
7  0.21 Premium   D     VS2      59.1    62   386  3.89  3.86  2.29
8  0.21 Premium   D     VS2      58.3    59   386  3.96  3.93  2.3
9  0.21 Premium   E     SI2      61.9    56   394  3.84  3.82  2.37
...

So the fact that I can leave it as x in the parameter list and still get the desired result as long as I reference it as c in the actual function code makes me realize that somehow the value in my call is not being passed to my function as I'm expecting it to be. But I cannot figure out why this doesn't work, or what I need to do to get it to work.

A: There are two problems here, and while you're seeing problem 2, I think you should really look at problem 1 so that you are not bitten by another bug.

*

*Doing equality tests with floating point on digital computers is unfortunately fundamentally flawed (IEEE-754, R FAQ 7.31). The only assurance you have of matching a floating-point value is to looking "around it" with tolerance (a test of inequality), such as abs(carat-0.2) < 1e-8. (You can get away with it for some comparisons, but you won't really know when it'll bite you until something weird happens and you dig in deep.) To do this, you should likely know something about the data itself so that your choice of 1e-8 is correctly informed.

*x is seen as dataset$x, not the function argument ... try using an argument name that is not in the dataset.
get_price_by_category <- function(dataset, a, b, tol = 1e-8) {
    print(c(x, typeof(x)))
    dataset %>% filter(abs(carat - a) < tol) %>% print()
}
carats %>% head(n=2) %>% walk(get_price_by_category, dataset = diamonds, b = "price")
# [1] "0.2"    "double"
# # A tibble: 12 x 10
#    carat cut       color clarity depth table price     x     y     z
#    <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
#  1   0.2 Premium   E     SI2      60.2    62   345  3.79  3.75  2.27
#  2   0.2 Premium   E     VS2      59.8    62   367  3.79  3.77  2.26
#  3   0.2 Premium   E     VS2      59      60   367  3.81  3.78  2.24
#  4   0.2 Premium   E     VS2      61.1    59   367  3.81  3.78  2.32
#  5   0.2 Premium   E     VS2      59.7    62   367  3.84  3.8   2.28
#  6   0.2 Ideal     E     VS2      59.7    55   367  3.86  3.84  2.3
#  7   0.2 Premium   F     VS2      62.6    59   367  3.73  3.71  2.33
#  8   0.2 Ideal     D     VS2      61.5    57   367  3.81  3.77  2.33
#  9   0.2 Very Good E     VS2      63.4    59   367  3.74  3.71  2.36
# 10   0.2 Ideal     E     VS2      62.2    57   367  3.76  3.73  2.33
# 11   0.2 Premium   D     VS2      62.3    60   367  3.73  3.68  2.31
# 12   0.2 Premium   D     VS2      61.7    60   367  3.77  3.72  2.31
# [1] "0.2"    "double"
# # A tibble: 9 x 10
#   carat cut       color clarity depth table price     x     y     z
#   <dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
# 1  0.21 Premium   E     SI1      59.8    61   326  3.89  3.84  2.31
# 2  0.21 Very Good E     VS2      63.2    54   386  3.82  3.78  2.4
# 3  0.21 Premium   E     VS2      60.5    59   386  3.87  3.83  2.33
# 4  0.21 Premium   E     VS2      59.6    56   386  3.93  3.89  2.33
# 5  0.21 Premium   D     VS2      61.6    59   386  3.82  3.78  2.34
# 6  0.21 Premium   D     VS2      60.6    60   386  3.85  3.81  2.32
# 7  0.21 Premium   D     VS2      59.1    62   386  3.89  3.86  2.29
# 8  0.21 Premium   D     VS2      58.3    59   386  3.96  3.93  2.3
# 9  0.21 Premium   E     SI2      61.9    56   394  3.84  3.82  2.37

N.B. I'll say it again: the choice of tolerance is critical to the logical accuracy of this function. If you're dealing with a units that are typically in the 1s or 1000s with 8 or fewer significant digits, then 1e-8 is fine. If you're dealing with high-precision numbers, you may need to get closer to .Machine$double.eps (which, on my 64-bit machine, is 2.22e-16, see ?.Machine for details about the components of this variable). I have no reason to not default to that, but this is why I said "choice of 1e-8 is correctly informed" -- only you know your data, if there is no practical difference beyond 1/1000ths, then you can use tol=1e-3.


text:
Q: Access array values outside of function in PHP I'm trying to access variables outside of my function that assigns values to them. I thought the best way would be to put them into an array but cannot seem to figure out how to access them elsewhere in my code. My function is as follows:
function getYouTubeMeta( $post_id ) {
    $video_id = get_post_meta( get_the_ID(), 'rfvi_video_id', true );
    $api_key = "*********************";
    $url = "https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=" . $video_id . "&key=" . $api_key;

    $json = file_get_contents($url);
    $json_data = json_decode($json);
    $time_stamp = $json_data->items[0]->contentDetails->duration;

    function duration($time_stamp) {
        $di = new DateInterval($time_stamp);
        return $di->format('%i:%S');
    }
    $youtube_duration = duration($time_stamp);

    $like_count = $json_data->items[0]->statistics->likeCount;
    $dislike_count = $json_data->items[0]->statistics->dislikeCount;
    $view_count = $json_data->items[0]->statistics->viewCount;
    $comment_count = $json_data->items[0]->statistics->commentCount;

    $youtube_meta = array('like_count', 'dislike_count', 'view_count', 'comment_count', 'youtube_duration');
    $result = compact($youtube_meta);

    return $result;
}

If I use print_r($result); I get:
Array ( [like_count] => 2954 [dislike_count] => 37 [view_count] => 271763 [comment_count] => 385 [youtube_duration] => 3:16 )

I need to be able to echo out each key value independently in my code. Something along the lines of:
<?php echo 'returned_like_count_value' ?>

A: First assign the results of your function to a variable:
$result = getYouTubeMeta($post_id);

This would loop through your array and echo out the keys and their values.
<?php
foreach($result as $key=>$value) {
  echo "Key=" . $key . ", Value=" . $value . "<br>";
}
?>

If you just want a particular value you can use:
echo $result['like_count'];


text:
Q: You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file." I'm setting up webpack to my react project using yarn and this error appears:

ERROR in ./src/app.js 67:6 Module parse failed: Unexpected token
  (67:6) You may need an appropriate loader to handle this file type,
  currently no loaders are configured to process this file. See
  https://webpack.js.org/concepts#loaders
         ℹ 「wdm」: Failed to compile.

webpack.config.js
const path = require("path");

module.exports = {
    entry: "./src/app.js",
    output: {
        path: path.join(__dirname, 'public'),
        filename: 'bundle.js'
    },
    module:{
        rules:[{
            loader: 'babel-loader',
            test: '/\.(js|jsx)$/',
            exclude: /node_modules/
        }]
    },
    devtool: 'cheap-module-eval-source-map',
    devServer: {
        contentBase: path.join(__dirname, 'public')
    }
}

.babelrc
{
    "presets": ["env", "react","@babel/preset-env"],
    "plugins": [
        "transform-class-properties"
    ]
}

package.json
{
  "name": "react",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "serve": "live-server public/",
    "build": "webpack",
    "dev-server": "webpack-dev-server"
  },
  "dependencies": {
    "babel-cli": "6.24.1",
    "babel-core": "6.25.0",
    "babel-plugin-transform-class-properties": "6.24.1",
    "babel-preset-env": "1.5.2",
    "babel-preset-react": "6.24.1",
    "live-server": "^1.2.1",
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "webpack": "^4.39.3",
    "webpack-dev-server": "^3.8.0"
  },
  "devDependencies": {
    "@babel/core": "^7.6.0",
    "babel-loader": "^8.0.6",
    "webpack-cli": "^3.3.8"
  }
}

A: You are using unnecessary escape character: which is not required.
Replace test: '/\.(js|jsx)$/', with test: /\.js$|jsx/, it should work fine.
I replicated your issue in my machine and found the same which is resolved by the above fix.
hope this helps, happy coding!!!

A: This error happened to me simply because the file was placed in the parent folder of the project (i.e. outside the project's folder).
Moving the file to the appropriate folder fixed it.

A: The selected answer missing some details:
It should be test: /\.js|\.jsx$/
\: is an escape character in this case for .
|: is an Alternation / OR operand
$: is end of line
Hopefully this is useful for you.
Source:
https://www.rexegg.com/regex-quickstart.html

A: In my case, I configure this and it works:
module: {
rules: [
  {
    test: /\.(js|jsx)$/,
    exclude: /node_modules/,
    use: {
      loader: "babel-loader",
      options: {
        presets: ["@babel/preset-react", "@babel/preset-env"],
      },
    },
  },

A: If you get this error while working on a file, before worrying about modifying webpack config, please check if the file leading to the error has an extension i.e .js or .jsx. I encountered this error when I forgot to add an extension on one of my Javascript files. i.e. instead of my-file.js, I had my-file

A: I know this is not a direct answer to the original question, but this is one of the most likely places people will end up when they are having trouble with a loader.
In my case the file that it was complaining about was inside of the node_modules folder. I was consuming a typescript file directly.
{
    test: /\.m?ts$|\.tsx?$/,
    // exclude: /node_modules/,
    use: {
        loader: "ts-loader",
        options: {
            onlyCompileBundledFiles: true,
        }
    },
},

The change I made was removing the exclude portion and adding onlyCompileBundledFiles to ts-loader. Other loaders may have something similar. But basically it will only process items included in the bundle regardless of if they are inside or outside of the node_modules folder.

A: add a .babelrc file to the same folder where your node_modules folder is, with the below content
{
  "presets": ["@babel/preset-react"]
}

A: Put the code mentioned below in webpack file
mix.extend(
    "graphql",
    new (class {
        dependencies() {
            return ["graphql", "graphql-tag"];
        }

        webpackRules() {
            return {
                test: /\.(graphql|gql)$/,
                exclude: /node_modules/,
                loader: "graphql-tag/loader"
            };
        }
    })()
);

mix.js("resources/js/app.js", "public/js").vue();

mix.graphql();


text:
Q: Docker Compose: .env: no such file or directory / NodeJS Hello I'm trying to make my docker compose work, but I have the following error:

Step 13/15 : COPY .env . COPY failed: stat
  /var/lib/docker/tmp/docker-builder209795817/.env: no such file or
  directory

I'm not able to find solutions or imagine what I can do to solve this
code:
DockerCompsoe:
version: "3.7"
services:
  db:
    image: postgres
    environment:
      POSTGRES_PASSWORD: postgres
      POSTGRES_USER: postgres
      POSTGRES_DB: emasa
    volumes:
      - ./pgdata:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    web:
      image: emasapg
      depends_on:
        - dbs
      ports:
        - "4000:4000"

DockerFile:
FROM node as builder
WORKDIR usr/app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

FROM node
WORKDIR usr/app
COPY package*.json ./
RUN npm install --production

COPY --from=builder /usr/app/dist ./dist      // I GOT PROBLEM HERE

COPY ormconfig.docker.json ./ormconfig.json
COPY .env .

expose 4000
CMD node dist/src/index.js

My package.json:
{
  "name": "back-end",
  "version": "0.0.1",
  "description": "Awesome project developed with TypeORM.",
  "scripts": {
    "dev:server": "ts-node-dev --respawn --transpileOnly src/index.ts",
    "build": "tsc -b"
  },
  "devDependencies": {
    "@types/express": "^4.17.3",
    "@types/node": "^13.9.1",
    "typescript": "^3.8.3"
  },
  "dependencies": {
    "apollo-server-express": "^2.11.0",
    "express": "^4.17.1",
    "graphql": "^14.6.0",
    "pg": "^7.3.0",
    "reflect-metadata": "^0.1.13",
    "ts-node": "^8.6.2",
    "typeorm": "0.2.24"
  }
}

my ormconfig:
{
  "type": "postgres",
  "host": "db",
  "port": 5432,
  "username": "postgres",
  "password": "postgres",
  "database": "emasa",
  "synchronize": true,
  "logging": false,
  "entities": ["src/entity/**/*.ts"],
  "migrations": ["src/migration/**/*.ts"],
  "subscribers": ["src/subscriber/**/*.ts"],
  "cli": {
    "entitiesDir": "src/entity",
    "migrationsDir": "src/migration",
    "subscribersDir": "src/subscriber"
  }
}

and this is my folders structures:

A: The error appears because there is no .env file and no dist folder.
First of all you need to create a .env file at the root of your project structure in order to provide the needed environment variables (e.g. like name, host, port, password and user of your database connection). Next run npm run build to build your project, which will create the dist folder (see your tsconfig.json).


text:
Q: JMetter, Encrypt requests, decrypt responses The system encrypts all requests and returns encrypted data. How can I encrypt all requests and decrypt responses? Also, can I load the JSON body of the request with the parameters from the file, something like:
{"Token":${token}, "SomeParam": ${somevalue}}

A: Encryption/decryption should be possible using JSR223 PreProcessor and JSR223 PostProcessor correspondingly, JMeter comes with Apache Commons Codec library which provides handy APIs for encryption/decryption of data using various algorithms
With regards to loading request parameters from the file containing nested JMeter Variables go for __eval() and __FileToString() functions combination like:
${__eval(${__FileToString(your_file.json,,)})}

Check out Here's What to Do to Combine Multiple JMeter Variables for more information.


text:
Q: Senators in a senate using pigeonhole principle. (NOTE: not duplicate, only clarification) There are $30$ senators in a senate. The senate needs to be divided into $n$ committees such that each senator is on exactly one committee. Each senator hates exactly $6$ other senators and is hated by exactly $6$ senators. (If senator A hates senator B, then senator B does not necessarily hate senator A). Find the smallest value of $n$ such that it is always possible to arrange the committees in a way that no senator hates another senator on his or her committee.
Yes, I know, there is already a question asked like this, but what I REALLY want is to clarify the answer of the other similar question on the site: Pigeonhole: Committee of senators who hate one another
Do you always start with $7$ when guessing the number of possible committees? Or is there a formula, or rule that states what number to start on when doing this guessing? The answer refers to something called the "induction hypothesis", but I'm not familiar about it, so it could really help if anyone explain these questions.
This question is not about finding the answer to the question in the first paragraph, but to go into detail about the method, and solution to solving this question. Any help would be wonderfully appreciated.
:)

A: Induction is the idea that for natural numbers $\Bbb N$ (so $1,2,3 \cdots$), if we can prove a statement is true for any natural number and also for the generic number $n + 1$, then it is true for all natural numbers. The induction hypothesis, specifically, means that we prove for some minimum case (in this problem, $7$) then assume (aka, hypothesise) that it is true for some generic natural number $n$. If we can then prove that if it's true for $n$, it is always true for $n + 1$, then it is true for all natural numbers (because we proved it is true for $7$, so if we let $n = 7$ then we've proven it's also true for $8$, so for $9$, and so on.)
Your other question, on why 7, is discussed in the comments of the answer for your linked question - the answer uses 7 because the solution given in the question says 7, and then there is further discussion into how one would find that it is 7 without already knowing that - sTertooy's answer gives a very intuitive approach of why 6 or fewer would not work.


text:
Q: Is this a good case for horizontal integration? Find enclosed area btw 2 equations. Why or why not? When doing horizontal integration... why do we write the function as a function of y with the x by itself? What is the high level point of that?
So here is my work. Is this right? I am asked to find the area enclosed between these equations:
$$ 4x + y^2 = 12, x = y$$
First thing's first is to graph it and find the points of intersection:

Point of intersection:
$$ \frac{12 - y^2}{4} = y$$
$$ 12 - y^2 = 4y$$
$$y^2 + 4y -12 = 0$$
$$(y - 2)(y+6) = 0$$
$$y = {2,-6}$$
So the points are $(2,2) , (-6, -6)$.
So the integral...why do we write it as a function of y? Can't we write it as a function of x still?:
$$ \int_{-6}^2 - y \, dy$$
$$= \int_{-6}^2 3 \cdot \frac{-1}{4} y^2 \, dy$$
$$= [ 3y - \frac{1}{4} \cdot \frac{y^3}{3} - \frac{y^2}{2} ]_{-6}^2$$
$$ 6 - \frac{2}{3} - 2 - (-18 + 18 -18) = 21 \frac{1}{3}$$
Does this look right? More importantly, why do we use the equation where y is the variable?

A: You could write it as a function of whatever you  want; as long as you do the integral correctly, either will give you the area between the two curves.  However, choosing one variable (in this case, $y$) to set up the integral for is sometimes easier than the other.
Here, for instance, writing this as a function $f(y)$ and integrating with respect to $y$ lets us write this area as a single integral $\int_{-6}^2 f(y)\, dy$. Here your $f(y)$ should be $\frac{12 - y^2}{4} - y$.
However, if we tried to integrate $dx$, we would run into two inconveniences. First, setting it up as a function $g(x)$ of $x$, we would have $y = \pm\sqrt{\text{something}}$, and we would have to make a choice of  sign here. Secondly, when trying to write this integral, we have to integrate the top function minus the bottom function right? But these change; from $x = -6$ to $x =  2$, the top function is $y = x$, and the bottom is the $4x + y^2  = 12$ function.  However, at $x = 2$, we switch; the area is now enveloped on top by the positive square root $y = \sqrt{12 - 4x}$, and on the bottom by the negative square root.
Thus,  in trying to do the $dx$ integral, we would a) have to work with more annoying functions, and b)  have to split our integral up  into two integrals. It's easier to integrate $dy$!


text:
Q: repeating a function in R and pass values to a matrix I am using an inbuilt  function from the sde package:
set.seed(123)
X <- sde.sim(model="OU", theta=c(3,1,2), N=10000, delta=1)

I want to repeat the same function 1000 times without changing any parameters, each time it will give a time series as output. I want to pass it to a matrix.
can anyone help me with the repeat command as its different from the normal repeat where you have a constraint.

A: With what I understood I would go with a simple for loop
mat <- matrix(,1000,10001)
for (x in 1:1000) { mat[x,] <- sde.sim(model="OU", theta=c(3,1,2), N=10000, delta=1) }

Another option from @DavidArenburg comment:
mat <- matrix(sde.sim(model="OU", theta=c(3,1,2), N=(1e7 -1), delta=1),nrow=1e3,ncol=1e4)

We have to set N to row by col minus 1 to get a divisible value at end (so each row will be of 10 000 values exactly and not 10 001 as in the for loop.
WARNING Unlike the for loop, here each line will not start with 1, only the first entry will be 1.

A: You can use replicate to run the function 1000 times and use cbind to combine the resulting time series into a matrix.
result = do.call( cbind, replicate(1000, sde.sim(model="OU", theta=c(3,1,2), N=10000, delta=1), simplify=FALSE ) )


text:
Q: I need help determining the difference between my code that I believe produces the same result as another, but won't be accepted I am stuck on how my code will not be accepted by freeCodeCamp's auto-grader. The objective was to create a function without any parameters that will generate a random number using Math.random(). Then we would have to multiply the randomly generated number by 10. After multiplying the randomly generated by 10, I would have to use Math.floor() to round it up or down.
Link to challenge: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-with-javascript
These are the objectives given to me, quoted directly from freeCodeCamp's challenge:
1.) The result of randomWholeNum should be a whole number.
2.) You should use Math.random to generate a random number.
3.) You should have multiplied the result of Math.random by 10 to make it a number that is between zero and nine.
4.) You should use Math.floor to remove the decimal part of the number.
Here is my code:
function randomWholeNum() {

  var x = Math.random();
  var z = x * 10;
  var y = Math.floor(z);
  return y;
}

As you can see, I used multiple variables to complete this task. x would generate the random number, z would store the random number multiplied by 10, y would round z, resulting in all objectives passed. However, when running the code, all objectives were ticked except for Number 3. I don't understand what went wrong, and after looking at the answer for the challenge,  which is:
function randomWholeNum() {
  // Only change code below this line.
  return Math.floor(Math.random() * 10);
}

I don't understand why the code I wrote doesn't produce the same result of freeCodeCamp's own.


text:
Q: Calling a function placed in another function that is in another class I couldn't grasp the idea why the codes below prints console Person twice. I thought it should have been Person and Student. When getInfo() inside printPerson() is called through "a" object, why is the one inside Person class being invoked and why is the one in the Student class not invoked? Thanks in advance.
class deneme{
     public static void main(String[] args) {
        Person b = new Person();
        b.printPerson();
        Student a = new Student();
        a.printPerson();
    }
}

class Student extends Person {
     public String getInfo() {
        return "Student";
    }

 }

class Person{

     private String getInfo() {
        return "Person";
    }

     public void printPerson() {
        System.out.println(getInfo());
    }
}

A: You have attempted to override a private method. That is not possible. See Override "private" method in java for details. Because Student is not able to see Person.getInfo Java assumes you are declaring a new method.
If you make getInfo public you will find that Student is printed instead.
This is a good argument for using the @Override annotation before any methods that you are intending to override a superclass's method. It isn't just documentation - it can avoid subtle errors by letting your IDE warn.

A: I think that is because Person.getInfo() is private and you cannot override private methods, so a.printPerson() will actually call its own getInfo(). Always annotate methods you want to override with @Override; the compiler will throw an error if there was no method found in the parent class to override.
If you want to make Person.getInfo() private to other classes but still want to override it, simply make it protected.


text:
Q: UI Grid column filtering works very slow I have used UI-Grid's built in cell filters but it takes hell lot of time to filter the data even when I have just 20 records.
<div id="grid1" ui-grid="gridCtrl.gridOptions1"
ui-grid-pagination
ui-grid-pinning
ui-grid-resize-columns
ui-grid-move-columns
ui-grid-selection
style="width: 100%; height:680px" class="ui-grid">
and i have just enabled filtering as true.
Please help

A: actually I found the reason behind this.. I rendered all my rows at once with virtualization Threshold = number of rows, this does not allow the default ui grid rendering algorithm to be used.

A: Here is a potential workaround...
1. In ui-grid.js, remove the watches set up for each column filter in the header.  See if this removes the sluggishness. It will also make the grid not respond to filter changes. Continue to steps 2-4 to make the filters work again.
//$scope.col.filters.forEach(function (filter, i) {
//filterDeregisters.push($scope.$watch('col.filters[' + i + '].term', function(n, o) {
    //  if (n !== o) {
    //    uiGridCtrl.grid.api.core.raise.filterChanged();
    //    uiGridCtrl.grid.api.core.notifyDataChange( uiGridConstants.dataChange.COLUMN );
    //    uiGridCtrl.grid.queueGridRefresh();
    //  }
    //}));
 //});

2. In your code, create a function that iterates through the filter terms of each column and creates a string of all filter terms.
function getConcatenatedFilter() {
        var concatenatedFilter = "";
        var api = this.getGridApi();
        if (api) {
            for (var i = 0; i < api.grid.columns.length; i++) {
                concatenatedFilter += i + ":";
                var column = api.grid.columns[i];
                var term = column.filters[0].term || "";
                if (term) {
                    concatenatedFilter += term;
                }
            }
        }
        return concatenatedFilter;
    }

3. Create one watch that monitors the concatenated filter function above. When it fires, create a timeout to that sets another scope variable called filtersCheck.  The timeout will wait 200ms before changing filtersCheck.
 $scope.$watch(function() {return getConcatenatedFilter();},
         function (newVal: string, oldVal: string) {
            if (filterTextTimeout) {
                $timeout.cancel(filterTextTimeout);
            }
            var tempFiltersString = newVal;
            filterTextTimeout = $timeout(() => {
                $scope.filtersCheck = tempFiltersString;
            }, 200);
        });

4. Finally, set up a final watch for filtersCheck which will refresh the grid when it fires.
$scope.$watch('filtersCheck', (newVal, oldVal) => {
    if (newVal && oldVal && newVal !== oldVal) {
        gridApi.grid.queueGridRefresh();
    }
});


text:
Q: Distance between two points in 3D - class, methods and objects, TypeError I'm trying to print the distance between two points in 3D using class and methods. I get a TypeError : distance() takes 1 positional argument but 2 were given.
Here is my code, k2 and k3 are the coordinates of the two points.
import math
class Point:
def __init__(self, x, y, z):
  self.x = x
  self.y = y
  self.z = z
def __str__(self):
  return "point : ({:d}, {:d}, {:d})".format(self.x,self.y,self.z)
def distance(self):
  distance = sqrt( (x1-x2)**2 + (y1-y2)**2 + (z1 -z2)**2 )
  return distance
k2 = Point(5, 7, 8)
k3 = Point(-3, -2, 5)
print(k3.distance(k2))

also tried
print(distance(k2, k3))

I get a NameError : name 'distance' is not defined
please suggest if I am missing something.
Thank you !
using python 3.7.4  on Mac Terminal

A: Where do x1/x2,... come from in the distance method? it seems your code wants to conjure them out of thin air...
Also, the method is declared as def distance(self), so it obviously only has a single argument (the reference to the object itself), and does not allow for any additional arguments to be passed to it.
What you really want, is an argument to the distance method where you can pass your reference-object to calculate the distance from. and you need to use the reference object's and the self object's coordinates to calculate the distance:
def distance(self, other):
   d = sqrt( (self.x - other.x)**2 + ...

This example is intentionally incomplete, but you should get the idea.
You probably really want to get a read on how to do object-oriented programming in Python (and probably how to do object oriented programming in general)


text:
Q: Target CSS to specific eDirectory page I want to make the major event image on the left height larger, without affecting other pages.
https://islandeguide.com/event/
I Noticed this page has this that makes it unique
h2 class="theme-title" data-trans="Featured Events">Featured Events/h2

So I thought I may be able to do something like
page.themetitle[Featured Events] .col-sm-5 > .theme-box.theme-box-vertical > .theme-box-content img{
height: 350px;
}

I made this part up page.themetitle[Featured Events] so I knew it would not work.
Does anyone know if I can put something there that would work?
Note:
I can add CSS to custom CSS document, but that is all! I do not have access to change the HTML/PHP, also I can not add Javascript.
This website was designed in a way that makes it very difficult to target elements without changing others on different pages, as they share Classes everywhere.

A: Try this:
h2[data-trans="Featured Events"].theme-title + div.row div.col-sm-5 div.theme-box.theme-box-vertical img {
    height: 350px;
}

Edit: You can shorten it a little using the child selector:
h2[data-trans="Featured Events"].theme-title + .row > .col-sm-5 > .theme-box.theme-box-vertical img {
        height: 350px;
}


text:
Q: Getting PID for a process running on a remote node I am new to Erlang and we are working on a small scale messaging server.
We are trying to build a process registry using Redis ( not planning to use existing once grpoc, global etc due to other business needs ) as a datastore ( store to hold user-id to "node | PID " mapping). When a process starts it register itself with Redis in the form user_id (key) and {node | pid } as value. ( pid is tored as string in redis)
example value inserted in redis are "user_abc", {one@mf, "0.37.0>"}
Now when I try to find PID for "user_abc" which is running in the cluster - i get {node and pid} as value on a remote node which in this case is {one@mf, "0.37.0>".
Question is how do we use {node, pid} details on remote node to connect to the process user_abc.
Thanks in advance for your help.

A: You can get a "cluster wide" pid by parsing that pid on the remote node:
On node a:
(a@host)1> pid_to_list(self()).
"<0.39.0>"

On node b:
(b@host)1> Pid = rpc:call('a@host', erlang, list_to_pid, ["<0.39.0>"]).
<7101.99.0>
(b@host)2> Pid ! my_test.
my_test

On node a:

(a@host)2> flush().
Shell got my_test
ok

Note that the process might not be alive, so calling erlang:monitor/2 on it before talking to it might be a good idea.

A: If you want to store erlang pid to redis, and want other node read it as a remote pid, use erlang:term_to_binary(Pid) to store, and use erlang:bianry_to_pid(PidBin) to read.
See this post:Erlang Pid


text:
Q: In MongoDB how is text stemmed if my text contains a UUID? I'm investigation slow updates on a collection in MongoDB.
The former colleagues have chosen the string type for the _id field and basing indexes on other string fields.
Now I understand text indexes are stemmed, and I can imagine this can be quite heavy when a document is updated.
Also the content of the _id-field is a UUID. Now I don't fully understand how stemming works, but guessing each part of the UUID (part1-part2-part3-part4-etc) becomes a unique entry in the index, causing queries to be slow.
Can someone explain how stemming would work on text which contains a UUID?

A: Stemming only applies to string fields that are part of a text index. The options for the default _id index cannot be changed and an _id index cannot be a text index, so stemming is not applicable in this context. The _id value is a single entry in the index which must be unique.

Now I don't fully understand how stemming works, but guessing each part of the UUID (part1-part2-part3-part4-etc) becomes a unique entry in the index, causing queries to be slow.

Stemming uses language-specific heuristics to reduce words to their expected root forms. Stemming libraries have a notion of typical inflection rules for languages but do not have any understanding of valid words or grammar. It generally doesn't make sense to include a UUID field (or other random non-language string) in a text index definition.
MongoDB text indexes use the open source Snowball library for stemming.

Can someone explain how stemming would work on text which contains a UUID?

The best approach would be to explain MongoDB $text queries to see exactly how they are parsed. However, there's also an online Snowball demo which can be useful if you want to quickly try stemming algorithms for different languages.
A MongoDB text index or $text query will treat whitespace and most punctuation characters (including hyphens) as word delimiters, so part1-part2-part3-part4-etc would be split into 5 terms. Each term will be stemmed and any duplicate terms will be ignored. Terms made up of random letters or values like part1 won't have a root form outside of accidental matching by the stemming heuristics.
For example, in English:

*

*Words ending in a single s are generally plural. If you make up a random word like part4s , it will stem to part4.

*Words ending in ss are generally not plural, so part4ss will be left unchanged.

You can see how a phrase would be stemmed by explaining a text search query and looking at the terms for the parsedTextQuery.
Using the mongo shell:
> db.stores.createIndex( { name: "text", description: "text" } )
> db.stores.find( { $text: { $search: "part1-part2-part3-part4-etc-part4s-part4ss" } } ).
       explain().queryPlanner.winningPlan.parsedTextQuery
{
    "terms" : [
        "etc",
        "part1",
        "part2",
        "part3",
        "part4",
        "part4ss"
    ],
    "negatedTerms" : [ ],
    "phrases" : [ ],
    "negatedPhrases" : [ ]
}

I added part4s and part4ss to your example UUID. Since part4s stems to part4 (which is already a unique term) you'll notice my query only finds 6 terms instead of 7.


text:
Q: select2 with lit element I am trying to use select2 in my lit element, but it is not finding the select2 functio and throws the error

"Uncaught (in promise) TypeError:
this.shadowRoot.getElementById(...).select2 is not a function"

I am following the code from here https://stackblitz.com/edit/litelement-how-to-implement-select2-in-litelement-e2twiq?file=index.js
My code:
import {LitElement, html} from 'lit';

class test extends  LitElement {
    render() {
        return html`

        <link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
        <script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
            <style>
            </style>
            <div id="header-container">
                        <select id="select-state" placeholder="Pick a state...">
                            <option value="">Select a state...</option>
                            <option value="AL">Alabama</option>
                            <option value="AK">Alaska</option>
                            <option value="AZ">Arizona</option>
                            <option value="AR">Arkansas</option>
                         </select>
                </div>
            `;
    }

    constructor() {
        super();
        this.countrydata = [html`<option id="option" >arpit</option>`,
            html`<option id="option">tandon</option>`,
            html`<option disabled id="option" >  shyam</option>`,
            html`<option id="option">brian</option>`,
            html`<option id="option">danielle</option>`,
            html`<option id="option">howard</option>`];
    }

    connectedCallback() {
        super.connectedCallback();
    }

    firstUpdated(){
        this.shadowRoot.getElementById('select-state').select2();
        //var test = this.shadowRoot.getElementById('sourcecountrycode');
        //this.test.select2();
    }
}

window.customElements.define("test", test);


text:
Q: iOS: How to show a shadow image in a button? My designer send me a button image with shadow which is complicate, so I need to use the button image instead of implementing the shadow myself. For example, the clickable red area is 20*20 and the whole image with shadow is 60*60. The red area is not in the center of the image.
The question is I want to make a 20*20 button and it can show the whole image.
The implement I'm using is adding an UIImageView (size=60*60) into a button(size=20*20). Is there any other way to do it? I think there's a way to use only image and button without an additional UIImageView

A: Here's a simple example:
func createView(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {

        // creating the container view
        let view = UIView()
        view.frame = CGRect(x: x, y: y, width: width, height: height)
        view.backgroundColor = .systemRed

        // creating the image view, set the image to the one you want
        let imageView = UIImageView()
        imageView.frame = CGRect(x: 0, y: 0, width: width, height: height)
        let image = UIImage(named: "myImage")
        imageView.image = image

        // creating the button
        let button = UIButton()
        button.frame = CGRect(x: 0, y: 0, width: width / 3, height: height / 3)
        button.backgroundColor = .systemBlue

        // adding a tap response functionality to the button
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)

        // adding the button and image view to the container
        view.addSubview(imageView)
        view.addSubview(button)

        //adding the container to the superview
        self.view.addSubview(view)

    }

Adding the method to handle a button tap:
    @objc func buttonTapped() {
        // all the code for handling a tap goes here
        print("button tapped")
    }

And finally calling createView() in viewDidLoad():
override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        createView(x: 100, y: 100, width: 60, height: 60)
    }

It is important to note that the x and y values of the button and image do not refer to that of the superview, but rather to that of the container view.
If you want to add the shadow image, it must be include in the Assets.xcassets folder. From there, you can simply change the name to that of the image and it will be uploaded.


text:
Q: Selecting Persons Name beginning on the right I know how to do a left, right and substring in T-SQL, but I'm having difficulty extracting just the name of the person below since the length of the name are not the same. Any ideas or syntax that I can use to extract just the name? Thanks
Data Value:
581;#Jackson, Daniel H; 501;#Sims, Katy L; 606;#Lawrence, Jennifer O

A: You can get the length of the name dynamically using PATINDEX, but it assumes that the Names are ALWAYS formatted the same way.
Here is an example of a TSQL Select that will give select the first names from the data you supplied:
CREATE TABLE #Temp (
    ID INT NOT NULL,
    FullName VARCHAR(100)
)
INSERT #Temp VALUES (581, 'Jackson, Daniel H')
INSERT #Temp VALUES (606, 'Lawrence, Jennifer O')

SELECT ID, FullName , SUBSTRING(FullName, PATINDEX('%, % _', FullName) + 2,
    PATINDEX('% _', FullName) - PATINDEX('%, %', FullName) - 2) FirstName
FROM #Temp
DROP TABLE #Temp

A: I use a function to split up CSV-Strings:
create function Do_Split
  (@InputString  NVARCHAR(4000)
  ,@Delimiter    NVARCHAR(50) = ';')
RETURNS @Items TABLE (Item NVARCHAR(4000)) AS

BEGIN --Function
IF (@Delimiter = ' ')
BEGIN
  SET @Delimiter = ';'
  SET @InputString = REPLACE(@InputString, ' ', @Delimiter)
END;

IF (@Delimiter IS NULL OR @Delimiter = '') SET @Delimiter = ';';

DECLARE @Item          NVARCHAR(4000)
DECLARE @ItemList      NVARCHAR(4000)
DECLARE @DelimIndex    INT

SET @ItemList = @InputString;
SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0);
WHILE (@DelimIndex != 0)
  BEGIN
  SET @Item = SUBSTRING(@ItemList, 0, @DelimIndex);
  INSERT INTO @Items VALUES (@Item);

-- Set @ItemList = @ItemList minus one less item
  SET @ItemList = SUBSTRING(@ItemList, @DelimIndex+1, LEN(@ItemList)-@DelimIndex);
  SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0);
  END;  -- End WHILE

IF @Item IS NOT NULL -- At least one delimiter was encountered in @InputString
  BEGIN
  SET @Item = @ItemList;
  INSERT INTO @Items VALUES (@Item);
  END;
ELSE      -- No delimiters were encountered in @InputString, so just return @InputString
  BEGIN
  INSERT INTO @Items VALUES (@InputString);
  END;

RETURN
END -- End Function
go

Usage:
 SELECT * FROM Do_Split('581;#Jackson, Daniel H; 501;#Sims, Katy L; 606;#Lawrence, Jennifer O',';');

Result:
581
#Jackson, Daniel H
 501
#Sims, Katy L
 606
#Lawrence, Jennifer O

A: It isn't clear how your data looks like, because your example concatenates multiple values in one row.
Case 1
Assume that there're 2 columns id and full_name in your_table. The semicolon ; was added by you intentionally to distinguish columns. In this case, you can obtain the value of full name using the function RIGHT. The length would be the length of full_name minus 1 which excludes the #.
--
-- id  full_name
-- --  ---------
-- 581 #Jackson, Daniel H
-- 501 #Sims, Katy L
-- 606 #Lawrence, Jennifer O
--
SELECT RIGHT(full_name, LEN(full_name) - 1) AS full_name
FROM your_table;

Case 2
If the above solution is not suitable, let's discuss another case. Assume that there's 1 column content in your_table and 3 rows. The semicolon ; was inside the value of content and need to be treated explicitly. In this case, you can obtain the value of full name using the function SUBSTRING. The full name will begin after just after the index of char # and this index can be obtained using CHARINDEX (Transact-SQL):
--
-- content
-- -------
-- 581;#Jackson, Daniel H
-- 501;#Sims, Katy L
-- 606;#Lawrence, Jennifer O
--
SELECT SUBSTRING(content, CHARINDEX('#', content) + 1, 1000) AS full_name
FROM your_table;


text:
Q: Beautiful soup select two item with parent child realtionship The code below finds all the links with gameId and puts the links in a dataframe. My issue is that I am not sure how I store them in a dataframe with the corresponding date. In this case the h2 is the parent tag with the child tag having the links. The code below get the links but how get date for each gameId.
import pandas as pd
import requests
from bs4 import BeautifulSoup

gmdf = pd.DataFrame(columns=['link','gamedate'])

url = 'https://www.espn.com/nfl/schedule/_/week/1/year/2020'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
links = soup.select('a')

for link in links:
      if 'gameId' in link.get('href'):
            print(link.get('href'))
            hlink = 'https://www.espn.com' + link.get('href')
            gmdf = gmdf.append({'link': hlink}, ignore_index=True)

This line to get the dates on the page but I need the dates with corresponding gameid in the data frame.
soup.select('h2')

A: Here is an alternative method from what Dhivakar has already provided. In it, I add the h2 tag in the original selection by BeautifulSoup, then, I set the date based on when the link does not have an href, since we know it must either be h2 or a tag, and h2 tags contain the dates.
import pandas as pd
import requests
from bs4 import BeautifulSoup

gmdf = pd.DataFrame(columns=['link','gamedate'])

url = 'https://www.espn.com/nfl/schedule/_/week/1/year/2020'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
links = soup.select('a, h2')

date = ""
for link in links:
    if link.get('href') is None:
        date = link.text
        print(date)
    elif link.get('href') is not None and 'gameId' in link.get('href'):
        print(date)
        print(link.get('href'))
        hlink = 'https://www.espn.com' + link.get('href')
        gmdf = gmdf.append({'link': hlink, 'gamedate': date}, ignore_index=True)

print(gmdf)

Output:

A: You can grab parent and siblings of elements just like in JavaScript.
Replace this after links = soup.select('a'),
schedule_year = soup.select_one('.automated-header h1').text.split("- ")[-1] # For the schedule year

for link in links:
      if 'gameId' in link.get('href'):
            schedule_date = link.parent.parent.parent.parent.parent.previous_sibling.text.split(", ")[-1] + " " + schedule_year # Grabs the h2 tag
            schedule_date = datetime.datetime.strptime(schedule_date, "%B %d %Y") # Converted the date to datetime object for manipulation
            hlink = 'https://www.espn.com' + link.get('href')
            gmdf = gmdf.append({'link': hlink, 'gamedate': schedule_date}, ignore_index=True)

A: You can simply use a nested loop within a list comprehension to loop those date headers then find the next table and grab the list of href containing the substring of interest (gameId). That way you can have the relevant date listed against each link in a list of tuples you convert to a DataFrame:
import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

r = requests.get('https://www.espn.com/nfl/schedule/_/week/1/year/2020')
soup = bs(r.text, 'lxml')

df = pd.DataFrame([('https://www.espn.com' + j['href'], i.text) for i in soup.select(
    '#sched-container .table-caption') for j in i.find_next('table').select('[href*=gameId]')], columns=['link', 'date'])

print(df)


text:
Q: Bootstrap 3.0 cause collapse entire code like a sentence, google prittyfy I am using Markdown, google prettify and bootstrap then result comes in single line like this
Create Proc log AS Begin Try Select 10 / 0 End Try Begin Catch EXEC LogErr End Catch

Just commented out the "~/Content/bootstrap.css" file in bundling of my mvc application and result comes like this
Create Proc log
AS
Begin Try
   Select 10 / 0
End Try
Begin Catch
   EXEC LogErr
End Catch

My entire application is designed by using the bootstrap, so I cannot remove this CSS, Is there any way to use the bootstrap with google prettify and markdown?

A: I found the issue, here is the class which was causing it
pre code {
  padding: 0;
  font-size: inherit;
  color: inherit;
  white-space: pre-wrap;
  background-color: transparent;
  border-radius: 0;
}

Change to
pre code {
  padding: 0;
  font-size: inherit;
  color: inherit;
  /*white-space: pre-wrap;*/
  background-color: transparent;
  border-radius: 0;
}

white-space: pre-wrap; was wrapping the code, might be it can help someone.


text:
Q: Inquiry about Validation Laravel I have a question about Laravel validation. I have two number <input> fields like:

I want to create a rule in the "Request" file from App\Requests\MyRequest.php that requires the value from the second input field to be greater than the first input field and that both fields must have a value greater than 0.
How should I code this? Does Laravel validation support this?

A: You can add validations in app/Http/Requests by running php artisan make:request MyRequest something like below:
<?php

namespace App\Http\Requests;

class MyRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
    */
    public function authorize()
    {
       return true;
     }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
             'first_field' => 'min:0',
             'second_field' => 'min:'.$this->first_field,
        ];
   }
}

You can find more about validations here


text:
Q: Persisted Computed Column to calculate area? I have a table (rugs) that has columns for length and width (both 2 place decimals).
I'm trying to create a computed column named area which simply multiplies the length by width to generate the area but hitting syntax errors when running the query.
My attempted code using mySQL was as follows:
alter table `rugs` add `area` as (`length` * `width`) PERSISTED

But it's not liking the syntax, getting a #1064 error

A: In MySQL, the syntax is:
alter table rug add area generated always as (length * width) stored;

The documentation explains the syntax.
Your syntax is more appropriate for SQL Server.


text:
Q: R - Wald test and Autocorrelation test Please, how can I do Wald test (heteroskedasticity) and autocorrelation test (from Wooldridge) in R?
I'm using Pooled OLS, Fixed Efects and Random Efects with library(plm) in a unbalanced panel.
Thanks.

A: Here is a link that provides directions how to perform the heteroskedasticity tests you are looking for using lme and lmtest packages. There are many comments and recommendations:
http://people.tamu.edu/~b-wood/Maximum%20Likelihood/RLesson%204.htm
As for specifically plm package:
You can find some examples here
Waldtest in R to get adjust F statistic with plm and result shown with stargazer? and looking at the documentation of plm package. The plm package states: In
plm we provide a number of joint, marginal and conditional
ml-based tests, plus some semi-parametric alternatives which are robust vs.  heteroskedasticity and free from distributional
assumptions.
You should also look into lfe package:
https://cran.r-project.org/web/packages/lfe/lfe.pdf


text:
Q: Code Insight (IntelliSense) I am trying to add a description to functions I developed - I want this description to display in code insight when another developer is using my units or when a user uses API/COM to connet and uses our software. At the moment all they see is e.g. Function name and return type but they have no idea what the function does exactly.
in C# you use XML tags.

A: Marco Cantu has a great blog post about how to use the same system of XML tags that Visual Studio uses to customize HelpInsight.

A: I'm not sure that's what you need but:
    /// <summary>
    ///
    /// </summary>
    /// <param name="par1"></param>
    /// <param name="bla"></param>
    /// <param name="foo"></param>
    /// <returns></returns>

Put this above a function declaration (just type the / character three times and visual studio will do the magic)
In summary you have to put the description


text:
Q: opening multiple PDF in a frame The requirement is that there are a couple of hyperlink on the left upon clicking the hyperlink I need to open PDF's on the right in a frame
(it can be a content editor or a page viewer etc.)
i placed two script editor (on the left and right, one to show hyperlinks another for the pdf).please see below for the code i have used
here i have loaded pdfs but hid all but the first one
<object class="pdfobject" id="1" data="https://he.sharepoint.com/sites/SiteOffices/PMMDetailsPDF/1.pdf?#zoom=85&scrollbar=1&toolbar=0&navpanes=1" width="800" height="800" type="application/pdf" />

here i created hyperlinks pointing to the same page and Jquery to show the pdfs.
Pdf1
Pdf1
Pdf1

$('.pdflink').click(function(){
    $('.pdfobject').hide(); //Hide all pdf
    var objId = $('this').attr('objectid'); //Get pdf object element id from link
    $('#' + objId).show(); //Show respective pdf
});

A: There are know issues with dynamically changing the source file path. Workaround you can try is by hiding and showing respective frame on clicking the link.
You can use jQuery or pure JavaScript to do this.
Adding link to Script Editor webpart as below
<object class="pdfobject" id="1" .... /> --This will be visible initially
<object class="pdfobject" id="2" style="display:none;"...
<object class="pdfobject" id="3" style="display:none;"...
....

Now you can handle the link
Pdf1
Pdf1
Pdf1
....

You can use below jQuery code
$('.pdflink').click(function(){
    $('.pdfobject').hide(); //Hide all pdf
    var objId = $('this').attr('objectid'); //Get pdf object element id from link
    $('#' + objId).show(); //Show respective pdf
});


text:
Q: How to deserialize this using GSON? (get rid of List) I have jsons like:
{
    "id":  "AnId",
    "type": "Button",
    "parameter": {
        "text" : "TestText"
    }
}

parameters can be of any structure and they can contain further json objects or arrays, too, e.g:
{
    "id":  "AnId",
    "type": "RadioGroup",
    "parameter": {
         "groupname": "AGroupName",
         "selected": "r2",
         "radioboxes": [
              {
                   "id": "r1",
                   "label": "radio1"
              },
              {
                   "id": "r2",
                   "label": "radio2"
              }
         ]
    }
}

However, depending on the type, it is known what the parameters look like, e.g.
public class RadioGroup {
    private String groupName;
    // ..other primitive attributes here..
    private Map<String, RadioBox> radioBoxes;
    // ... getters/setters
}

public class RadioBox {
  private String id;

  private String label;
  // ... getter/setters
}

BUT I don't know the type before I deserialized it!
I wonder what is the best way to deserialize input where I dont know whether I get button or radiogroup json?
Until now I just deserialize the given input (button or checkbox, not known yet) to Map<String, Object>, if it is in fact button it works fine, but if I provide the radiogroup as input, I will get gson's internal type ArrayList<StringMap> for the radioboxes. The primitive parameters like groupName are fine (String.class). But what can I do to get List<Map<String,Radiobox>> instead of ArrayList<StringMap> for the radioboxes parameter?

A: You need to set the Type of the custom class you're using. This is for serialising (just an example):
    Gson gson = new GsonBuilder().create()
    Type aType = new TypeToken</ClassName/>() {}.getType();
    String json = gson.toJson(this, aType);

gson will then convert the variable types correctly. If you're using a custom class as a variable, you'll need to write a custom type adapter and register the type adapter with the GsonBuilder() instance.
To deserialise, you'll need the same process.
EDIT:
    Class<?> klass = null;
    try {
        klass = Class.forName(className);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        throw new JsonParseException(e.getMessage());
    }

A: you can parse arbitrary json using GSON JsonDeserializer. I've write model class for RadioGroup as following but you can change it according to your need.
public class RadioGroup {
  private String id;
  private String type;
  // You can put groupName and selected properties into other class,
  private String groupname;
  private String selected;
  // for button param parsing into Map
  private Map<String,String> btnParam;
  // for radion Btn just parsing into List
  private List<RadioBox> radioboxes;
}

public class CustomDeserializer implements JsonDeserializer<RadioGroup> {

        @Override
        public RadioGroup deserialize(JsonElement json, Type arg1,
                JsonDeserializationContext arg2) throws JsonParseException {

            final JsonObject jsonObject = json.getAsJsonObject();
            final String id= jsonObject.get("id").getAsString();
            final String type= jsonObject.get("type").getAsString();
            final RadioGroup radioGroup = new RadioGroup();

            radioGroup.setId(id);
            radioGroup.setType(type);

            JsonElement jsonElementForParam = jsonObject.get("parameter");
            JsonElement jsonElementForText = jsonElementForParam.getAsJsonObject().get("text");

            if(null==jsonElementForText){
                String groupname = jsonElementForParam.getAsJsonObject().get("groupname").getAsString();
                String selected = jsonElementForParam.getAsJsonObject().get("selected").getAsString();
                JsonElement jsonElementForRadioboxes = jsonElementForParam.getAsJsonObject().get("radioboxes");

                radioGroup.setSelected(selected);
                radioGroup.setGroupname(groupname);

                Gson gson = new Gson();
                Type typeOf = new TypeToken<List<RadioBox>>(){}.getType();
                List<RadioBox> radioboxes =gson.fromJson(jsonElementForRadioboxes, typeOf);
                radioGroup.setRadioboxes(radioboxes);

            } else if (null!=jsonElementForText) {
                Gson gson = new Gson();
                Type typeOf = new TypeToken<Map<String,String>>(){}.getType();
                Map<String,String> map = gson.fromJson(jsonElementForParam, typeOf);
                radioGroup.setBtnParam(map);

            }

            return radioGroup;
        }
      }

Finally Parse it
GsonBuilder gsonBuilder = new GsonBuilder();
   gsonBuilder.registerTypeAdapter(RadioGroup.class, new CustomDeserializer());
   Gson gson = gsonBuilder.create();
   RadioGroup radioGroup = gson.fromJson(buttonJson, RadioGroup.class);


text:
Q: Use Jython and lint on VScode I would like to use Pylint to lint Jython code.
Clearly, all Java functions (JPanel, JFrame, JComboBox, etc.) are recognized as an error (eg. undefined variable 'JPanel').
I would like to know if there was a way to disable the undefined variable rule on VScode.
Or better yet, if an external Jython linter existed, it would be optimal! Because I have seen that there are no extensions for VSCode for Jython, unfortunately, and of course not even on the linting of jython code.
If none of the things listed above were possible, I would be happy to use another editor with linting, shorcut for self-formatting, etc.
In short, the essential of VScode!
EDIT
Based on a small experience of development in Angular it would be optimal to be able to put a pylinting file of Python 2.7 (since jython 3 doesn't exist) inside the project folder, exactly at the same way as it is done with tslint.json, and customize it by excluding for example the java functions.

I hope there is a way to do it.

A: Since Jython runs on Java (and not Python), you should use a Java Linting utility instead of Pylint. It will read in the import on the top of your document (import org.python.util.PythonInterpreter;) and (ideally) follow it to know all available methods and global variables exposed by Jython.
For linting Java, there are many options out there. You could try checkstyle, Findbugs or javac bundled as a linter. Since you're using VSCode, you might want to try Checkstyle (VSCode Marketplace), Java(c) Linter (VSCode Marketplace) or the official Eclipse-based Red Hat Java Language Support Extension (VSCode Marketplace) which includes Linting amongst other features.
Most of these extensions can be configured over a settings.json file in a .vscode directory from your project root.


text:
Q: Loop until TcpClient response fully read I have written a simple TCP client and server. The problem lies with the client.
I'm having some trouble reading the entire response from the server. I must let the thread sleep to allow all the data be sent.
I've tried a few times to convert this code into a loop that runs until the server is finished sending data.
// Init & connect to client
TcpClient client = new TcpClient();
Console.WriteLine("Connecting.....");
client.Connect("192.168.1.160", 9988);

// Stream string to server
input += "\n";
Stream stm = client.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(input);
stm.Write(ba, 0, ba.Length);

// Read response from server.
byte[] buffer = new byte[1024];

System.Threading.Thread.Sleep(1000); // Huh, why do I need to wait?

int bytesRead = stm.Read(buffer, 0, buffer.Length);
response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Response String: "+response);

client.Close();

A: The nature of streams that are built on top of sockets is that you have an open pipeline that transmits and receives data until the socket is closed.
However, because of the nature of client/server interactions, this pipeline isn't always guaranteed to have content on it to be read.  The client and server have to agree to send content over the pipeline.
When you take the Stream abstraction in .NET and overlay it on the concept of sockets, the requirement for an agreement between the client and server still applies; you can call Stream.Read all you want, but if the socket that your Stream is connected to on the other side isn't sending content, the call will just wait until there is content.
This is why protocols exist.  At their most basic level, they help define what a complete message that is sent between two parties is.  Usually, the mechanism is something along the lines of:

*

*A length-prefixed message where the number of bytes to be read is sent before the message

*A pattern of characters used to mark the end of a message (this is less common depending on the content that is being sent, the more arbitrary any part of the message can be, the less likely this will be used)

That said you aren't adhering to the above; your call to Stream.Read is just saying "read 1024 bytes" when in reality, there might not be 1024 bytes to be read.  If that's the case, the call to Stream.Read will block until that's been populated.
The reason the call to Thread.Sleep probably works is because by the time a second goes by, the Stream has 1024 bytes on it to read and it doesn't block.
Additionally, if you truly want to read 1024 bytes, you can't assume that the call to Stream.Read will populate 1024 bytes of data.  The return value for the Stream.Read method tells you how many bytes were actually read.  If you need more for your message, then you need to make additional calls to Stream.Read.
Jon Skeet wrote up the exact way to do this if you want a sample.

A: Try to repeat the
int bytesRead = stm.Read(buffer, 0, buffer.Length);

while bytesRead > 0. It is a common pattern for that as i remember.
Of course don't forget to pass appropriate params for buffer.

A: You dont know the size of data you will be reading so you have to set a mechanism to decide. One is timeout and another is using delimiters.
On your example you read whatever data from just one iteration(read) because you dont set the timeout for reading and using default value thats "0" milisecond. So you have to sleep just 1000 ms. You get same effect with using  recieve time out  to 1000 ms.
I think using lenght of data as prefix is not the real solution because when socket is closed by both sides, socket time-wait situation can not handled properly. Same data can be send to server and cause server to get exception . We used prefix-ending character sequence. After every read we check the data for start and end character sequence, if we cant get end characters, we call another read. But of course this works only if you have the control of server side and client side code.

A: In the TCP Client / Server I just wrote I generate the packet I want to send to a memory stream, then take the length of that stream and use it as a prefix when sending the data.  That way the client knows how many bytes of data it's going to need to read for a full packet.


text:
Q: Why didn't Tony Stark have the Arc Reactor removed? If Tony Stark could have gotten the Arc Reactor removed safely (as evidenced in Iron Man 3), then why didn't he get that done in Iron Man 2 when it was killing him?

A: Copied from my answer over on Movies.SE for a similar question:
During the scene where Tony has the surgery, you can see a miniature ARC reactor and some gadgets above Tony.  As the surgeon removes a piece of shrapnel, he releases it and it flies up to the gadget.  So Tony and the surgeon built an electromagnetic device to help out with the surgery.  The eagle-eyed will also notice that when they show Pepper and Rhodey watching the surgery, the signs on the doors in front of them are in Chinese.  Shortly afterwards, Tony gives Pepper a necklace, and behind them is Shanghai's skyline.  He went to China for his surgery.
During the credits, you'll see there were several movie studios involved in making the film.  Marvel Studios and Paramount are familiar names to people who watch Hollywood films.  DMG Entertainment was another one, which may be more familiar to fans of Chinese cinema.  They're a Chinese company that in recent years has been investing in Hollywood movies.  They do this, and Hollywood movie studios agree to this, because by working with a Chinese company, the film then isn't treated like a foreign film.  There are limits on the number of foreign films that can be released each year in China, this sidesteps that.  In return though, DMG has extra China-centric scenes filmed that are then included in a China-only cut of the film (this happened for both Looper and Iron Man 3).
For Iron Man 3, the China-only scenes explain why Tony went to China for his surgery.  At the start of the film, in Switzerland, Tony briefly meets Ho Yinsen and Dr. Wu, a cardiologist.  Dr. Wu is the one who performs his surgery.  In the non-China cut of the film, this isn't really explained.  During the China-only scenes, it's stated that Dr. Wu is the only one who can remove the shrapnel from Tony's chest.  So Tony goes to China and gets the shrapnel removed, which is something he couldn't do before.


text:
Q: RVM vs native installation of ruby I was wondering if there is any downsides from using rvm in a production server. What should I prefer, rvm or native installation and why?

A: Don't do it, err, maybe do it
Simplicity is always rewarded.
Rvm is a development tool. Since you will not be switching Ruby versions back and forth dynamically on a production server, it can do no good and could create arbitrary levels of pain and suffering.
Update: Ok, we've got some excellent comments and know more now. For one, rvm was in fact a production tool first. (Who knew?) It looks like if an application doesn't bundle its own gem environment, rvm will do it at the system level, and that could be useful.
So there probably isn't a single answer to this question.  If only one application runs on the server, or if all server applications are, say, Rails3, then rvm will not be needed. But other scenarios will benefit from the environment management.

A: Use RVM. Because it is more simple.
You'll have all distributions in one place, all gems in one place, and you're using the same tool that you use in development. There are no performance issues either.

A: Use RVM, as that way your application has exactly what it needs, and system updates do not interfere or change your requirements.  One host I set up had a distro version of 1.8, but I wanted to develop for 1.9.2.  Rather than break the distro version, RVM lets me run a custom version.  RVM plays well with passenger phusion for rails deployments too.

A: Compile your own Ruby and MongoDB, PostgreSQL, MySQL, redis, and whatever other supporting tools you rely on. This way get full control over the versions used everywhere and you can apply any necessary security or bug fix upgrades at will without having to wait for your OS vendor to supply system updates and patches. Compiling your own also makes it easier to ensure that your development, staging, and production environments are all using the same versions of everything you need.
If using RVM makes it easier for you to build your own toolchain then use RVM. In any case, using the system supplied tools often leaves you a few versions behind and leaves you hanging when you need to apply critical patches.

A: system installation:

*

*easier accessible

rvm installation:

*

*possible to switch (fast) ruby

*allow multiple version if required for multiple apps

*easy upgrade of ruby version and management of gems update


text:
Q: How do I create a lambda expression with unknown fields? I want to dynamically build the lambda expression so that I can build a query with an unknown number of fields...how do I accomplish this?
I am looping through an object that contains all of the fields and values adding to the Where clause for each field...
searcher = searcher.Where(f => f.fieldName.Contains(fieldValue));

i.e. pseudo-code:
foreach(var field in fields){
    searcher = searcher.Where(f => field.name.Contains(field.value));
}

If I were living in the stone-age I'd pseudo-code it like this:
var first = true;
string query = " SELECT * FROM TABLE WHERE ";
foreach(var field in fields){
    if(first){
        query += field.name + " LIKE '%" + field.value + "%' ";
    }else{
        query += " AND " + field.name + " LIKE '%" + field.value + "%' ";
    }

    first = false;
}

Please tell me the stone-age isn't more powerful than current technology! ;-)

A: I hope this will be helpful.
searcher = fields.Aggregate(searcher, (current, field) => current.Where(f => f.Name.Contains(f.Value)));


text:
Q: Differentiate between a number (of type double) with decimal places and one without - c++ I am trying to implement a simple decimation algorithm in c++. I have two arrays, say p & q, where the subscripts are related to each other by the following relation:
p[k] = q[0.5*k]. This means that the following sequence should hold valid:
p[0] = q[0]
p[1] = 0
p[2] = q[1]
p[3] = 0
p[4] = q[2]

and so on...
Please note that p[k] takes on a value only and only when the result of (0.5*k) contains no decimal places (or has 0 in decimal) and does not use any rounding off etc.
My question is: Is there a way to distinguish between an integer (a number with no decimal places or only 0 in decimal, say 2.0) and a number with decimal places in C++, provided both are cast to double?
eg.) 2.0 is an integer cast to double. 2.1 is a number with decimal places.
eg. 2) * 0.9*2 should put 0 into array p while 0.9*10 should put q[9] into array p.*
If I use the statement, (int) (0.5*k), then I end up with an integer in every case, irrespective of the value of k.
Edit: The 0.5 in the above case is only illustrative. It could be any number, say 2, 2.5, 0.9, 0.95 etc.)
Any help is most welcome,
Thanks,
Sriram.

A: Assuming k is of an integer type, you could use if (k % 2 == 0) ... to check if kis divisible by two:
if (k % 2 == 0)
  p[k] = q[k / 2];
else
  p[k] = 0;

This can also be expressed using the ternary operator:
p[k] = (k % 2 == 0) ? q[k / 2] : 0;

A: Presuming that the coef can be anything else,
p[floor(coef*k)] = (fabs(coef*k-floor(coef*k))<1E-6)?q[k]:0;

A: The short syntax for what you want to do could be this:
p[k] = k % 2 ? 0 : q[k/2];

Is there a way to distinguish between a whole number and an integer in C++?

Define whole number, and define integer in this context. I'm confused!
Are you taking about the difference as explained here?
If you want to detect whether a number is integer or not, then probably this may help:
#include<cmath>

bool IsInteger(double d)
{
    double intpart;
    return std::modf(double number, &intpart) == 0.0;
}

A: k % 2 is in a couple of answers in this thread.
However, this is not useful in answering the OP's question. Note the edit:
"Edit: The 0.5 in the above case is only illustrative. It could be any number, say 2, 2.5, 0.9, 0.95 etc.)"
k % 2 only works because the value chosen was 0.5. It won't hold true for any other values.
Therefore, unless I'm missing something entirely, the simplest approach I can think of is the following:
Subtract the floor of the number from the number itself. If the result is > 0, it is not an integer.

A: Unless you have expressions that result in irrational numbers, you could use Boost.Rational to represent your indizes.

A: @Aix's suggestion of k%2 looks like it'd combine nicely with the ?: operator:
p[k] = (k%2) ? 0 : q[k/2];


text:
Q: What parameters can be used in filepath for ModelCheckpoints (tf.Keras)? I'm trying to train a Keras model and save model weighta at every epoch and patch.
I define a checkpoint as follows:
checkpoint_path='model_checkpoints_5000/checkpoints_{epoch:02d}_{batch:04d}'
checkpoint = ModelCheckpoint(filepath = checkpoint_5000_path,frequency = 5000)

and train the model:
model.fit(x=x_train, y=y_train, epochs=3, validation_data=(x_test, y_test),
               batch_size=10, callbacks=[checkpoint])

But right after the forst iteration the error occurs:
KeyError: 'Failed to format this callback filepath: "model_checkpoints_5000/checkpoints_{epoch:02d}_{batch:04d}". Reason: \'batch\'

How can I have python add the batch number to the file name?
How to fide the list of other parameters that are available for output?
My setup: Windows 10, jupyter notebook in chrome, Python 3.5.4, Tensorflow 2.3.0, Keras is imported from Tensorflow.


text:
Q: Django permissions mixin on CBV, how to apply on 'publish blog' method I'm quite new to Django, and I use the Django's CBVs. Currently I'm applying the permissions to my project by using the LoginRequiredMixin, PermissionRequiredMixin etc. On the views it works perfect! However, I've got a few methods that are function-based.
For example, to publish a blog via an URL

/blogs/1/publish

is bound to
url(r"^(?P<pk>[0-9]+)/publish/$", views.publish, name="publish"),

which calls
def publish(request, pk):
    if request.method == "GET":
        Blog.objects.filter(pk=pk).update(publish_date=datetime.datetime.now())
    return HttpResponseRedirect("/blogs/" + pk)

Since I use class-based-views, all of my views can be protected with the mixins. On function based, I'm not sure what the appropriate method would be to protect these.
Should I someway convert these function based methods to a class or
should I create method decorators which check the permissions for these occasions? Or is there an other method which is more convenient?

A: Django has decorators like login_required and permission_required decorator, which you can use for function based views. These have actually been in Django much longer than the mixins for CBVs which were added in Django 1.9.
@permission_required('myapp.can_publish')
def publish(request, pk):
    if request.method == "GET":
        Blog.objects.filter(pk=pk).update(publish_date=datetime.datetime.now())
    return HttpResponseRedirect("/blogs/" + pk)

As an aside, it's normally best practice to use a POST request for an action like changing the published date.

A: Too ways are possible:

*

*create CBV for publish and override post method:
class PublishView(UpdateView):

    model = Blog

    def post(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk', None)
        Blog.objects.filter(pk=pk).update(publish_date=datetime.datetime.now())
        return HttpResponseRedirect("/blogs/" + pk)

*Inside the Blog UpdateView define publish as staticmethod:

     class BlogUpdateView(UpdateView):

            model = Blog

            @staticmethod
            def publish(request, pk):
               if request.method == "GET":
               Blog.objects.filter(pk=pk).update(publish_date=datetime.datetime.now())
               return HttpResponseRedirect("/blogs/" + pk)

 in urls you access your function directly your publish method
url(r"^(?P<pk>[0-9]+)/publish/$", views.BlogUpdateView.publish, name="publish"),


text:
Q: error with docker container in bitbucket pipelines I'm deploying my dockerized Django app using bitbucket pipelines but unfortunately, the pipeline already creates two containers but not the last one the error and my files are attached below.
error
ERROR: for db  Cannot create container for service db: authorization denied by plugin pipelines: -v only supports $BITBUCKET_CLONE_DIR and its subdirectories
Encountered errors while bringing up the project.

docker-compose.yml
version: "3.8"

services:
  db:
    container_name: db
    image: "postgres"
    restart: always
    volumes:
      - postgres-data:/var/lib/postgresql/data/

  app:
    container_name: app
    build:
      context: .
    restart: always
    volumes:
      - static-data:/vol/web
    depends_on:
      - db

  proxy:
    container_name: proxy
    build:
      context: ./proxy
    restart: always
    depends_on:
      - app
    ports:
      - 80:8000
    volumes:
      - static-data:/vol/static

volumes:
  postgres-data:
  static-data:

bitbucket-pipelines.yml
image: python:3.7.2

pipelines:
  default:
    - step:
        services:
          - docker
        caches:
          - docker
          - pip
        script:
          - pip install docker-compose
          - docker-compose -f docker-compose-deploy.yml up --build
          - pipe: atlassian/aws-code-deploy:0.2.5
            variables:
              AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION
              AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
              AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
              COMMAND: 'upload'
              APPLICATION_NAME: $APPLICATION_NAME
              ZIP_FILE: 'application.zip'
              S3_BUCKET: $S3_BUCKET
              VERSION_LABEL: 'my-app-2.0.0'
          - pipe: atlassian/aws-code-deploy:0.2.5
            variables:
              AWS_DEFAULT_REGION: $AWS_DEFAULT_REGION
              AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
              AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
              COMMAND: 'deploy'
              APPLICATION_NAME: $APPLICATION_NAME
              DEPLOYMENT_GROUP: $DEPLOYMENT_GROUP
              WAIT: 'true'
              S3_BUCKET: $S3_BUCKET
              VERSION_LABEL: 'my-app-2.0.0'
              IGNORE_APPLICATION_STOP_FAILURES: 'true'
              FILE_EXISTS_BEHAVIOR: 'OVERWRITE'

definitions:
  services:
    docker:
      memory: 3072
``


text:
Q: Can you use 'less' or 'more' to output one page worth of text? So in Linux, less is used to read files page by page for better readability. I was wondering if you can do something like less file.txt > output.txt to get one page worth of file.txt and output/write it to `output.txt.
Apparently, this does not work, output.txt is exactly the same as the original file, I'm wondering why this is the case, and if there are other work-arounds. Thank you!

A: You can use the split command.
split -l 100 -d -a 3 input output

This will split the input file every 100 lines (-l 100), will use numbers as suffixes (-d) and will use 3 numbers as suffix (-a 3) in the output file. Something like this output000, output001, output002

A: You can use head to get a specific number of lines, and tput lines to see how many lines there are on your current terminal.
Here's a script that fetches a pageful, or the standard 25 lines if no terminal is available:
#!/bin/bash
lines=$(tput lines) || lines=25
head -n "$lines" file.txt > output.txt

A: we use head and tail to get n lines of top or bottom part of a file
cat /var/log/messages|tail -n20

head -n10 src/main.h


text:
Q: When using a restrict Pointer in C, is it OK to change a variable using its initial Identifier? When using a restrict Pointer in C, is it OK to change the variable using its initial Identifier?  For example:
int foo = 0;

int * restrict fooPtr = &foo;
++(*fooPtr);                   // Part 1: foo is 1 (OK)

++foo;                         // Part 2: foo is 2 (Is this OK?)

int * fooPtr2 = &foo;
++(*fooPtr2);                  // Part 3: foo is 3 (BAD: You shouldn't access via a second pointer)

...I changed the value of foo through foo after the restrict fooPtr was created.
Part 1 looks OK to me. I'm confused about Part 2. And from what I understand about restrict, Part 3 is bad (compiler allows it, but its behavior is undefined, and it's up to the programmer not to do that).

A: No, Part 2 is not OK.
The specific part of the standard is 6.7.3.1/4. This section is pretty dense, and takes a few re-reads, but P is a restrict pointer, and X is some object it is used to access, and which is modified. So in your example P is fooPtr and X is foo. Then:

Every other lvalue used to access the
  value of X shall also have its address
  based on P.

"based on" is defined in the previous paragraph, and to summarize, the lvalue foo does not have its address based on the restrict pointer P. So the rule is broken when you access the object foo through its own name.
Part 3 is not OK for exactly the same reason, the lvalue *fooPtr2 isn't based on P either, but is also used to access X.
I say "not OK" - to be precise, the combination of 1+2 provokes undefined behavior, as does the combination of 1+3. As long as you don't actually access the object through the restrict pointer, none of the definition of restrict "kicks in". If you wanted to you could remove Part 1, retain the unused restrict pointer, and then 2 and 3 would be OK.

A: Yes, "part 3" is undefined behaviour.  From the C99 spec (6.7.3, paragraph 7):

An object that is accessed through a
  restrict-qualified pointer has a
  special association with that pointer.
  This association, defined in 6.7.3.1
  below, requires that all accesses to
  that object use, directly or
  indirectly, the value of that
  particular pointer.

A: I'd say #2 is bad.  For instance, the compiler might optimize by loading the value at *fooPtr into a register, and then write that register value back out to foo again later - after your ++foo, so that the ++foo is lost.

A: Assuming that all of the parts of your question occur in the same block, it's not OK to access the value of foo directly (part 2) nor to access it via another pointer (part 3):

*

*6.7.3.1 Formal definition of restrict

Every other lvalue used to access the value of X shall also have its address based on P.

The formal definition of restrict is quite difficult to follow (at least it is for me), however the following less formal description also from the standard sums it up pretty well (at least for this case):

An object that is accessed through a restrict-qualified pointer has a special association
  with that pointer. This association, defined in 6.7.3.1 below, requires that all accesses to that object use, directly or indirectly, the value of that particular pointer.


text:
Q: Java support for json testing? I am using morphia (ODM for mongodb) in my project and write its annotations on my models.
I want to write unit tests to validate the mapping.
I can call the mapper, using morphia.getMapper().toDBObject(input) and run a test on the output.
For example, for the model
Car:
@Property("COLOR")
String color;
@Property("PlaTE")
int plate;
@Property("seats")
int seats;

I expect to receive the output:
{ "COLOR" : "value", "PlaTE" : 111, "seats" : 4 }

In order to test it, I need to create a string that represent this output, and in java it's a nightmare...
String expected = "{ \"COLOR\": \"value\", \"PlaTE\": 111, \"seats\" }";

And you can see how ugly this can get with embedded objects and arrays...
I was thinking of writing the output in a json file and read it during the test, but it kinda breaks the rules of unit testing...
Is there any convenient way of representing json objects in java to achieve a neat and clean unit tests?

A: If you're looking for a way to test your RESTful endpoints (JSON or XML), I would recommend http://rest-assured.io/ I've used it in a number of projects and it's great. They have excellent documentation too: https://github.com/rest-assured/rest-assured/wiki/Usage