Spring-hibernate mapping problem

Question: I have a spring-hibernate application which is failing to map an object properly: basically I have 2 domain objects, a Post and a User.  The semantics are that every Post has 1 corresponding User.
The Post domain object looks roughly as follows:
class Post {

  private int pId;
  private String attribute;
  ...
  private User user;

  //getters and setters here

}

As you can see, Post contains a reference to User. When I load a Post object, I want to corresponding User object to be loaded (lazily - only when its needed).
My mapping looks as follows:
<class name="com...Post" table="post">
    <id name="pId" column="PostId" />
    <property name="attribute" column="Attribute" type="java.lang.String" />

    <one-to-one name="User" fetch="join"
        class="com...User"></one-to-one>
</class>

And of course I have a basic mapping for User set up.
As far as my table schema is concerned, I have a table called post with a foreign UserId which links to the user table.
I thought this setup should work, BUT when I load a page that forces the lazy loading of the User object, I notice the following Hiberate query being generated:
Select ... from post this_ left outer join user user2_ on this.PostId=user2_.UserId ...

Obviously this is wrong: it should be joining UserId from post with UserId from user, but instead its incorrectly joining PostId from post (its primary key) with UserId from user.
Any ideas?  Thanks!
Update:
Thanks to a couple of the posts below I now realize that I should have been using a many-to-one mapping instead of a one-to-one.  I changed the mapping under post to the following:
<many-to-one name="User" class="com...User" column="uId"/>

But now I get a run-time error telling me that there is no attribute called uId.  This makes sense since I do not have a uId column in my post domain object (I simply have a reference to a user object).  Now I am really confused as to how I can get Hibernate to realize that it needs to map the foreign key from the post table to the user table.  Should explicitly add a uId attribute to my post domain object to be a placeholder for the foreign key?
I hope I am making sense...
Answer: Since a user has many posts, your association is in fact a "many-to-one", not a "one-to-one". It should work if you map it accordingly.
Edit: Yes, you can map the property Post.user on the Post with a "many-to-one", or the set User.posts in User with a "one-to-many", or both. Have you specified the name of your foreign key column?
Edit2: In Hibernate speak, a "column" in the database is mapped to a "property" in your Java-Class. That is, the column attribute contains the name of your foreign key column in the database, not the name of any property in your Java class. If I read your question right, you should use "UserId", not "uId".
Oh, and a fetch="join" can not be lazy, as it mandates that the user is fetched in the same query as the post.
Comment: Thanks, but is it correct to place this mapping in the "post" mapping?  I tried this with similar incorrect results.  I am not sure how to get it to join on UserId from the Post table since my domain objects don't have any notion of a foreign key, just a reference to a User object.
Comment: Thanks for your update, can you please elaborate what you mean by "have you specified the name of your foreign key column?", as I suspect that this could be my problem?
Comment: Thank you!!! I have wasted so much time on this...as you probably guessed I am new to hibernate...
Answer: That is the behaviour of a one-to-one mapping. They usually share a primary key. Hibernate is assuming that the primary key of post is teh same as the primary key of user. This page summarizes this behaviour.
I suspect that one user can actually have more than one posts though. That makes your mapping a one-to-many.
Comment: You are right about a user having more than 1 post.  I am just confused as to where to place this mapping: under the mapping for Post or under the mapping for User?

Spring-hibernate mapping problem


How to install Anaconda on RaspBerry Pi 3 Model B

Question: I would like to know how to install the latest Anaconda version from Continuum on my Raspberry Pi 3 model B. Any help would be appreciated...
Comment: As of today - the support is quite bad, you'll get Python 3.4 at most and the available packages are also limited (e.g.: current jupyter requires at least 3.5). While on a PC Anaconda is a good way to get an 'up-to-date' python with rich repositories, it's not so great for RPi. It's easier to update to `stretch` for Python 3.5 or even `buster` for 3.7.
Comment: check berryconda
Answer: Installing Miniconda on Raspberry Pi and adding Python 3.5 / 3.6
Skip the first section if you have already installed Miniconda successfully.
Installation of Miniconda on Raspberry Pi
wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
sudo md5sum Miniconda3-latest-Linux-armv7l.sh
sudo /bin/bash Miniconda3-latest-Linux-armv7l.sh

Accept the license agreement with yes
When asked, change the install location: /home/pi/miniconda3
Do you wish the installer to prepend the Miniconda3 install location
to PATH in your /root/.bashrc ? yes
Now add the install path to the PATH variable:
sudo nano /home/pi/.bashrc

Go to the end of the file .bashrc and add the following line:
export PATH="/home/pi/miniconda3/bin:$PATH"

Save the file and exit.
To test if the installation was successful, open a new terminal and enter
conda

If you see a list with commands you are ready to go.
But how can you use Python versions greater than 3.4 ?

Adding Python 3.5 / 3.6 to Miniconda on Raspberry Pi
After the installation of Miniconda I could not yet install Python versions higher than Python 3.4, but i needed Python 3.5. Here is the solution which worked for me on my Raspberry Pi 4:
First i added the Berryconda package manager by jjhelmus (kind of an up-to-date version of the armv7l version of Miniconda):
conda config --add channels rpi

Only now I was able to install Python 3.5 or 3.6 without the need for compiling it myself:
conda install python=3.5
conda install python=3.6

Afterwards I was able to create environments with the added Python version, e.g. with Python 3.5:
conda create --name py35 python=3.5

The new environment "py35" can now be activated:
source activate py35

Using Python 3.7 on Raspberry Pi
Currently Jonathan Helmus, who is the developer of berryconda, is working on adding Python 3.7 support, if you want to see if there is an update or if you want to support him, have a look at this pull request. (update 20200623) berryconda is now inactive, This project is no longer active, no recipe will be updated and no packages will be added to the rpi channel.
If you need to run Python 3.7 on your Pi right now, you can do so without Miniconda. Check if you are running the latest version of Raspbian OS called Buster. Buster ships with Python 3.7 preinstalled (source), so simply run your program with the following command:
Python3.7 app-that-needs-python37.py

I hope this solution will work for you too!
Comment: @paul-strobel thanks for this well detailed answer. I faced a problem on my rpi and conda wasn't able to install packages for a ownership conflict, you may wish to add this to your answer, this will solve the problem `sudo chown -R pi: miniconda3` source: https://askubuntu.com/a/726196/673947
Also if you wish to add how to install `RPi.GPIO` then it would be the best tutorial on conda for raspberry
Comment: Note: berryconda as of early 2020 is no longer active https://github.com/jjhelmus/berryconda
Comment: I tried many times but after the third line and after wrote 'yes' it shows a bunch of  'y' after that nothing. I cannot write anything.
Comment: @ProtimaRaniPaul can you specify your problem further? Which version of Python are you installing, where exactly do you get stuck etc.?
Comment: @PaulStrobel As I said I did exactly given above, After the first three lines of code (before Path Variable Addition.) It asked me to input 'yes' it shows 'y' one after another in a new line then it goes totally blank.  I can see nothing in the terminal. I am using Respbian 10. Thank you so much for your comment.
Comment: anyone else having trouble with this? seem to be in dependency hell where i can't update conda b/c python is too low and i can't update to python 3.5 or 3.6 b/c conda is too low. anytime i try to install the above it just breaks my miniconda :(
Comment: Hi, I am tried this on my Raspberry Pi 4 Model B running running the Rasbian OS. After I follow the steps above and type conda, I get "-bash: conda: command not found". Does anybody know how to fix this?
Answer: On Raspberry Pi 3 Model B - Installation of Miniconda (bundled with Python 3)
Go and get the latest version of miniconda for Raspberry Pi - made for armv7l processor and bundled with Python 3 (eg.: uname -m)
wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
md5sum Miniconda3-latest-Linux-armv7l.sh
bash Miniconda3-latest-Linux-armv7l.sh

After installation, source your updated .bashrc file with source ~/.bashrc. Then enter the command python --version, which should give you:
Python 3.4.3 :: Continuum Analytics, Inc.

Comment: For now, I replaced NOOBS (based on Debian 8 Raspbian) with ArchLinux ARM mostly because of the unparalleled high quality of its documentation. This has also given me access to Python 3.5 along with various other up-to-date packages, as ArchLinux is very prompt in upgrading its repositories when the upstream releases newer package versions. I suggest this as a potential stop-gap solution until Miniconda has a little more love for armv7l systems.
Comment: Is there any reason why you use `sudo`? Better practice and more convenient to use not to use `sudo` to install.
Comment: Hi @mahtuag the newest version It's not available on the repo(https://repo.continuum.io/miniconda/) for the Raspberry Pi Model 3 Processor ARMv7. It's like you said, really unfortunate.
Comment: I followed this but I missed the step about changing the default installation directory.  Is that a big problem?  I updated .bashrc with `export PATH="/root/miniconda3/bin:$PATH"` and rebooted but I still get `bash: conda: command not found`.  What should I do?
Comment: Just tried this - followed steps exactly, (on a raspberry pi zero w) and the conda command just returns "Illegal instruction" for anything I attempt to do with conda (even `conda --version` or just plain `conda`). Any advice?
Comment: What if I wanted to install it for all users, not just `pi`?
Comment: Still works well for me as of June 2018. I recommend not using sudo and it also seems that the installer automatically adds miniconda to your PATH.
Comment: Why can't I use conda to install anything, it always has `Fetching package metadata: ....
Error: No packages found in current linux-armv7l channels matching: xxxx`
Comment: I tried many times but after the third line and after wrote 'yes' it shows a bunch of  'y' after that nothing. I cannot write anything.
Answer: If you're interested in generalizing to different architectures, you could also run the command above and substitute uname -m in with backticks like so:
wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-`uname -m`.sh

Answer: I was trying to run this on a pi zero. Turns out the pi zero has an armv6l architecture so the above won't work for pi zero or pi one. Alternatively here I learned that miniconda doesn't have a recent version of miniconda. Instead I used the same instructions posted here to install berryconda3
Conda is now working. Hope this helps those of you interested in running conda on the pi zero!
Comment: Yes, you need to always check your machine archtecture. At time of this comment, this page: https://repo.continuum.io/miniconda/ contains only miniconda 3.5.5 with Py2. This makes root environment by Py2, but doesn't preclude installing other versions.


Fill the actual data with duplicated data and remove duplicated data

Question: I have the following data:-
library(data.table)
data <- data <- data.table(address = c("AA", "BB", "AA", "CC", "DD", "EE", "DD"),
                   revenue = c(NA, 121, 22, 33, 44, 33, NA),
                   castord = c(21, 22, NA, 3, NA, 223, 33),
                   versaze = c(NA, 22, 124, 33, NA, 44, 43))
data

#    address revenue castord versaze
# 1:      AA      NA      21      NA
# 2:      BB     121      22      22
# 3:      AA      22      NA     124
# 4:      CC      33       3      33
# 5:      DD      44      NA      NA
# 6:      EE      33     223      44
# 7:      DD      NA      33      43

Now this data has AA and DD addresses duplicated. And their first occurrence has some NA data as you can see in the row 1 and 5. What I want to do is fill this data by using the duplicated rows of these addresses. If the duplicated row has NA values, then NA shouldn't replace the values in the row of first occurrence. This will give me the following data:-
    data <- data.table(address = c("AA", "BB", "AA", "CC", "DD", "EE", "DD"),
                   revenue = c(22, 121, 22, 33, 44, 33, NA),
                   castord = c(21, 22, NA, 3, 33, 223, 33),
                   versaze = c(124, 22, 124, 33, 43, 44, 43))

#    address revenue castord versaze
# 1:      AA      22      21     124
# 2:      BB     121      22      22
# 3:      AA      22      NA     124
# 4:      CC      33       3      33
# 5:      DD      44      33      43
# 6:      EE      33     223      44
# 7:      DD      NA      33      43

And then remove those duplicated rows:-
data <- data.table(address = c("AA", "BB", "CC", "DD", "EE"),
                   revenue = c(22, 121, 33, 44, 33),
                   castord = c(21, 22, 3, 33, 223),
                   versaze = c(124, 22, 33, 43, 44))

#    address revenue castord versaze
# 1:      AA      22      21     124
# 2:      BB     121      22      22
# 3:      CC      33       3      33
# 4:      DD      44      33      43
# 5:      EE      33     223      44

Answer: Using data.table, group by address, loop through columns, remove NAs, get the first value:
data[, lapply(.SD, function(i) (na.omit(i)[ 1 ])), by = address]
#    address revenue castord versaze
# 1:      AA      22      21     124
# 2:      BB     121      22      22
# 3:      CC      33       3      33
# 4:      DD      44      33      43
# 5:      EE      33     223      44

Answer: If you use dplyr::group_by and summarise where you take the first value that is not NA using na.omit, it fills out the empty values for you if the first row is NA.
data <- data %>% group_by(address) %>%
  summarise(
    revenue = first(na.omit(revenue)),
    castord = first(na.omit(castord)),
    versaze = first(na.omit(versaze))
    )

Comment: Is there a `data.table` way to do this?
Comment: Not that I know of and nothing I could skim in their documentation. Why is it a problem to use dplyr/tidyverse?
Comment: Actually the real table I have is very large around 900 mb and I wanted to use `data.table` to keep it as memory efficient as possible.


Plugin chartjs-plugin-crosshair does not work

Question: I'm trying to use the chartjs-plugin-crosshair and it doesn't work for me.
I have following packages:

"chart.js": "^3.9.1"
"chartjs-plugin-crosshair": "^1.2.0"

It seems that the import of the library is not done correctly and therefore it does not take the settings of the chartjs-plugin-crosshair.
Code
In Angular
import { Component } from '@angular/core';
import ChartStreaming from 'chartjs-plugin-streaming';
import zoomPlugin from 'chartjs-plugin-zoom';
import annotationPlugin from 'chartjs-plugin-annotation';
import 'chartjs-adapter-moment';
import 'hammerjs';
import Chart from 'chart.js/auto';

import * as CrosshairPlugin from 'chartjs-plugin-crosshair';
Chart.register(CrosshairPlugin);
Chart.register(ChartStreaming, zoomPlugin, annotationPlugin);

const ctx = (<HTMLCanvasElement>document.getElementById('MyChart')).getContext('2d');
    this.chart = new Chart(ctx!, {
      type: 'line',
      data: {
        labels: this.labels,
        datasets: [
          {
            label: 'Series 1',
            data: this.Serie1,
            backgroundColor: [
              colors.color1,
            ],
            borderColor: [
              colors.color1,
            ],
            borderWidth: 1,
            xAxisID: 'y_axis_1',
            pointRadius: 0,
          },
          {
            label: 'Series 2',
            data: this.Serie2,
            backgroundColor: [
              colors.color2,
            ],
            borderColor: [
              colors.color2,
            ],
            borderWidth: 1,
            xAxisID: 'y_axis_2',
            pointRadius: 0,
          },
        ],
      },
      options: {
        maintainAspectRatio: false,
        indexAxis: 'y',
        scales: {
          yAxes: {
            ticks: {
            },
            reverse: true,
            type: 'realtime',
            //Cada 30 segundos
            time: {
              //1/2 minuto
              unit: 'minute',
              displayFormats: {
                minute: 'HH:mm:ss',
              },
            },
            realtime: {
              frameRate: 60,
              duration: 30000,
              refresh: 2000,
              delay: 4000,
              //ttl: 8640000000000,
              ttl: 86400000,
              onRefresh: chart => {
                let chartTime: any = new Date();
                let url = 'http://localhost:3000/';
                fetch(url)
                  .then(response => response.json())
                  .then(Data => {
                    this.chart.data.labels.push(chartTime);
                    this.chart.data.datasets[0].data.push(Data.data1);
                    this.chart.data.datasets[1].data.push(Data.data2);
                    this.chart.data.datasets[2].data.push(Data.data3);
                    chart.update('quiet');
                  })
                  .catch(error => console.log(error));
              },
            },
          },
          y_axis_1: {
            grid: {
              lineWidth: 1,
              tickWidth: 1,
            },
            position: 'top',
            min: 0,
            max: 4000,
            ticks: {
              color: colors.color1,
            },
            title: {
              display: true,
              text: 'Y Axis 1',
              color: colors.color1,
            },

          },
          y_axis_2: {
            grid: {
              lineWidth: 1,
            },
            position: 'top',
            min: 0,
            max: 300,
            ticks: {
              color: colors.color2,
            },
            title: {
              display: true,
              text: 'Y Axis 2',
              color: colors.color2,
            }
          },
        },
        plugins: {

          // crosshair: {
          //   line: {
          //     color: "#d1d1d1",
          //     width: 1,
          //   },
          // },
          annotation: {
            annotations: {
              line1: {
                type: 'line',
                scaleID: 'y_axis_1',
                value: 3500,
                borderColor: colors.black,
                borderWidth: 2,
                label: {
                  backgroundColor: colors.color1,
                  content: '2000',
                  display: true,
                  position: 'start',
                  yAdjust: 50,
                  rotation: 'auto',
                  font: {
                    size: 12,
                  }
                }
              },
              line2: {
                type: 'line',
                scaleID: 'y_axis_2',
                value: 250,
                borderColor: colors.black,
                borderWidth: 2,
                label: {
                  backgroundColor: colors.color2,
                  content: '2000',
                  display: true,
                  position: 'start',
                  //yAdjust: -60,
                  rotation: 'auto',
                  font: {
                    size: 12,
                  }
                }
              },
            }
          },
          tooltip: {
            //usePointStyle: true,
            mode: 'nearest',
            intersect: false,
          },
          title: {
            display: true,
            text: 'Realtime Chart'
          },
          legend: {
            position: 'bottom',
          },
          zoom: {
            pan: {
              // pan options and/or events
              enabled: true,
              mode: 'y',
              modifierKey: 'ctrl',
            },
            zoom: {
              // zoom options and/or events
              onZoomComplete: function ({ chart }) {
                console.log(`I was zoomed!!!`);
              },
              mode: 'y',
              wheel: {
                enabled: true,
                speed: 0.1
              },
              drag: {
                enabled: true,
              },
              pinch: {
                enabled: true
              },
            }
          },
        },
      },
      plugins: []
    });

I have to synchronize four graphs like this and I have not found the solution.
Comment: Do you get any errors during build or runtime (IDE or browser console)? Please add the output. Also, how did you install both packages, using a package-manager ?
Answer: Basically to fix it you have to create a file named index.d.ts and add this:
declare module 'chartjs-plugin-crosshair';

Learn more about this solution here


Get checked status on click event in angular Material

Question: I have a angular element
<mat-checkbox class="btn-block"
              labelPosition="before"
              (change)="showOptions($event)"
              (click)="makeJSON($event.checked,i,j,k)">
</mat-checkbox>

Here onchange(which actually gives the status of checkout) is doing some other task and I want the status of checkbox(either checked or unchecked) on click event.
I already tried looking over the object created by click and it does not have click object inside, so how can I detect if the checkbox is checked or not.
Comment: @Apoorv did Gunter's answer solve your problem? If so, please accept it. If not, please edit your question to state why you don't feel that it solves your problem. An important part of using this site is to accept answers that solves your problem. The reason for this is twofold: 1) it tells us that your question is resolved and doesn't require further answers. 2) it helps future readers with the same question be directed to a useful answer.
Answer: You can use
(change)="showOptions($event)"
(change)="makeJSON($event.checked,i,j,k)">

or
(change)="showOptions($event);makeJSON($event.checked,i,j,k)">

Answer: With your (change)="showOptions($event)" you can simply get the status like this:
showOptions(event:MatCheckboxChange): void {
    console.log(event.checked);
}

Answer: Another solution can be, You can use template reference variable with checkbox and pass that variable to method parameter.
 <mat-checkbox #checkbox (change)='showOptions(checkbox.checked)' value=''>all</mat-checkbox>

Here #checkbox reference hold all checkbox related properties(like value, checked etc.).
checkbox.checked this will give current state of checkbox with true and false.
Comment: This works and IMO is more concise than the most upvoted solution
Answer: Yes you can get the checked event using change function
(change)="showOptions($event);
In Ts
showOptions(event){
 console.log(event.checked); //true or false
}

When Checkbox is false not checked
When Checkbox is true then its checked
Answer: whTax =false;
<mat-checkbox color="primary"
                      name="whTax" [checked]="false"
                      [(ngModel)]="whTax" id="IsHold"
                      (change)="onWHChange(whTax)">
                        W/H TAX
                  </mat-checkbox>
    onWHChange(isWhChecked){
      console.log('isWhChecked:>>', isWhChecked);
    }


Adplus fullonfirst for a specific exception?

Question: A colleague is trying to track down a race condition, leading to an InvalidOperationException. I suggested adplus with fullonfirst, but it turns out that a third party library throws and catches all manner of exceptions under the hood. Is there any way if restricting to a managed exception type?
Answer: This old bugslayer post describes how to configure Adplus to create mini dumps on specific exceptions.
Comment: Thanks, couldn't find that anywhere!


Trying to add two matrices with numbers entered as a string and then display solution, but trouble with stdin and stdout

Question: It's a programming task to enter two matrices using stdin and then display the result in stdout. I often found runtime error or no stdin or stdout to display while the program is running good.
This is my code for addition of two matrices.
<code>       """The constraint is the numbers will be entered only without any
          string to be seen on console and also that to be in the same
          fashion being each number input separated by a white space."""
          import sys

            def main():

            num1 = []
            num2 = []

            rc1 = raw_input().split(' ')
            rc1_arr = [int(z) for z in rc1]
            r1 = rc1_arr[0]
            c1 = rc1_arr[1]
            while(r1 != 0):
                    mat1 = raw_input().split(' ')
                    arr1 = [int(z1) for z1 in mat1]
                    num1.append(arr1)
                    r1=r1-1

            rc2 = raw_input().split(' ')
            rc2_arr = [int(z) for z in rc2]
            r2 = rc2_arr[0]
            c2 = rc2_arr[1]
            while(r2 != 0):
                    mat2 = raw_input().split(' ')
                    arr2 = [int(z2) for z2 in mat2]
                    num2.append(arr2)
                    r2=r2-1

            for i in range(max(rc1_arr[0],rc2_arr[0])):
                 for j in range(max(rc1_arr[1],rc2_arr[1])):
                     su = num1[i][j]+num2[i][j]
                     sys.stdout.write(str(su))
                     sys.stdout.write(" ")
                 sys.stdout.write("\n")

        main()

       """ while running in idle it looks like this
       ##The input part is:
       3 3         ## represents no. of rows and columns
       1 2 3       ## This is the matrix 1 of 3*3
       4 5 6
       7 8 9
       3 3         ## represents no. of rows and columns for second matrix
       1 1 1       ## This is the matrix 2 of 3*3
       1 1 1
       1 1 1
       ## And the output is like:
       2 3 4       ## Sum of the above two matrices.
       5 6 7
       8 9 10
       """
</code>
Please help.
Comment: Can you please specify the input and output that you want.
Comment: @Ezio I have added some comment lines to show for the input and output to look into it...
Comment: Your program seem to work fine when the number of rows and columns of both the matrices are same. If the number of rows and columns of the two matrices differs then it will fail.
Comment: Yes the code is working fine but i need to give the input and output in stdin and stdout so that online interpreter will provide me some results... Also if you have identified the problem with unequal no. of rows and columns, will you please suggest a trick to remove it...
Comment: Declare two arrays of same number of rows and columns.
Number of rows = max(rc1_arr[0],rc2_arr[0])
Number of columns = max(rc1_arr[1],rc2_arr[1]).
Initialize both the arrays with 0 and then take entries with the user and fill the corresponding cells.The cells which does not get any entries will contain 0 and hence the addition remains the same.
Comment: @Ezio I found my error in the last second for loop where I am giving unnecessary space after the last element of first row... And now my program is running smoothly... Thanks for your help... :)
Answer: You could have some problem with the indentation... I did not touch a line (other than adjust the indentation and it work as expected!)
<code>#!/usr/bin/env pyhton2
import sys

def main():

    num1 = []
    num2 = []

    rc1 = raw_input().split(' ')
    rc1_arr = [int(z) for z in rc1]
    r1 = rc1_arr[0]
    c1 = rc1_arr[1]
    while(r1 != 0):
        mat1 = raw_input().split(' ')
        arr1 = [int(z1) for z1 in mat1]
        num1.append(arr1)
        r1=r1-1

    rc2 = raw_input().split(' ')
    rc2_arr = [int(z) for z in rc2]
    r2 = rc2_arr[0]
    c2 = rc2_arr[1]
    while(r2 != 0):
        mat2 = raw_input().split(' ')
        arr2 = [int(z2) for z2 in mat2]
        num2.append(arr2)
        r2=r2-1

    for i in range(max(rc1_arr[0],rc2_arr[0])):
        for j in range(max(rc1_arr[1],rc2_arr[1])):
            su = num1[i][j]+num2[i][j]
            sys.stdout.write(str(su))
            sys.stdout.write(" ")
        sys.stdout.write("\n")

main()
</code>
Comment: I knew that the code is running fine but I want the inputs by stdin and outputs in stdout. This is the real task. Even the IDEONE online interpreter is not producing results with this...
Comment: What do you mean with stdin and stdout then? Do you mean redirection from a file (stuff.py < input.txt)? Your code is working reading on stdin and writing on stdout...


What's meant by the number of "distinct $C^k$ differential structures" other than the amount of distinct maximal atlases?

Question: When reading the Wiki page on differential structures, I'm struck by the exceptional case of $R = 4$.
However, the definition of differential structure leaves me nonplussed, as it seems to just be another name for "maximal atlas" in the context of https://i.stack.imgur.com/MBce6.png, which says: "There is an "essentially unique" smooth structure for any topological manifold of dimension smaller than 4."
When they say "smooth structure" do they simply mean a unique maximal atlas (C-infinity) or is there more to it?
Thanks so much for helping with the clarification.
Answer: You are on the right track, but not quite there yet.
First, a smooth structure is indeed nothing more than a maximal $C^\infty$ atlas.
However, to say that the smooth structure is "essentially unique" does not mean that there exists a unique maximal $C^\infty$ atlas. Such a strong uniqueness property is always false: for any smooth manifold $M$ there exists a non-smooth homeomorphism $h : M \to M$, and using $h$ you can then define a different maximal $C^\infty$ atlas by transport of structure, which means replacing your given atlas $\{\phi_i : U_i \to \mathbb R^m\}$ with the new atlas $\{\phi_i \circ h^{-1} : h(U_i) \to \mathbb R^m \}$. For example, even the standard structure on $\mathbb R$ can be changed by transport of structure using the non-smooth homeomorphism $h(x) = \sqrt[3]{x}$.
Instead, for the smooth structure to be "essentially unique" usually means that it is unique up to transport of structure: for any two maximal $C^\infty$ atlases $\{\phi_i : U_i \to \mathbb R^m\}$ and $\{\psi_j : V_j \to \mathbb R^m\}$ there exists a homeomorphism $h : M \to M$, and a bijection between the index sets, such that if $i \leftrightarrow j$ correspond under that bijection then $V_j = h(U_i)$ and $\psi_j = \phi_i \circ h^{-1}$. This, of course, is equivalent to the statement that $h$ is a diffeomorphism from the structure $\{\phi_i : U_ \to \mathbb R^m\}$ to the structure $\{\psi_j : V_j \to \mathbb R^m\}$.
Comment: Thank you. Then would the following statement be correct?: "Define two $C^\inf$ atlases to be equivalent if there exists a diffeomorphism between them. Then for $R = 1$, there's only one $C^\inf$ atlas (up to a diffeo) on any given manifold, and for $R = 4$ the amount of $C^\inf$ atlases (up to a diffeo) is uncountable."
Answer: Yes, a $C^k$ (/differential/smooth) structure on a manifold $M$ is exactly a maximal atlas $\mathscr{A}$ with all transition functions of class $C^k$.
A caveat: Exotic $C^k$ structures on a manifold $M$ are not merely maximal atlases which are not the same. One typically says that two $C^k$ structures (i.e. atlases) $\mathscr{A}$ and $\mathscr{A}'$ on $M$ are equivalent (or diffeomorphic) of there is a function $f:M\to M$ such that, with respect to the two structures, $f:(M,\mathscr{A})\to(M,\mathscr{A}')$ is a $C^k$ diffeomorphism.
For instance, $\mathbb{R}^n$ has infinitely many smooth structures, but all of them are equivalent for $n\neq 4$. This is what is meant by "essentially unique" in the linked snippet.


Build .NET Core 2.0 EXE file with C# 7.1

Question: I have a project I'm trying to build. It's using C# 7.1 features, and I can run it via Visual Studio, but when I try to publish to get an .exe file I get the error:
Agent.cs(8,30): error CS8107: Feature 'async main' is not available in C# 7.
Please use language version 7.1 or greater. [C:\Users\stuarts\Documents\Visual
Studio 2017\Projects\Agent\Agent\Agent.csproj]
CSC : error CS5001: Program does not contain a static 'Main' method suitable
for an entry point [C:\Users\stuarts\Documents\Visual Studio
2017\Projects\Agent\Agent\Agent.csproj]

The .csproj (project) file:
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <IsPackable>false</IsPackable>
    <NetStandardImplicitPackageVersion>1.6.1</NetStandardImplicitPackageVersion>
    <RuntimeFrameworkVersion>2.0.0-*</RuntimeFrameworkVersion>
    <RuntimeIdentifier>win10-x64</RuntimeIdentifier>
    <ApplicationIcon />
    <StartupObject />
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <LangVersion>7.1</LangVersion>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="RabbitMQ.Client" Version="5.0.1" />
  </ItemGroup>

</Project>

I'm building with:
dotnet publish -c Release -r win10-x64 Agent.csproj

Again, this all works when debugging in Visual Studio. Why is getting a simple .exe file out of a console application project template so awkward!
Answer: Your problem is that in the section...
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <LangVersion>7.1</LangVersion>
</PropertyGroup>

...you specify to use C# 7.1 in the Debug configuration.
However, with...
dotnet publish -c Release -r win10-x64 Agent.csproj

...you compile in the Release configuration.
You need to set up C# 7.1 in Release, too. You could also remove the condition entirely, which sets up the language version for any configuration.
Comment: @Stuart Is there any particular reason to set this separately for Debug and for  Release? It could also be set in the first `PropertyGroup` section for all configurations.
Comment: Thank you for this!
Comment: @Stuart: My pleasure.
Comment: @ZevSpitz You are right, there is absolutely no reason to specify the condition.
Comment: @ZevSpitz: I have edited the answer. It now includes the option to remove the condition.
Comment: Excellent, I'm surprised actually that the 7.1 feature isn't a global property by default from VS. Thanks for this answer.


How can I capture the Powershell informational console output to a variable?

Question: I can't seem to figure out how to capture the quoted text below for parsing. I've tried setting it to a variable as well as redirecting all streams with *>&1 . How can I grab the output text? The *>&1 works for errors, but not for the text below for some reason? Writing to a file is not an option.
Connect-Mailbox -Identity $guidT -user $targetDNT -Alias $aliasT -Database $databaseT -DomainController $domainSpecificDCsSourceAccountT[0]

I've also tried
$outValue = Connect-Mailbox -Identity $guidT -user $targetDNT -Alias $aliasT -Database $databaseT -DomainController $domainSpecificDCsSourceAccountT[0] *>&1

WARNING: The operation completed successfully but the change will not
  become effective until Active Directory replication occurs.

[edit]
For repro, this command appears to fall into the same situation, and is easier to setup/configure
$var = Set-Mailbox $sourceUserT -LitigationHoldEnabled $false

[edit2]
Some commands like set-mailbox will work if you change the type from a string to an array such as but connect-mailbox is not able to use that?
So this was kind of dumb luck, it works for the set-mailbox command but not the connect-mailbox command?
PS> Set-Mailbox "first.last" -LitigationHoldEnabled $false -WarningVariable wv
    WARNING: The command completed successfully but no settings of 'xxx/last, first' have been modified.

PS> $wv

PS>

However when it did it this way
[System.Collections.ArrayList]$wvar = @();
Set-Mailbox "onprem.detailee1" -LitigationHoldEnabled $false -WarningVariable +wvar
WARNING: The command completed successfully but no settings of 'xxxx/last, first' have been modified.

PS> write-host $wvar
The command completed successfully but no settings of 'xxxx/last, first' have been modified.

So Powershell cannot cast some outputs (warning, error, etc) to a string, however they can add the object to an array. Strangely enough the non-typing portion of the Powershell language is not applicable here.
Answer: You should be able to use the -WarningVariable Common Parameter to capture messages destined for the warning stream.
Connect-Mailbox -Identity $guidT -user $targetDNT -Alias $aliasT -Database $databaseT -DomainController $domainSpecificDCsSourceAccountT[0] -WarningVariable WarningVar

$WarningVar

The common parameters include variable options for messages sent to the error, information, and warning streams.
Comment: Hi, I agree but that was tried and it does not work for this command? I believe it may be an object typing issue?

    PS C:\Users\xx\Documents>
    PS C:\Users\xx\Documents> Connect-Mailbox -Identity $guidT -user $targetDNT -Alias $aliasT -Database $databaseT -DomainController $domainSpecificDCsSourceAccountT[0] -WarningVariable WarningVar
    WARNING: The operation completed successfully but the change will not become effective until Active Directory replication occurs.
    PS C:\Users\xx\Documents> $warningvar

    PS C:\Users\xx\Documents>
Comment: Maybe it is doing two writes with the second write being empty string. Then it wipes out the variable if the append `+` is not applied.
Comment: Possibly, that would make sense. I can't get either to work with the connect-mailbox command. Do you have any ideas?
Comment: The command behavior does seem bizarre. I've had some good results with calling the code within a script block: `$var = & {Connect-Mailbox ...} *>&1`
Comment: @AdminOfThings, I think the issue is buggy stream behavior when _implicit remoting_ is involved - see my answer.
Answer: One way I found to do this was to set erroraction explicitly to stop (-ea stop) for the cmdlet in a try catch statement, then I could get the exception value with $_.Exception.Message in the catch statement as it forces the cmdlet to have a terminating error.
This is something I've found to be frustrating coming from c# where a try/catch statement works without having to explicitly define an error as terminating or not. If you do not do that for some cmdlets, the try/catch will not work and it will never catch the terminating error.
Hopefully this helps others, more info
https://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell
Comment: FYI: You can get c# like behaviour by setting `$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop` early in your script.  Alternatively you can use `if(-not $?){Write-Warning "An error occurred: '$($Error[0].Exception.Message)'"}`.  Hope that's of some help. See also: https://stackoverflow.com/questions/6834487/what-is-the-dollar-question-mark-variable-in-shell-scripting and  https://stackoverflow.com/a/17461657/361842
Answer:
The problem most likely stems from buggy behavior with respect to streams from implicitly remoting commands, such as created via Import-PSSession; GitHub issue #9585 is presumably related.
You have already found one workaround, as demonstrated in your question: if you explicitly create the target variable to pass to -WarningVariable as a System.Collections.ArrayList instance and pass the variable name prefixed with + (-WarningVariable +var) - normally intended for appending to a preexisting variable value - capturing the warning(s) is possible.
A slightly simpler workaround is to call the command via Invoke-Command and apply -WarningVariable to the latter:
Invoke-Command -WarningVariable warnings {
  Connect-Mailbox -Identity $guidT -user $targetDNT -Alias $aliasT -Database $databaseT -DomainController $domainSpecificDCsSourceAccountT[0]
}

# $warnings now contains any warnings emitted by the command.

Answer: Did you try the following?
$var = myCommand | out-string

Comment: Yes, $var is empty that way
Comment: This would only capture _success_ output, and would convert it to a single, multi-line string.


can I play the same game but on two different play disks on xbox 360

Question: I'm not sure how to say this but I used a friend of mine's grand theft auto v and I installed it and everything but I'm going to buy my own grand theft auto v soon but I would like to know if I can use my play disk to continue my story mode or do I need my friend's disk?
Answer: Nothing is tied to the specific game disc on either the PS3 or Xbox 360 as far as I'm aware. You didn't specify which system. You could start a game on a Redbox rental for instance, and then continue it on a purchased game. As long as you have the save game data still, it should work.


Allow libertine apps full access to sd card on Ubuntu Touch

Question: I would like to use libertine apps to read epub and cbz files on my SD Card. How can I enable access for these apps so that they can navigate to the proper folders?
Answer: You can bind your SD card into your libertine-container by creating a directory (e.g. called 'mount') into the ~/.local/share/libertine-container/user-data/CONTAINERID/ and execute the command: sudo mount -B /media/phablet/YOURSDCARD/ ~/.local/share/libertine-container/user-data/CONTAINERID/mount/ and you have access to your SD card in libertine from the container's home directory. Of course you can bind your SD card anywhere else in you libertine-container :)


Does calling window.close() terminate the session from IIS also?

Question: I want to know that when we call window.close then does this also terminate the session on IIS?
I am writing below code and I am trying to terminate the session of the user from IIS.
  Sub OnClickLogout()
      dim Answer, msg
      Msg = "This will terminate the session and close the browser. Do you want to continue?"
      Answer = MsgBox(Msg, vbYesNo + vbCritical, "Error")
      if Answer = vbYes then
          window.close() ' Does this terminate the sesion of the user also?
      else
         'Return to the previous page
      End if
  End Sub

If no then please tell me how can I accomplish it.
Answer: Closing the browser does not terminate the session. You can check this by adding Global.asax file to your project and get grip to session end event.
   void Session_End(object sender, EventArgs e)
   {
   }

More about session events can be found here:
http://msdn.microsoft.com/en-us/library/ms178583(v=vs.100).aspx
To terminate the session you should call:
        Page.Session.Clear();
        Page.Session.Abandon();


what's the purpose of variable val in this algo

Question: it's an algo from internet about Red-Black BST Java implementation. I am confused about the variable named val in this program. Here is the code:
package tools;
public class redBlack2 {
    private static final boolean RED   = true;
    private static final boolean BLACK = false;
    private Node root;
    public redBlack2() {}
    private class Node {
        private int key;
        private int val;
        private Node left, right;
        private boolean color;
        public Node(int key, int val, boolean color) {
            this.key = key;
            this.val = val;
            this.color = color;
        }
    }
    private boolean isRed(Node x) {
        if (x == null) return false;
        return x.color == RED;
    }
    public int get(int key) {
        return get(root, key);
    }
    private int get(Node x, int key) {
        while (x != null) {
            if      (key < x.key) x = x.left;
            else if (key > x.key) x = x.right;
            else              return x.val;
        }
        System.out.println("There is no such key.");
        return 0;
    }
    public boolean contains(int key) {
        return get(key) != 0;
    }
    public void put(int key, int val) {
        root = put(root, key, val);
        root.color = BLACK;
    }
    private Node put(Node h, int key, int val) {
        if (h == null) return new Node(key, val, RED);
        if      (key<h.key) h.left  = put(h.left,  key, val);
        else if (key>h.key) h.right = put(h.right, key, val);
        else if (key == h.key)  h.val   = val;
        if (isRed(h.right) && !isRed(h.left))      h = rotateLeft(h);
        if (isRed(h.left)  &&  isRed(h.left.left)) h = rotateRight(h);
        if (isRed(h.left)  &&  isRed(h.right))     flipColors(h);
        return h;
    }
    private Node rotateRight(Node h) {
        Node x = h.left;
        h.left = x.right;
        x.right = h;
        x.color = x.right.color;
        x.right.color = RED;
        return x;
    }
    private Node rotateLeft(Node h) {
        Node x = h.right;
        h.right = x.left;
        x.left = h;
        x.color = x.left.color;
        x.left.color = RED;
        return x;
    }
    private void flipColors(Node h) {
        h.color = !h.color;
        h.left.color = !h.left.color;
        h.right.color = !h.right.color;
    }
    public static void main(String[] args) {
        redBlack2 r = new redBlack2();
        r.put(34,1);
        r.put(23,2);
        r.put(65,3);
        r.put(73, 4);
        System.out.print(r.get(73));
    }
}

is that just a mark we give to the number we put inside the Tree? then don't we already have key as a mark? why we still need variable val?
Comment: Suppose someone gives you a dictionary you've never seen before.  You decide to look up a word.  When you find the word, the dictionary doesn't tell you anything about it--no pronunciation, no definition, no anything, just the word.  You don't know any more than you did before (except that you know the word is in the dictionary, which is a little bit, but not much).  Wouldn't it be more useful to have a dictionary that provides more information along with the word?  Does that help explain what `val` is for?
Comment: `val` stores the value given in call to `put(int key, int val)` and later returned by `get(int key)`. Why do you believe the value of `key` is the same as the value of `val`? If you simply follow the code to see where the value comes from and where it is used, the answer is just that.
Comment: Similarly, Java provides both `Set` and `Map` collections.  A `Set` can look up a key and tell you whether the key is in the set, but it can't tell you anything more.  A `Map` allows you to provide additional data associated with the key.  Does that help explain?
Answer: Yes, you're right, it's just like a mark. We can indeed implement this algorithm with just one variable, i.e., key. In this algo, val is something that is being stored as a type of data for which we need to keep track.
For example consider this

You have several numbered boxes like 34, 23, 65, 73 and you want to
  implement RB Tree operations on them. So these number on boxes
  resembles the key in your algorithm.
Now consider each box contains a number of balls in it. These balls
  can be seen as a data which is stored inside the box and you need to
  keep a track of it. So this can be considered as val.

You can even go a step further and keep a track of several things that are inside a box by changing the data-type of val to List or Map or even user-defined objects. It will still work the same way.
Answer: In this implementation, this data structure acts like a Map, which means it maps keys to values. That val is a common abbreivation of value, which is quite self-explainatory. It could be of any type existing in Java, be it primitive or reference.


Can I repair Damaged Mods?

Question: I sometimes get mod drops that say they're damaged. Is there any way to repair them? Should I bother levelling them? Or is this just the game's way of indicating quality? (I so far am just ignoring damaged mods in favour of ones that aren't damaged, but if I can make these useful to me, I'd like to.)
Answer: You can't repair damaged mods.  Instead, you have to find the normal versions of these mods elsewhere in the solar system.
Damaged mods are generally weaker than their non-damaged counterparts, plus they also have less upgrades available.
If you're looking for a specific mod, its drop locations may be listed in the in-game Codex.  It's also a good idea to check the Warframe Wiki.
Comment: On a side note, of the damaged mods you receive by completing quests/junctions, the only one I still have yet to replace with a non-damaged mod is Equilibrium... because it only drops from a specific boss with a fairly low drop chance (~7.5%).  Which was also bad luck on my part because I fought said boss at least 8 times while farming for Nekros warframe parts.

Can I repair Damaged Mods?


Computing the convolution of $f(x)=\gamma1_{(\alpha,\alpha+\beta)}(x)$

Question: If I have a top hat function
$$
f(x)=\begin{cases}
    \gamma       & \quad \text{if } \alpha<x<\alpha+\beta\\
    0  & \quad \text{otherwise }
  \end{cases}
$$
and I convolute it with itself:
$$
f*f(x)=\int^{\alpha+\beta}_{\alpha}\gamma f(x-t)\ dt
$$
I know the solution is a triangle function but how do I solve this integral?
Comment: @GuyFsone I am not the OP
Comment: @JohnDoe sorry I did  not notice
Comment: what is gamma here
Comment: @GuyFsone a constant
Comment: then what is your problem this looks obvious
Answer: Answer:
$$f*f(x)=\begin{cases}
    \gamma^2(\beta- |x-2\alpha-\beta|)      & \quad \text{if } |x-2\alpha-\beta|< \beta\\
    0  & \quad \text{if } |x-2\alpha-\beta|\ge \beta
  \end{cases}$$
see the details below
-----------------------------------------------------------------------------

Let $x\in \Bbb R$ for $t\in (\alpha,\alpha+\beta)$ we have
  $$x-t\in [\alpha,\alpha+\beta]\Longleftrightarrow t\in [x-\alpha-\beta,x-\alpha]$$

  Therefore, we have
  $$t, x-t\in [\alpha,\alpha+\beta]\Longleftrightarrow \color{red}{t\in[\max(\alpha,x-\alpha-\beta), \min(x-\alpha,\alpha+\beta)] \\\Longleftrightarrow |x-2\alpha-\beta|< \beta } $$

In fact, observes that
$$ \min(x-\alpha,\alpha+\beta) =\min(x,2\alpha+\beta)-\alpha~~~~$$and$$~~~\max(\alpha,x-\alpha-\beta)=\max(x, 2\alpha+\beta)-\alpha-\beta$$

Hence, if $x\in \Bbb R$ is such that $$\max(\alpha,x-\alpha-\beta)< \min(x-\alpha,\alpha+\beta) \\\Longleftrightarrow \max(x, 2\alpha+\beta)-\beta< \min(x, 2\alpha+\beta) \\\Longleftrightarrow |x-2\alpha-\beta|=\max(x, 2\alpha+\beta)-\min(x, 2\alpha+\beta)< \beta \\\Longleftrightarrow |x-2\alpha-\beta|< \beta $$

then $$f*f(x)=\int_{\Bbb R} f(t)f(x-t)\ dt =\int^{\alpha+\beta}_{\alpha}\gamma f(x-t)\ dt \\=\int^{\min(x-\alpha,\alpha+\beta)}_{\max(\alpha,x-\alpha-\beta)}\gamma f(x-t)\ dt \\=\int^{\min(x-\alpha,\alpha+\beta)}_{\max(\alpha,x-\alpha-\beta)}\gamma^2 dt \\=\color{red}{\gamma^2 \min(x-\alpha,\alpha+\beta) -\gamma^2 \max(\alpha,x-\alpha-\beta)\\=\gamma^2(\beta- \max(x, 2\alpha+\beta)+\min(x, 2\alpha+\beta)) \\=\gamma^2(\beta- |x-2\alpha-\beta|)}$$
otherwise  if $x\in \Bbb R$ is such that $$\max(\alpha,x-\alpha-\beta)\ge\min(x-\alpha,\alpha+\beta)$$ then $$f*f(x) =0$$


exporting gridview to Ms Excel 2007

Question: I am trying to export grid view data into excel 2007 i.e. xlsx format. but its giving error.
i am using following code
protected void Button1_Click(object sender, EventArgs e)
<code>    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=text.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.DataSource = Presenter.CurrentModel.BillStatementGlModelRecords;
        GridView1.DataBind();
        GridView1.AllowPaging = false;

        GridView1.DataBind();
        GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");

        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            //Change Color back to white
            row.BackColor = System.Drawing.Color.White;
            //Apply text style to each Row
            row.Attributes.Add("class", "textmode");
        }
        GridView1.RenderControl(hw);
        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
</code>
but not working properly and on opening the file it gives following error
"Excel cannot open the file 'ChangeRequestList[2].xlsx' because the file
format or file extension is not valid. Verify that the file has not been
corrupted and that the file extension matches the format of the file"
Can anyone help me?
Thanks
Comment: Please edit the code properly. Thanks
Comment: Can you open the sheet in Excel without any error? Is yes, please verify if there is any application (read) locking your file.
Comment: Make sure you're using "Microsoft Excel 12.0 Object library" COM component in project's reference.
Comment: yes i am using "Microsoft Excel 12.0 Object library" COM component in project's reference. but still the error is same
Answer: Have a look at this Code - I already used it and it's working.
But it produces plain text (csv I guess) and not xlsx but I think that shouldn't be a problem though.

exporting gridview to Ms Excel 2007


Embedded C Programming - IF statement not working properly

Question: The code below is not working. In this program, if I press Swich1 (PORTK PK1 pin of Arduino Mega), and then if I press Switch2, LED 0 to 3 (which are connected at pins 0 to 3 of port F of Arduino Mega) should blink one by one for each pressing of switch. If I press SW2 switch two times, then while pressing SW1 switch, led 4 to 7 should blink one by one. But the first case is working, whereas the second case is not working.
void setup() {

  DDRF =0xFF;
  DDRK = 0x00;
  volatile long i,j,m;
  j=0;
  m=0;
  while (1)
  {
    if ((PINK & 0x02) == 0x02)
    //for(i=0; i<1000; i++) ;
    {
      j=1;
      if (j/2) {
        if ((PINK & 0x01) == 0x01) {
          m++;
          for(i=0; i<50000; i++)
            ;
        }
        if (m==1)
          PORTF =0x01;
        else if(m==2)
          PORTF=0x02;
        else if(m==3)
          PORTF=0x04;
        else if (m==4) {
          PORTF = 0x08;
          m=0;
        }
      }

      if (j%2) {
        if ((PINK & 0x01) == 0x01)
        // for(i=0; i<20000; i++) ;
        {
          m++;
          for (i=0; i<50000; i++)
            ;
        }
        if (m==1)
          PORTF =0x01;
        else if (m==2)
          PORTF=0x02;
        else if (m==3)
          PORTF=0x04;
        else if (m==4) {
          PORTF = 0x08;
          m=0;
        }
      }
    }
  }
}

void loop() {
  // put your main code here, to run repeatedly:
}

Comment: Four close braces on a single line is an indication of gross layout problems in your code.  It is unreadable, and that line alone makes it very hard to see what is going on.  Please use a more orthodox layout style to (dramatically) improve the readability of your code.  See Wikipedia on [Indentation styles](https://en.wikipedia.org/wiki/Indentation_style).  I use Allman style; many people prefer 1TBS (One True Brace Style).
Comment: With `if (j/2)` you mean `if (j > 1)`?  As you set `j=1` that `if` condition is never true.  Also, I suggest you reduce code duplication.  Those two if statements have identical bodies.
Comment: Is there any reason why all your  code is in `setup` function while function `loop` is empty?
Comment: You check if PINK's bit 2 is set, then immediate check if bit 1 is set to run the delay loop.  Is there a state change between those two statements?  It's the only way m would be set to something besides the initial `m = 0`.
Comment: You are supposed to respond to questions and requests from comments. Providing readable code will greately improve the chance to attract people willing to help.
Comment: `//for(i=0; i<1000; i++) ;` Commenting code like you do is dangerous. Commenting and uncommenting changes your program flow because it makes the next block after this line either part of the `if` or not. You should urgently put these statements into the block that is part of the `if` and not before it.
Comment: "But the first case is working, whereas the second case is not working." There are no 2 cases in your code. Same thing twice. Remember: Writing readable code is vital also for you.
Comment: How are you debouncing the switch? These kind of questions about switches without any signal debouncing mentioned are very tiresome. Debouncing is typically mentioned in the first couple of beginner classes in embedded programming. TL;DR: if you have no hardware RC filter on this switch, then this program is hopelessly broken and cannot be salvaged.
Comment: You should be aware that Arduino "sketches" are C++, not C.  Your code breaks the sketch framework.  The body of the `while(1)` loop in `setup()` should be in `loop()` without the `while`.  The framework calls `loop()` repeatedly.  That said if you are not going to use the Arduino library for I/O, why use Arduino Sketch at all rather than straight C (or C++)?
Comment: The biggest problem with Arduino is lack of a debugger in most platforms.  You might consider testing and debugging in Tinkercad for example - it simulates the hardware with virtual breadboards and you can step and debug your code.  (Not sure if it simulates switch bounce though).  Your code could stand some simple improvements.  For example consider how many lines could be replaced with `PORTF = 1u << (m - 1) ;`
Comment: The Arduino library has a delay function.  Your busy loops are flawed and may be optimised out.  That said you should avoid delays in Arduino Sketch framework.  It is better to implement `loop()` as a state-machine and poll `millis()` or `micros()` to determine if it is time to change state or perform some action.
Comment: On Arduino Mega, PK1 is nominally analogue input A9.  Not an obvious choice for a digital input, but it can be used as a GPIO by `pinMode( A9, INPUT )`  / `digitalRead( A9 )`; the advantage then being that the code is portable across all Arduino boards rather then being MegaAVR specific.
Answer: The if statement works exactly how you would expect - the block is executed it the Boolean expression if true, otherwise it does not.  You have integer expressions, a non-zero integer expression evaluated as Boolean is true, while zero is false.
Here:
  j=1;
  if (j/2) {  // <<<< ALWAYS FALSE (1/2 == 0)

while here:
  if (j%2) {  // ALWAYS TRUE (1%2 == 1)

The point being that you assign 1 to j but never modify it.  The initialisation to zero is never used before j is ever tested - it is always 1 when tested.
It is not clear what you intended, but clearly j needs to be modified conditionally depending on the switch states.
That is in any case the answer to your question, but the code itself is not "Arduino-friendly".  In the Arduino framework you would normally:

Use the Arduino library for I/O
Perform only initialisation in setup()
Do the iterative work in loop()
Allow the framework to do the iteration rather then having an indefinite loop.
Have the iterative work non-blocking (no busy-wait delays) so that background work can be done.

In this case I would separate the switch detection from both each other and the LED control and use the Arduino I/O.  For example:
static const int SW1 = A9 ;
static const int SW2 = A9 ;
static const size_t LED_COUNT = 4u ;
static const int LEDS[2][LED_COUNT] = { { A0, A1, A2, A3 },
                                        { A4, A5, A6, A7 } } ;
void setup()
{
  // Switch inputs
  pinMode( SW1, INPUT ) ;
  pinMode( SW2, INPUT ) ;

  // LED outputs
  for( size_t i = 0; i < LED_COUNT; i++ )
  {
    pinMode( LEDS[0][i], OUTPUT ) ;
    pinMode( LEDS[1][i], OUTPUT ) ;
    digitalWrite( LEDS[0][i], 0 ) ;
    digitalWrite( LEDS[1][i], 0 ) ;
  }
}

void loop()
{
  static unsigned long led_time = millis() ;
  static unsigned long sw1_time = millis() ;
  static unsigned long sw2_time = millis() ;
  static const int DEBOUNCE_MILLIS = 20 ;
  static const int LED_MILLIS = 500 ;
  static bool previous_sw1_state = digitalRead( SW1 ) != 0 ;
  static bool previous_sw2_state = digitalRead( SW2 ) != 0 ;
  static size_t current_led = LED_COUNT ;
  static size_t current_group = 0 ;

  unsigned long now = millis() ;

  // If SW1 state changed (with debounce)...
  bool sw1_state = digitalRead( SW1 ) != 0 ;
  if( now - sw1_time > DEBOUNCE_MILLIS &&
      sw1_state != previous_sw1_state )
  {
    sw1_time = now ;
    previous_sw1_state = sw1_state ;

    // If SW1 pressed and LED cycle not running...
    if( sw1_state && current_led > LED_COUNT)
    {
       // Start LED cycle
       current_led = 0 ;
    }
  }

  // If SW2 state changed (with debounce)...
  bool sw2_state = digitalRead( SW2 ) != 0 ;
  if( now - sw2_time > DEBOUNCE_MILLIS &&
      sw2_state != previous_sw2_state )
  {
    sw2_time = now ;
    previous_sw2_state = sw2_state ;

    // If SW2 pressed and LED cycle not running...
    if( sw2_state && current_led > LED_COUNT )
    {
       // Switch group
       current_group = current_group == 0 ? 1 : 0 ;
    }
  }

  // If LED cycle in progress, and time to switch LED...
  if( current_led <= LED_COUNT &&
      now - led_time > LED_MILLIS  )
  {
    led_time = now ;

    // Previous LED off
    if( current_led > 0 )
    {
      digitalWrite( LEDS[current_group][current_led - 1], 0 ) ;
    }

    // Current LED on
    if( current_led < LED_COUNT )
    {
      digitalWrite( LEDS[current_group][current_led], 1 ) ;
    }

    // Next LED
    current_led++ ;
  }
}

Note that there are no busy-wait delays.  That allows you to do other work in the loop() without affecting the timing significantly.
SW1 starts the sequence, and SW2 toggles which group of LEDs the sequence runs on when you next press SW1
Comment: @IyyappanChithambarathanu you are welcome, and welcome to SO, but appreciation of an answer is better shown by up-voting and/or marking an answer as accepted.  Messages of thanks are unnecessary and explicitly discouraged.
Comment: Tested at https://www.tinkercad.com/things/7PvfzuZeCej on Uno with modified I/O.


Ubuntu 20.04 very slow, sometime hanging

Question: Recently, I install Ubuntu in my computer. My configuration is the following:

Intel® Core™ i7-10700 CPU @ 2.90GHz × 16
Mesa Intel® UHD Graphics 630 (CML GT2)
SSD: 500
RAM: 16GB

But my computer seems very slow when I open Activities, or run a Java process in InteliJ, or Java in Android, or when I run yarn start or something else. I don't know why. My computer sometime hangs. I captured some screenshots of my process.
Please help me resolve the problem, or help me speed up my computer. I think about reinstall Hackintosh, because I am more familiar with MacOS than Ubuntu.
Some images that might be useful:
Comment: No, you don't increase swap to 16G. Edit your question and show me `free -h` and `sysctl vm.swappiness` and `grep -i swap /etc/fstab`. Also show me `sudo dmidecode -s bios-version` and tell me the EXACT make/model # of your computer or motherboard. Start comments to me with @heynnema or I'll miss them.
Comment: System "freezes" are often caused by running too many, too large programs and running out of available memory. Use `free` to see if you have swap space, read `man mkswap swapon fstab` to create some. Traditionally, swap space of 1.5 × RAM has been recommended,  but YMMV. If you don't plan to hibernate your system, you can have less than 1.0 × RAM.
Comment: Thanks @waltinator. default my swap 2GB, but I'm check only  free 100MB, you mean I must increase swap RAM to 16GB or more
Comment: Also show me `top`.
Comment: @heynnema. If you see screenshot above.
Comment: @heynnema: - grep -i swap /etc/fstab: 0, bios version: 1401. My Bios: Asus EX-B460M-V5.
Comment: That's not the `top` command. This is Ubuntu, correct?
Comment: @heynnema. Yes, this is Ubuntu. I screenshots system monitor, it's same top command.
Comment: Show me `free -h` and `sysctl vm.swappiness` and `sudo blkid` and `cat /etc/fstab`... but EDIT that output into your question please. Give me the "regular" `top` command.
Comment: Also show me `sudo lshw -C memory`.
Comment: @heynnema. I edit my question. Please review it.
Answer: BIOS
Asus EX-B460M-V5
You have BIOS 1401. There's a newer BIOS available, version 1604, dated 3/16/21, and can be downloaded here.
RAM
You may need more RAM. Add another one of these...

SWAP
We'll increase your 2G /swapfile to 4G, and revisit the performance metrics.

We'll currently leave your vm.swappiness at 60.
Note: Incorrect use of the rm and dd commands can cause data loss. Suggest copy/paste.
In the terminal...
sudo swapoff -a           # turn off swap
sudo rm -i /swapfile      # remove old /swapfile

sudo dd if=/dev/zero of=/swapfile bs=1M count=4096

sudo chmod 600 /swapfile  # set proper file protections
sudo mkswap /swapfile     # init /swapfile
sudo swapon /swapfile     # turn on swap
free -h                   # confirm 16G RAM and 4G swap

Edit /etc/fstab, using sudo -H gedit /etc/fstab or sudo pico /etc/fstab.
Confirm this /swapfile line in /etc/fstab... and confirm no other "swap" lines... use SPACES in this line... confirm NO TABS...
/swapfile  none  swap  sw  0  0

reboot                    # reboot and verify operation

Comment: RAM: I think 16GB enough for my need. SWAP: ok I try, and let you know.
Answer: What increased my performance slightly on various setups is turning off the "animations" in Tweaks. Worth trying.

Also looking at your Swap I'd definitely increase it. (to about the size of your RAM at least) Even though it may not be related to your current issue your swap is awfully low and may cause other issues later on. (source: https://itsfoss.com/swap-size/)

To increase swap:
sudo swapoff -a
Resize
sudo dd if=/dev/zero of=/swapfile bs=1G count=8
Permissions
sudo chmod 600 /swapfile
Make usable
sudo mkswap /swapfile
sudo swapon /swapfile

Edit /etc/fstab and add the new swapfile if it isn't already there (based on suggestion from @heynnema )
/swapfile none swap sw 0 0
Check the amount of swap available
grep SwapTotal /proc/meminfo
Comment: Fair enough. AU is a good place for this kind of dialog, like we had. It's also a good place for new contributors to learn from more senior contributors :-)
Comment: No, you don't increase swap to *"about the size of your RAM at least"*. And you assumed a /swapfile, and didn't delete the original one. What if they have a swap partition? And you forgot to check/add the /swapfile line in /etc/fstab.
Comment: You don't need to delete anything when changing size instead of creating a new swapfile from scratch. (https://bogdancornianu.com/change-swap-size-in-ubuntu/) Also the "about the size of your RAM at least" is the most widely shared recommendation as far as I have seen (at least). I mean, given you have the necessary disk space there's only drawbacks in having swap smaller than RAM. Especially if you hibernate. (https://itsfoss.com/swap-size/)
Comment: Yes, I assumed the swap file because because "starting with Ubuntu 17.04, the swap partition was replaced by a swap file. The main advantage of the swap file is easy resizing" (source: https://linuxbsdos.com/2017/04/18/swap-partition-out-swap-file-in-on-ubuntu-17-04/). Assuming a user is using the current and up to date setup is not necessarily wrong. (especially since the OP is running 20.04)
Comment: I've added the `/swapfile none swap sw 0 0` line based on your suggestion
Comment: The added swap size table is nice, but I don't believe the info is current, esp for Ubuntu 20.04. Any /swapfile 3G or less, is too small. And their hibernation numbers are just their RAM + swap. Funny enough, the table matches the 4G swap for 16G RAM that I recommended in my accepted answer.
Comment: I guess we'll disagree then. :)


Temporarily remove the ssh private key password in a shell scriptI

Question: I am required to deploy some files from server A to server B.  I connect to server A via SSH and from there, connect via ssh to server B, using a private key stored on server A, the public key of which resides in server B's authorized_keys file.  The connection from A to B happens within a Bash shell script that resides on server A.
This all works fine, nice and simple, until a security-conscious admin pointed out that my SSH private key stored on server A is not passphrase protected, so that anyone who might conceivably hack into my account on server A would also have access to server B, as well as C, D, E, F, and G.  He has a point, I guess.
He suggests a complicated scenario under which I would add a passphrase, then modify my shell script to add a a line at the beginning in which I would call
ssh-keygen -p -f {private key file}

answer the prompt for my old passphrase with the passphrase and the (two) prompts for my new passphrasw with just return which gets rid of the passphrase, and then at the end, after my scp command
calling
ssh-keygen -p -f {private key file}

again, to put the passphrase back
To which I say "Yecch!".
Well I can improve that a little by first reading the passphrase ONCE in the script with
read -s PASS_PHRASE

then supplying it as needed using the -N and -P parameters of ssh-keygen.
It's almost usable, but I hate interactive prompts in shell scripts.  I'd like to get this down to one interactive prompt, but the part that's killing me is the part where I have to press enter twice to get rid of the passphrase
This works from the command line:
ssh-keygen -p -f {private key file} -P {pass phrase} -N ''

but not from the shell script.  There, it seems I must remove the -N parameter and accept the need to type two returns.
That is the best I am able to do.  Can anyone improve this?  Or is there a better way to handle this?  I can't believe there isn't.
Best would be some way of handling this securely without ever having to type in the passphrase but that may be asking too much. I would settle for once per script invocation.
Here is a simplified version the whole script in skeleton form
#! /bin/sh
KEYFILE=$HOME/.ssh/id_dsa
PASSPHRASE=''

unset_passphrase() {
        # params
        # oldpassword keyfile
        echo "unset_key_password()"
        cmd="ssh-keygen -p -P $1 -N '' -f $2"
        echo "$cmd"
        $cmd
        echo
}

reset_passphrase() {
        # params
        # oldpassword keyfile
        echo "reset_key_password()"
        cmd="ssh-keygen -p -N '$1' -f $2"
        echo "$cmd"
        $cmd
        echo
}

echo "Enter passphrase:"
read -s PASSPHRASE
unset_passphrase $PASSPHRASE $KEYFILE
# do something with ssh
reset_passphrase $PASSPHRASE $KEYFILE

Answer: Check out ssh-agent. It caches the passphrase so you can use the keyfile during a certain period regardless of how many sessions you have.
Here are more details about ssh-agent.
Answer: OpenSSH supports what's called a "control master" mode, where you can connect once, leave it running in the background, and then have other ssh instances (including scp, rsync, git, etc.) reuse that existing connection.  This makes it possible to only type the password once (when setting up the control master) but execute multiple ssh commands to the same destination.
Search for ControlMaster in man ssh_config for details.
Advantages over ssh-agent:

You don't have to remember to run ssh-agent
You don't have to generate an ssh public/private key pair, which is important if the script will be run by many users (most people don't understand ssh keys, so getting a large group of people to generate them is a tiring exercise)
Depending on how it is configured, ssh-agent might time out your keys part-way through the script; this won't
Only one TCP session is started, so it is much faster if you're connecting over and over again (e.g., copying many small files one at a time)

Example usage (forgive Stack Overflow's broken syntax highlighting):
REMOTE_HOST=server

log() { printf '%s\n' "$*"; }
error() { log "ERROR: $*" >&2; }
fatal() { error "$*"; exit 1; }
try() { "$@" || fatal "'$@' failed"; }

controlmaster_start() {
    CONTROLPATH=/tmp/$(basename "$0").$$.%l_%h_%p_%r
    # same as CONTROLPATH but with special characters (quotes,
    # spaces) escaped in a way that rsync understands
    CONTROLPATH_E=$(
        printf '%s\n' "${CONTROLPATH}" |
        sed -e 's/'\''/"'\''"/g' -e 's/"/'\''"'\''/g' -e 's/ /" "/g'
    )
    log "Starting ssh control master..."
    ssh -f -M -N -S "${CONTROLPATH}" "${REMOTE_HOST}" \
        || fatal "couldn't start ssh control master"
    # automatically close the control master at exit, even if
    # killed or interrupted with ctrl-c
    trap 'controlmaster_stop' 0
    trap 'exit 1' HUP INT QUIT TERM
}

controlmaster_stop() {
    log "Closing ssh control master..."
    ssh -O exit -S "${CONTROLPATH}" "${REMOTE_HOST}" >/dev/null \
        || fatal "couldn't close ssh control master"
}

controlmaster_start
try ssh -S "${CONTROLPATH}" "${REMOTE_HOST}" some_command
try scp -o ControlPath="${CONTROLPATH}" \
    some_file "${REMOTE_HOST}":some_path
try rsync -e "ssh -S ${CONTROLPATH_E}" -avz \
    some_dir "${REMOTE_HOST}":some_path

# the control master will automatically close once the script exits

Comment: Thanks, what's the difference between doing this and going through ssh-agent, which provided me with a similar one-time entry of passphrase?
Comment: @Steve:  Updated the answer to include the advantages over `ssh-agent`
Answer: I could point out an alternative solution for this. Instead of having the key stored on server A I would keep the key locally. Now I would create a local port forward to server B on port 4000.
ssh -L 4000:B:22 usernam@A

And then in a new terminal connect through the tunnel to server B.
ssh -p 4000 -i key_copied_from_a user_on_b@localhost

I don't know how feasible this is to you though.
Answer: Building up commands as a string is tricky, as you've discovered. Much more robust to use arrays:
cmd=( ssh-keygen -p -P "$1" -N "" -f "$2" )
echo "${cmd[@]}"
"${cmd[@]}"

Or even use the positional parameters
passphrase="$1"
keyfile="$2"
set -- ssh-keygen -p -P "$passphrase" -N "" -f "$keyfile"
echo "$@"
"$@"

The empty argument won't be echoed surrounded by quotes, but it's there
Comment: Arrays are bash-specific---they won't work in a POSIX shell (`/bin/sh`).  The only ways to build up a command in a whitespace-safe and POSIX-compliant manner are via positional parameters (as you suggest) or escaping special characters and using `eval`.
Comment: @Richard, true but the question does have a `bash` tag.
Comment: Glenn: yes, even though ssh-agent looks like a total solution to my problem, there is still the nagging issue of why entering
`ssh-keygen -p -P $1 -N '' -f $2`
on the command line succeeds but running the same from within a bash script does not.


What type of subfloor should be used for on grade for nail down engineered hardwood?

Question: I am ripping up tiles on the ground floor of my home and would like to install 1/2 inch engineered hardwood. It is over a concrete slab on grade. What is the best and most economical way to do this once the tiles are removed and the concrete is cleaned and leveled?
-Can I float a plywood subfloor and then nail the hardwood to it? If so should I leave expansion gaps between the plywood and the walls? I have seen this suggested on other forums but doesn't seems to make sense to me. Shouldn't the subfloor be screwed down if the flooring is to be nailed to it?
-Or should I secure the subfloor to the concrete and then nail the wood flooring to that? What is the best way to go about doing this?
-A modular subfloor like Dricore seems great but expensive and maybe overkill for an on grade floor?
What is the best recommendation for this type of project? What subfloor should I use, how should it be installed, where should the vapor barrier be placed and what is the best way to secure the engineered hardwood flooring to the subfloor?
Comment: What's wrong with the tiles?
Answer: If you're not wedded to a nail-down install, the best route to go with here is a floating floor with nothing but a soft underlayment between the flooring and the slab. This is an accepted install method for engineered hardwood over a slab, and your flooring manufacturer/seller should be able to provide you with instructions for how to do it and not void the warranty.
As for vapor barriers, you only need to worry about that if your concrete slab doesn't already have a vapor barrier underneath it. Obviously there's no way to easily check, but if the slab was poured in the last 20 or 25 years, there's a very good chance it already has one. In any event, once the current flooring is off, you should have a calcium chloride moisture test performed on the slab. Where you live matters, too. I live in the desert, so soil moisture is a non-issue here, and my slab's lack of a vapor barrier underneath it is irrelevant. If you're in the pacific northwest, it's a different story.
If the moisture test shows that you need a vapor barrier, choose a closed-cell foam underlayment, not something water-sensitive like cork.
Comment: You don't need to build a floating subfloor. It would be a waste of time and money. Install your flooring over the slab with foam underlayment between them, and glue the boards together, applying glue to the grooves. Leave a 1/4" gap between the boards and the walls, and undercut the door frames. Just follow the manufacturer's instructions, really.
Comment: I've been told that floating floors can be problematic with heavy furniture, cabinets or appliances on top of them. I will be installing about 900 sq feet in a mostly open floor plan. Would a floating floor installation be ok over that sq footage or would I have problems with spaces opening up or buckling? Is it possible to nail down the flooring to the floating subfloor? Or is that not recomended? Thanks!
Comment: I don't understand that claim. The underlayment will be like 1/32" thick; it's not going to sag, especially if the flooring is a glue-together tongue-and-groove type. The planks will basically be held together as one solid very rigid mass. And remember that you're going to be holding it down at the edges with baseboards.
Comment: So you would recommend both a floating subfloor and floating engineered flooring with the flooring glued together? The flooring I have is 1/2 inch engineered tongue and groove. It says it can be nailed, glued or floated. Would you recommend any underlayment between the subfloor and the floated flooring?
Comment: Wouldn't a hardwood direct over concrete get cold in the winter? I was thinking that a subfloor would keep the temperature of the floor closer to that of the room in general and if any small amount of water  does seep into the floor from the outdoors the subfloor would prevent the planks from coming in direct contact with the water. What do you think? Still a waste of time? Should I just go with the foam and then the engineered hardwood? I live in New York so the weather gets pretty cold but is not overly humid like the pacific northwest. Thank you for all your advice.
Comment: Any hard floor will get cold in the winter if the concrete slab is not insulated. Preventing a hard flooring material installed over concrete from being cold in the winter is a whole other kettle of fish; open a new question for that. But to answer your question, simply laying a plywood subfloor underneath the engineered hardwood will do very little to keep the floor warmer. It will help a small amount, but likely not enough to notice. I'll add more in your new question.


Difference between brightness and lightness in Image Manipulation

Question: I have an application to adjust the lightness/brightness of the image and the saturation and i found this link here which uses android colormatrix to adjust the brightness. Here's the function to adjust brightness in colormatrix.
<code>public static void adjustBrightness(ColorMatrix cm, float value) {
value = cleanValue(value,50);
if (value == 0) {
    return;
}

float[] mat = new float[]
{
    1,0,0,0,value,
    0,1,0,0,value,
    0,0,1,0,value,
    0,0,0,1,0
};
cm.postConcat(new ColorMatrix(mat));
</code>
}
But i don't know if there's a difference with lightness in brightness. Because in GIMP software there is lightness and brightness. See the screenshot below. If there's another method to adjust lightness/brigthness saturation at the same time I would be happy to see it :).

Comment: What you improperly call `Lightness` is the `Luminance` and it's a component in the **HSL** color space (as opposed to the **RGB** color space). http://www.larry-bolch.com/shade/hsl.htm
Comment: Wow @FrankN.Stein nice link. It really explains what Lightness is, I like the link because it provides the easy picture of what is Lightness is. :). Thanks man.
Comment: Archive link for the page linked above, which has since gone offline: https://web.archive.org/web/20181010163341/http://www.larry-bolch.com:80/shade/hsl.htm
Answer: Brightness is visual perception related with reflecting or radiating of lights of different frequencies. On the otherhand lightness is TONE which moves from Darkest color to lightest color of same color Gamma is nothing but an attribute to handle luminescence Means how bright should be the image be (it's more a mathematical calculation rather definition.
In non technical words we can say
Lightness seems to more affect the saturation of the photograph, whereas brightness seems to affect how vivid the colors look.
If you want to go in deep for the proof of concepts, please follow this
http://www.sciencedirect.com/science/article/pii/S0042698910004578
Comment: Hi @Awadesh, thanks man. I think i got it but i would like to visit the link you provided :). You are quick.


Facing problem in solution of non-linear ordinary differential equation.

Question: I am a beginner in Mechanical Engineering research field. Recently I read a paper that contains one non-linear ordinary differential equation. The original author's have not explained anything about how the non-linear ordinary differential equation has been solved.
I request you people to kindly help me by providing solution steps or any link that can help me to find solution of the same.
The equation is:
$\frac{dQ}{dT} + Q^2 - \frac{1}{({\beta}T+1)^2}=0$
and solution of the above equation as suggested by the original authors is:
$Q(t) = \frac{1}{2({\beta}T+1)} \left ( \beta + tanh\left ( \frac{1}{2}.\frac{ln({\beta}T+1)\sqrt{{\beta}^2 + 4}-2.arctanh(-2+{\beta})/\sqrt{{\beta}^2 + 4}.\beta}{\beta} \right ) \sqrt{{\beta}^2 + 4} \right ) $
Comment: It is a [Riccati equation](https://en.wikipedia.org/wiki/Riccati_equation) and it can be reduced to a second order linear equation.
Answer: You have
$$\frac{dQ}{dT}+Q^{2}=\frac{1}{(\beta{T}+1)^{2}}$$
Let
$$Q(T)=\frac{A}{(\beta{T}+1)}$$
Then
$$\frac{dQ}{dT}+Q^{2}=\frac{A^{2}-\beta{A}}{(\beta{T}+1)^{2}}$$
Thus, for the solution, we want $A^{2}-\beta{A}-1=0$, this gives you two particular solutions $Q_{p, 1/2}$. Two more general solution containing a single arbitrary constant each can be obtained by then letting
$$Q_{1/2}=Q_{p, 1/2}+\frac{1}{y_{1/2}}$$
This will give two linear equations for $y_{1/2}$, and they are easy to solve.


Is there a way in saga-redux to know when saga has run completion in 'main file(?)' to update dom?

Question:
I want to do a kind of endless scroll.
When I scroll, I make a call to my API with Saga.
I receive the data in this.props.searchSTT.newWord (which are id + word + timestamp)
When I receive the data I want to create for each word an html element such as :

 {
        this.props.setCurrentstart(word.Dts as number);
    }}
>
    {word.Word}

Curently it is working because I have put a manual delay of 5sec.
I don't want a manual delay because if my API need 6 sec to return the information it crash.
so my files looks like that :
Result.tsx (where I render the dom)
let c = (

 {
      let element = document.getElementById('myscrolldiv') as HTMLElement
      if (!isNull(element)) {
        if (element.offsetHeight + element.scrollTop >= element.scrollHeight) {
          if (isNullOrUndefinedOrEmptyArray(this.props.searchSTT.newWords)) {
            this.props.doSearchByDate({
              medias: this.props.searchSTT.currentMediaID,
              start: new Date(previousEnd - offset),
              end: new Date(previousEnd + offset),
            })
            setTimeout(() => {
              this.updateText()
            }, 5000)
          }
        }
      }
    }}
  >
    {this.props.searchSTT.currentSentence}

)

...
private updateText() {
  let newWords = this.props.searchSTT.newWords
  let sentence = newWords.map(
    (
      word: Proto.media.ISearchSpeechesWord,
      index: number,
      array: Proto.media.ISearchSpeechesWord[]
    ) => {
      return (
         {
            this.props.setCurrentstart(word.Dts as number)
          }}
        >
          {' '}
          {word.Word}{' '}

      )
    }
  )
  this.props.setCurrentsentence(sentence)
}

my current workarround is to have a fixed delay of 5sec before updating the DOM and hope that during those 5sec I had the answer
From what I understand from the code I working with :
this.props.doSearchByDate() is in action.ts
export const searchSpeechesDate = (
  params: ISearchSTTDateParams
): ISearchSpeechesDateAction =>
  action(SearchSTTActionTypes.SEARCH_SPEECHES_DATE, params)

export const setNewwords = (
  newWords: Proto.media.ISearchSpeechesWord[]
): ISetNewwords => action(SearchSTTActionTypes.SET_NEWWORDS, newWords)

Backend.getInstance().Bind(
  'searchSpeechesDateResult',
  (incoming: IFromCommand) => {
    const cmd = incoming as SearchSpeechesDateResult
    const str = store as Store
    const state = str.getState() as IApplicationState

    try {
      str.dispatch(setNewwords(cmd.results))
    } catch (err) {
      Logger.warn(err as string, 'Unable to parse search words result')
    }
  }
)

in saga.ts :
function* handleSearchDate(action: ReturnType<typeof searchSpeechesDate>) {
  const str = store as Store
  const state = str.getState() as IApplicationState
  const cmd = new SearchSpeechDate(
    action.payload.medias,
    action.payload.start,
    action.payload.end
  )
  try {
    yield effects.call(cmd.Send.bind(cmd))
  } catch (err) {
    Logger.warn(err as string, 'Failed to launch search')
  }
}

what I would like is instead of having the :
setTimeout(() => {this.updateText();}, 5000); I would like to have something like: wait until this.props.searchSTT.newWord is not empty (or an error msg)
I have also tried an infite while checking if this.props.searchSTT.newWord is empty but it is not working either
It has been almost 2 weeks and I couldn't find anything that could help me maybe I don't use the correct term for what I'm looking for, but at this point i'm desesperate
Answer: The standard way to update react from sagas is through updating redux store. So the whole process is something like:

Dispatch an action from react to get new data  - doSearchByDate
Listen for the action redux saga, and run some async operation (like fetching stuff from BE) - *handleSearchDate
Once you have the new data, dispatch them through put effect and udpate your redux store state in a reducer - probably whatever cmd.Send.bind(cmd) action does
react-redux then listens on the store to change and updates your react component with new data (either through connect or useSelector hook).

This should work for you as well, though the whole updateText function feels weird (probably since I lack more context). Usually you wouldn't dispatch JSX through an action, but instead you would just directly rerender your component with new props in render method (or inside function component).
If the whole communication gets more complicated you could also include a callback function in your action (from step 1), and then call it once the saga is done with the new data, though that is kinda an anti-pattern, since redux actions are in essence events and you are not guaranteed by the framework that your action gets handled exactly once (but rather it could be 0-n times). In some situations it is a reasonable workaround though.


SagePay Direct - MoTo or CA repeating transactions / token usage

Question: As well as E-Commerce payments, SagePay Direct allows account holders to create payments "over the phone" (with details submitted directly from our server) or using Continuous Authority (with details submitted directly from our server). By the looks of things, the details submitted by our server would be identical apart from the payment type which is set to "C" for Continuous Authority and "M" for MOTO.
I am building a payment gateway and some of our users will have "M" and "C" and some of them will only have "M". In both cases cards can be added (with a token returned) and then a payment can be set up using that returned token. And as long as we tell SagePay that we want to keep using the token we can then submit subsequent payments without the customer present. My confusion is that it LOOKS as though there's nothing stopping the "M"-only users from making subsequent payment requests. Is that the case?
I realise they won't be able to repeat a transaction - but given that all the data is submitted by our website, would we be able to make MoTo payments that are, in effect, repeated use of the card token without interception by the cardholder? Or is there some protection to ensure that this does not happen?
Answer: "would we be able to make MoTo payments that are, in effect, repeated use of the card token without interception by the cardholder"
Yes. As long as you specify accountType=M , and ApplyAVSCV2=2 (to supress the CV2 requirement), you should be fine. Because you aren't handling card data, it would also be OK for you to use the Direct protocol (which is a lot simpler when you don't have the need for the customer to intervene)


What does acpi -t measure?

Question: Whenever I use acpi -t, no matter what I'm doing, the temperature it displays is the same:
Thermal 0: ok, 14.0 degrees C

So to try and figure out why that is, I go to the man page:

acpi  Shows  information from the /proc or the /sys filesystem, such as
  battery status or thermal information.

This isn't that useful to someone like me who doesn't have a terribly in-depth understanding of the Linux kernel and whatnot, and the description of the -t option isn't any better:
   -t |  --thermal
             show thermal information

Can anyone explain what acpi -t is measuring to get it's information?
Answer: ACPI is an acronym for the Advanced Configuration and Power Interface. This interface is intended to be a standard way for the operating system to access information about the computer, including thermal info. The "thermal info" generally reports the temperature of the processor, although some systems may give additional info.
Evidently something between the sensor and the acpi command is not working properly, because the processor temperature should fluctuate with load and conditions.
Another tool is lm-sensors, which uses different interfaces to read other sensor information from the computer.

What does acpi -t measure?


What would a specific example of a simple async/await function be expressed as Promises?

Question: I'm trying to understand the relationship between async/await and Promises in TypeScript and have gotten myself a but too confused, I think.
Im particular, I'm trying to understand how the async/await version of an example function,  downloadFileAA, defined below maps to an implementation that uses Promises instead. What is going in behind the scenes with Promises? Obviously neither of my Promise versions are satisfactory or entirely capture what's going on in the async/await version (downloadFilePromise never reports success or failure, and  downloadFilePromise2 requires some weird redundancy: result.then() in the argument to resolve to pass type checking), but I'm not certain why.
What would a Promise-based version of downloadFileAA look like? Is there a reason to prefer it (or not) over the async/await version?
import * as FileSystem from 'expo-file-system'

const callback = ( downloadProgress ) => {
    const progress = downloadProgress.totalBytesWritten / downloadProgress.totalBytesExpectedToWrite
    console.log(
        `${Number( progress )
            .toLocaleString( undefined, { style: 'percent', minimumFractionDigits: 0 } )
            .padStart( 5, ' ' )} of ${downloadProgress.totalBytesExpectedToWrite} bytes`
    )
}

const downloadResumable = FileSystem.createDownloadResumable(
    'http://...',
    FileSystem.documentDirectory + 'somebigfile',
    {},
    callback
)

const downloadFileAA = async () => {
    try {
        console.log( 'Starting download (with async/await)... ' )
        const result = await downloadResumable.downloadAsync()
        console.log( result ? `Finished downloading to ${result.uri}` : 'Undefined result?'  )
    } catch ( e ) {
        console.error( `Failed download: ${e.message}` )
    }
}

const downloadFilePromise = () => {
        console.log( 'Starting download (with Promise)... ' )
        new Promise<FileSystem.FileSystemDownloadResult>(  ( resolve, reject ) =>
            downloadResumable.downloadAsync()
         )
            .then( ( result ) => console.log( `Finished downloading to ${result.uri}` ) )
            .catch( ( reason ) => console.error( `Failed download: ${reason}` ) )
}

const downloadFilePromise2 = () => {
        console.log( 'Starting download (with Promise Two)... ' )
        new Promise<FileSystem.FileSystemDownloadResult>(  ( resolve, reject ) => {
            const result = downloadResumable.downloadAsync()
            result  ? resolve( result.then() ) : reject( result )
        } )
            .then( ( result ) => console.log( `Finished downloading to ${result.uri}` ) )
            .catch( ( reason ) => console.error( `Failed download: ${reason}` ) )
}

Comment: https://www.geeksforgeeks.org/difference-between-promise-and-async-await-in-node-js/#:~:text=Promise%20is%20an%20object%20representing,the%20code%20execute%20more%20synchronously.
Comment: @vanowm Yes, lol, that's exactly what got me started trying to translate from async/await to Promises, but as you can see I didn't get very far.
Comment: `async`/`await` is not syntactic sugar for `new Promise`, but only for `.then(…)`.
Answer: Assuming that downloadAsync returns a Promise and that console.log doesn't throw, this
const downloadFileAA = async () => {
    try {
        console.log( 'Starting download (with async/await)... ' )
        const result = await downloadResumable.downloadAsync()
        console.log( result ? `Finished downloading to ${result.uri}` : 'Undefined result?'  )
    } catch ( e ) {
        console.error( `Failed download: ${e.message}` )
    }
}

is equivalent to
const downloadFileAA = () => {
    console.log('Starting download (with async/await)... ')
    return downloadResumable.downloadAsync()
        .then((result) => {
            console.log(result ? `Finished downloading to ${result.uri}` : 'Undefined result?')
        })
        .catch((e) => {
            console.error(`Failed download: ${e.message}`);
        });
};

What await does is it replaces .then. It doesn't replace Promises - both .then and await require a Promise (to be used sensibly, at least).
Your downloadFilePromise function is broken because it constructs a Promise that, by definition, never resolves - you must call the resolve or reject argument in order for the constructed Promise to resolve. But since it looks like downloadAsync already returns a Promise, constructing another Promise to surround it doesn't make any sense  - just use the Promise you have instead of making a new one.

Is there a reason to prefer it (or not) over the async/await version?

It's purely a stylistic choice. IMO await shines best when there are multiple values that need to be waited for (serially), but otherwise either work just fine (as long as they're implemented properly, of course).
Comment: As an addendum, I would say the caveat "as long as they're implemented properly" is an important one. One of the main strengths of async-await is that control flow is very easy to visualise, whereas with `.then()` chains, it's easy to overlook a chain with no catcher etc. So while yes, both can be used to write equivalent code, in my personal opinion async-await makes mistakes easier to spot. And since we all make mistakes when writing code, that's a very good thing.
Comment: You should return `downloadResumable.downloadAsync` in the second example otherwise this can't be awaited.
Comment: @lawrence-witt In `downloadFilePromise`? How does that fix it?


How to ignore / exclude index file from VS Code / Intellisense / Autocomplete?

Question: I am working on a library project which has a lib.ts file at the workspace root which defines all public exports of the library as follows:
export * from "./a/a.ts"
export * from "./b/b.ts"
export * from "./c/c.ts"

I am also using VS Code autocomplete (ctrl + space) a lot to let VS Code organize/add imports automatically while I am developing. Unfortunately, Intellisense keeps importing from lib.ts rather than from the original file that defined the export.
So, assuming that a needs b, VS Code would organize the imports in a.ts as follows:
import { b } from "../lib"

export const a = b(1)

That results in circular dependencies at build time, which seems to confuse rollup:
  lib.ts -> a/a.ts -> lib.ts -> b/b.ts

Is there a way to tell VS Code to ignore lib.ts and import b from its original source, like so?
import { b } from "../b/b"

export const a = b(1)

Answer: I ran into this exact same problem and found this setting in the preferences:
typescript.preferences.autoImportFileExcludePatterns
In your case you could add a glob like this:
{
  "typescript.preferences.autoImportFileExcludePatterns": [
    "../../lib.ts"
  ],
}

and then it won't suggest imports from any lib.ts files that you don't want to import from.