text:
Q: PHP How to handle/parse csv files that have missing columns I have many csv files generated by a third party, for which I have no say or control.
So each day I must import these csv data to mysql.
Some tables have correct matching number of columns to header.
Others do not.
Even when I did a prepared statement, it still did not import.
I tried to create a repair csv function, to add extra columns to each row, if their count of columns was less than the count of header columns.
As part of this project I am using the composer package league csv.
https://csv.thephpleague.com/
But here is my function code:
public function repaircsv(string $filepath) {

    // make sure incoming file exists
    if (!file_exists($filepath)) {

        // return nothing
        return;
    }

    // setup variables
    $tempfile = pathinfo($filepath,PATHINFO_DIRNAME).'temp.csv';
    $counter = 0;
    $colcount = 0;
    $myline = '';

    // check if temp file exists if it does delete it
    if (file_exists($tempfile)) {

        // delete the temp file
        unlink($tempfile);

    }

    // C:\Users\admin\vendor\league\csv
    require('C:\Users\admin\vendor\league\csv\autoload.php');

    // step one get header column count
    $csv = Reader::createFromPath($filepath);

    // set the header offset
    $csv->setHeaderOffset(0);

    //returns the CSV header record
    $header = $csv->getHeader();

    // get the header column count
    $header_count = count($header);

    // check if greater than zero and not null
    if ($header_count < 1 || empty($header_count)) {

        // return nothing
        return $header_count;

    }

    // loop thru csv file
    // now read file line by line skipping line 1
    $file = fopen($filepath, 'r');
    $temp = fopen($tempfile, 'w');

    // loop thru each line
    while (($line = fgetcsv($file)) !== FALSE) {

        // if first row just straight append
        if ($counter = 0) {

            // append line to temp file
            fputcsv($temp, $line);

        }

        // if all other rows compare column count to header column count
        if ($counter > 0) {

            // get column count for normal rows
            $colcount = count($line);

            // compare to header column count
            $coldif = $header_count - $colcount;

            // loop til difference is zero
            while ($colcount != $header_count) {

                // add to line extra comma
                $line .= ',';

                // get new column count
                $colcount = count($line);

            }

            // append to temp file
            fputcsv($temp, $line);

            // show each line
            $myline .= 'Line: ['.$line.']

';

        }

        // increment counter
        $counter++;

    }

    // check file size of temp file
    $fs = filesize($tempfile);

    // if below 200 ignore and do not copy
    if ($fs > 200) {

        // copy temp to original filename
        copy($tempfile,$filepath);

    }

    return $myline;
}

The logic is to copy the original csv file to a new temp csv file and add extra commas to rows of data that have missing columns.
Thank you for any help.
Edit: So the various csv's contain private data, so I can not share them.
But let us for example say i download multiple csvs for different data daily.
Each csv has a header row, and data.
If the number of columns in each row isn't 100% the same number of columns as in the header, it errors out.
If there are any special characters, it errors out.
There are 1000's of rows of data.
The code above is my first attempt to try to fix rows that have missing columns.
Here is an example
FirstName, LastName, Email
Steve,Jobs
,Johnson,sj@johns.com
Just a very small example.
I have no control of how the csvs are created, I do control the download process and import process.
Which then i use the csv data to update mysql tables.
I have tried the load data infile but that errors out too.
So I need to fix the csv files after they are downloaded.
Any ideas?

A: Do not mix array and string, instead of
$line .= ',';
do
$Line[]= '';
Also fix:
$myline .= 'Line: ['.implode(',', $line).']

';

Suggestion, you can replace your while loop with:
$line = array_pad($line, $header_count, ''); // append missing items
$line = array_slice($line, 0, $header_count); // remove eventual excess items


text:
Q: JBuilder and Java 5 I'm using JBuilder 6 and running against Java 1.3
I'm migrating to Java 5
Do I need a more modern version of JBuilder to run against Java 5?

A: Yes.  Primarily to support the syntax sugar added in Java 5 like Generics and the enhanced for loop.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way to make OS X more tolerant of momentary USB disconnects? My MacBook Pro (16-inch, 2019) is connected to a Thunderbolt 3 dock which has external monitors and, most crucially, a USB3 Time Machine drive on it.
If I so much as lightly touch the Thunderbolt cable, the dock and all attached devices disconnect. The biggest concern is the unsafe un-mounting of the hard drive, but losing my monitors, keyboard and microphone is also annoying.
Is there any setting which would make OS X more tolerant in momentary (less than 2 second) Thunderbold disconnects? I expect not... in which case, are there any hardware changes which can make a Thunderbolt connection less flakey? (It's an Apple thunderbolt cable, but a third party dock)

A: No, there's no such setting. That sort of thing is not possible to make happen in software in the operating system.
I would advise you to use cables and docks that allows you to physically lock the cable, so that you do not accidentally unplug it. Some plugs can be locked with screws to the dock, or have various "twist-to-lock" mechanism to ensure a reliable connection.


text:
Q: VueJS - Errors interpretation in .vue file I just started to learn VueJs and I totally got blocked by an error that prevents me from compiling my app.
My command line says:

Failed to compile with 1 errors
  19:46:58  error  in ./src/components/SliderHome.vue
Syntax Error: Unexpected token (1:233)
@ ./src/components/SliderHome.vue 11:0-366  @
  ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue
  @ ./src/App.vue  @ ./src/main.js  @ multi
  (webpack)-dev-server/client?http://localhost:8080
  webpack/hot/dev-server ./src/main.js

In my sliderHome.vue:

<template>

{{ slide.headlineFirstLine }}

{{ slide.headlineSecondLine }}

{{ slide.headlineFirstLine }}

{{ slide.headlineSecondLine }}

Call To Action

{{ slide.sublineFirstLine }} / {{ slide.sublineSecondLine }}

        <button class="controls-button"
          v-for="(slide, index) in slides"
          :key="slide.id, index.id"
          v-bind:class="{ active: index === currentSlide }"
          v-on:click="updateSlide(index)">{{ slide.headlineFirstLine }} {{ slide.headlineSecondLine }}</button>

</template>

I would like to know where I need to look, or what I need to be looking for to clean this error...
Thanks in advance to any help you can bring to me.


text:
Q: Are there any differences between the future in the past when using "would" & reported speech when changing "will" to "would"? This site said:

The future in the past is used to look into the future from a point of
  time in the past. However, this "future" event still occurred at a
  time before the present time.

E.g. I woke up (1) at 8am yesterday. I was meeting my boss (2) at ten
  o'clock that morning, so I wouldn't be able to have lunch (3) with
  Susan. I wasn't going to get home (4) again until late that night.

But, see this example in reported speech:
Let say today is Monday & at 1 PM, A says "I will have lunch with Susan tomorrow".
Ok, at 2 PM, B says "She said she would have lunch with Susan tomorrow".
My question is that:
So, the law of Reported speech does not adhere the law of the future in the past, right?
Because the law of the future in the past said the-future-in-the past event still occurred at a time before the present time. but the action "would have lunch with Susan tomorrow" will not happen before now.
However, let say, at 3pm on Wednesday, B says "She said she would have lunch with Susan yesterday", then it adheres to the law of the future in the past because that action occurred before now.
So, Are there any differences between the future in the past when using "would" & reported speech when changing "will" to "would"?


text:
Q: Using BoundList as widget I have an extended bound list, and I use it as a widget. Get/set value and other works good, but: How can I add a field label before it? Example of set value:
setValue: function (v) {
    this.value = v;
    // TODO select selected
    var sm = this.getSelectionModel();
    var store = this.getStore();
    var rec = store.findRecord(this.valueField, v);
    sm.select(rec);
},

Can you help me? Or is the only solution that I have to put this bounding list in a panel?

A: The easiest way to get around this is to put it inside a FieldContainer.


text:
Q: Java Progressbar to get running of function I created a pinging program to ping 5 server. How do I have the progressbar to get run while the progress is being run. When the ping is done the progressbar will be 100%
  private void btnGetstatusActionPerformed(java.awt.event.ActionEvent evt) {

        try {

            pingserver1();
            pingserver2();
            pingserver3();
            pingserver4();
            pingserver5();

    }

   public void pingserver1() throws UnknownHostException, IOException {

        InetAddress addr = InetAddress.getByName("127.0.0.1");

        System.out.println("Sending Ping Request to " + addr);
        boolean status = addr.isReachable(5000);

    }

....

A: You could create yourself an SwingWorker, within the doInBackground method, you would execute your pingserverx methods.
You could then use the SwingWorkers progress API to send notifications about updates to the progress and within the ProperyChangeListener, update the UI.
For example and example
Take a look at Concurrency in Swing for more details


text:
Q: Округление Decimal Есть число и 40 знаков после запятой. Последнюю цифру дробной части нужно округлить;один раз вверх и один раз вниз.
Запускаю
Num = Decimal(123.1234567890123456789012345678901234567890)
Delta = Decimal(1/10000000000000000000000000000000000000000)
NumUp = Num + Delta
NumDown = Num - Delta
print('Delta     =   ' '%.40f' % Delta)
print('NumUp     = '   '%.40f' % NumUp)
print('Num       = '   '%.40f' % Num)
print('NumDown   = '   '%.40f' % NumDown)

Ожидую получить:
Delta     =   0.0000000000000000000000000000000000000001
NumUp     = 123.1234567890123456789012345678901234567891
Num       = 123.1234567890123456789012345678901234567890
NumDown   = 123.1234567890123456789012345678901234567889

А получаю:
Delta     =   0.0000000000000000000000000000000000000001
NumUp     = 123.1234567890123514644074020907282829284668
Num       = 123.1234567890123514644074020907282829284668
NumDown   = 123.1234567890123514644074020907282829284668

Как добиться необходимого округления?

A: У вас точность теряется три раза:

*

*при создании Decimal из float

*при операциях с Decimal

*при преобразовании Decimal в float для печати

Можно всё исправить таким образом:
from decimal import *
# по умолчанию точность работы с Decimal всего 28 знаков, нам нужно задать "с запасом"
getcontext().prec = 43
# создаём Decimal из литерала, а не из float, чтобы не потерять точность!
Num = Decimal('123.1234567890123456789012345678901234567890')
# можно создавать Decimal и таким образом, главное, что не из float
Delta = 1 / Decimal(10000000000000000000000000000000000000000)
NumUp = Num + Delta
NumDown = Num - Delta
# вывод на печать делаем без float-формата, средствами форматирования самого Decimal
print('Delta     =', Delta)
print('NumUp     =', NumUp)
print('Num       =', Num)
print('NumDown   =', NumDown)

Delta     = 1E-40
NumUp     = 123.1234567890123456789012345678901234567891
Num       = 123.1234567890123456789012345678901234567890
NumDown   = 123.1234567890123456789012345678901234567889


text:
Q: Intellij MYSQl how to connect with controller class? I'm new to intelliJ, just switched from eclipse. I have a few question:
I have gone to the project settings, to the libraries and added MYSQl connection. Also under modules and dependencies I have the mySql connector.
I have tried the following code in eclipse:
String dbUsername = "root";
    String dbPassword = "12frimyux09";
    String URL = "127.0.0.1";
    String port = "3306";
    String dbName = "university";
    //Connection con;
    String SQL;
    String dbURL = "jdbc:mysql://" + URL + ":" + port + "/" + dbName + "?verifyServerCertificate=false&useJDBCComplaintTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
    Properties property  = new Properties();

        property.setProperty ("user", dbUsername);
        property.setProperty("password", dbPassword);
        property.setProperty("useSSL", "false");
        property.setProperty("autoReconnect", "true");

        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection con = DriverManager.getConnection (dbURL, property);

worked just fine, but doesn't work with intellij (I put the code in the controller class), even tried using try and catch, still no luck, I get the following error.1
Also in eclipse when I use Integer.parseInt I get alot of suggestions, but with intellij I get error and no suggestions, tried cntrl space and cntrl p, also went to file, settings, code completion and set all the ticks under parameter info, what am I doing wrong, why isn't intellji completing me???


text:
Q: targeting dev sites with vhost setup using ngrok I'm trying to tunnel a clients site in my sites directory with "ngrok http -host-header = client1.dev 80", I get a 404 when accessing the url. After some experimenting, if I put an index.html file in the home directory, it will display that file. Not sure why a file in the home directory works while files in sites directory do not. I must be missing something here..Any ideas?
directory structure :
www
  |home
  |sites
    | client1
    | client2
      ...

vhost.conf :
<Directory "/www">
Options Indexes MultiViews FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>

<Virtualhost *:80>
VirtualDocumentRoot "/Users/myname/www/home/wwwroot"
ServerName home.dev
UseCanonicalName Off
</Virtualhost>

<Virtualhost *:80>
VirtualDocumentRoot "/Users/myname/www/sites/%1/wwwroot"
ServerName sites.dev
ServerAlias *.dev
UseCanonicalName Off
</Virtualhost>

A: Cool All your config is good,
You just have to exec command
ngrok http -host-header=rewrite home.dev:80

ngrok http -host-header=rewrite sites.dev:80

New Command (8-30-22 edit):
ngrok http --host-header=rewrite sites.dev:80

A: If you want a more permanent configuration, you can edit your ~/.ngrok2/ngrok.yml config file.
tunnels:
  test: # the name of your tunnel to call from the command line
    addr: 80 # Your localhost port
    proto: http
    host_header: test.localhost # Your localhost virtualhost

And then you can run from your command line
ngrok start test

A: For me it only worked with:
ngrok http -host-header=sites.dev 80

Change sites.dev to you virtual host name
Source: Virtual hosts (MAMP, WAMP, etc)

A: Not sure if the command got changed from the previous versions.
From the help doc of Ngrok,
ngrok http --host-header=ex.com 80          # rewrite the Host header to 'ex.com'

Notice the double hyphens(--).


text:
Q: CUPS Changing AuthInfoRequired from username,password to none with https URI I have two CentOS 6 servers running cups and connecting to the same ipp over https printer. Both were installed with the same lpadmin command below.
lpadmin -p ptr -v https://username%40mailer.com:p%40ssword@myprintserver.com/printer -E

Server 1 was able to print without issue.
Cups
Name        : cups
Arch        : x86_64
Epoch       : 1
Version     : 1.4.2
Release     : 44.el6

printers.conf
<Printer ptr>
AuthInfoRequired username,password
Info ptr
DeviceURI https://username%40mailer.com:p%40ssword@myprintserver.com/printer

Server 2 is not able to print
Cups
Name        : cups
Arch        : x86_64
Epoch       : 1
Version     : 1.4.2
Release     : 78.el6_9

printers.conf
<Printer ptr>
AuthInfoRequired none
Info ptr
DeviceURI https://username%40mailer.com:p%40ssword@myprintserver.com/printer

In /var/log/cups/error_log
D [26/Oct/2017:10:31:53 -0400] [Job 220770] Connected to printer...
D [26/Oct/2017:10:31:53 -0400] [Job 220770] Connected to my-printserverip:443 (IPv4)...
D [26/Oct/2017:10:31:53 -0400] [Job 220770] Getting supported attributes...
D [26/Oct/2017:10:31:53 -0400] [Job 220770] ATTR: auth-info-required=none
D [26/Oct/2017:10:31:53 -0400] [Job 220770] Backend returned status 2 (authentication required)
D [26/Oct/2017:10:31:53 -0400] [Job 220770] Job held for authentication.

On Server 2 I tried stoping cups, changing AuthInfoRequired from none to username,password and then starting cups however it doesn't fix it and on the next cups restart just reverts back to none. I tried bouncing cups on Server 1 and it retains the username,password. I then updated Server 1 to version 78.el6_9, uninstalling and reinstalling ptr with the above lpadmin command and now both servers are in the same boat reverting to AuthInfoRequired none and Job held for authentication.
Is there something different I need to do with the new version of cups?
I have tried passing -o auth-info=username,password, however this appears to make the AuthInfoRequired line disappear all together and results in the same errors in the log as above.
Update 1:
Testing with CentOS 7 gives expected behavior of automatically populating AuthInfoRequired with username,password CUPS version 1.6.3-26
Update 2:
Tried to rpmrepack cups 1.4.2-44 from another CentOS 6 server and rpm downgrade to the prior older version with no success.
Update 3:
I have started reading the cups source code for my version. It appears the AuthInfoRequired field is automatic set for ipp printers based on if cups see's a password in the DeviceURI, not sure why it's tossing my Auth info out the window.

A: Instead of auth-info=username,password use auth-info-required (eg -o auth-info-required=username,password). CUPS rewrites printers.conf when stopping (see the man page, CUPS source), so to edit the file either stop the CUPS server first or use lpoptions.
If you revert to 1.4.2-44 and set auth-info-required you should be back to being able to print.


text:
Q: ufunc 'isnan' not supported for the input types / could not convert string to float: for dates import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
appl = pd.read_csv('appl.csv') #apple stock prices taken from finance.yahoo.com

x = appl[['Date', 'Open','High','Low','Close']]
y = pd.to_datetime(appl['Date'])

import numpy as np
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2, random_state=0)
model = LinearRegression()
#model.fit(np.isnan(x_train),np.isnan(y_train))
model.fit(x_train,y_train) #<--- receive error on this line
model.coef_
model.intercept_

I get when using model.fit(x_train,y_train) the errors ufunc 'isnan' not supported for the input types
and when not using model.fit(np.isnan(x_train),np.isnan(y_train)) could not convert string to float:


text:
Q: Order of individual Fourier coefficient of a Maass form Let $D$ be a definite quaternion division algebra over $\mathbb{Q}$ and $\mathcal{O}$ be an Eichler order of $D$. Let $F$ be a Maass form in $L^2(PGL_2(\mathcal{O})\backslash PGL_2(D\otimes\mathbb{R}))$. For a finite unramified prime $p$ we have $K_p=GL_2(\mathcal{O}_p)=GL_4(\mathbb{Z}_p)$. We can think of a Hecke operator of $GL_2(D_p)$ with respect to $GL_2(\mathcal{O}_p)$ as: $$p^2T_{p,2}=K_p\begin{pmatrix}p&&&\\&p&&\\&&1&\\&&&1\end{pmatrix}K_p,$$which is self-adjoint. Let, $T_{p,2}F=\lambda(p)F$, so $\lambda(p)$ is real.
One can calculate the Fourier expansion of $T_{p,2}F$. Namely if $\rho(n)$ are Forier coefficient of $F$ then,
$$\lambda(p)\rho(n)=\rho(p^{-1}n)+\rho(pn)+\frac1p\sum_{\alpha,\beta\in C_p}\rho(\alpha^{-1}n\beta),$$ where $C_p=\{\alpha|\text{reduced norm}(\alpha)=p\}/\mathcal{O}^\times$ (see prop 5.9, 2c). Hence one can calculate,$$\lambda(p)\rho(1)=\rho(p)+(p+\frac1p)\rho(1).$$
$\textbf{Q.}$ Is it true that $\lambda(p)\gg1$ for almost all finite $p$? I.e. Can we say something about order of $\rho(p)$?
I am not sure whether involving Jacquet-Langlands makes this question easier to deal with or not.
Thanks for any help and/or reference.


text:
Q: How does breeding Alolan form Pokémon work? I'm curious how breeding in Pokémon Sun and Moon is affected by the new Alolan forms. Is the form randomly distributed based on the parents, like abilities or nature are?
For example, if I breed an Alolan Dugtrio with a standard Dugtrio, what is the probability that I will get an Alolan Diglett?

A: According to Serebii, you will hatch a Alolan form of whatever Pokémon you are breeding, by default, if there is one.

When you transfer Pokémon from previous games and breed them, you will get their Alola Forms. However, if you attach an Everstone to the non-Gen VII native variant and breed, you'll get the standard form.

Thus, if you breed two standard Dugtrio, you will get an Alolan Diglett. The only way to not breed an Alolan form is to have the standard form parent hold an Everstone.
As mentioned in the comments, this means that breeding a standard form Pokémon with a Ditto holding an Everstone will still result in an Alolan form baby. In order to get a standard form baby with one of the parents being a Ditto is for the non-Ditto parent to hold the Everstone.


text:
Q: How to use Fable output to other JS projects I have a small fs file code
module FableApp

open Fable.Import.Browser
let sum x y=
    x+y

let myfunct=
    let result=sum 5 10
    console.log(result)

I am trying to compile it to JS and use in other projects. I have seen that its possible through Fable Repl but I want to do pragmatically. As I need to compile FsProjects in future.
When I tried to compile this using webpack then I got this code
(window.webpackJsonp= window.webpackJsonp|| []).push([
    [0],
    [function(n, o, t) {
        "use strict";

        function c(n, o) {
            return n + o | 0
        }
        t.r(o), t.d(o, "Sum", function() {
            return c
        }), t.d(o, "myfunct", function() {
            return r
        });
        var r = function() {
            var n = 0 | c(5, 10);
            console.log(n)
        }()
    }]
]);

A: According to your requirements I think that the fable-splitter npm package would be exactly the thing you are looking for.
As described in the documentation you would add a line to the scripts block of your package.json file in which you tell the script runner to build your project and put the unbundled files to the output location.
"scripts": {
  "build": "fable-splitter src/MyProject.fsproj --outDir out"
}

There are more fine grained configuration options I'd suggest you look at the documentation to get acquainted with the API in case you should need it. If you want to use the configuration in your build you would change the script block to include a configuration parameter pointing to the config file.
"scripts": {
  "build": "fable-splitter --config splitter.config.js"
}


text:
Q: Can I add Google Play Services to already published app? My game is published and live on Google Play. But in the next update I want to add Play Services. Is this possible, because I read that I have to publish the Play Services first and then the game. If it's possible can you give me detailed instructions, because I tried once and screwed the things.

A: You will have to go back to your source code, add the Google Play Services and build another APK. After that re-upload it to Google Play again, say version 2. The instruction to add Google Play Services to your project is stated in the Add Google Play Services to Your Project:
To make the Google Play services APIs available to your app:

Open the build.gradle file inside your application module directory.
  Note: Android Studio projects contain a top-level build.gradle file
  and a build.gradle file for each module. Be sure to edit the file for
  your application module. See Building Your Project with Gradle for
  more information about Gradle. Add a new build rule under dependencies
  for the latest version of play-services. For example: apply plugin:
  'com.android.application'
      ...
dependencies {
    compile 'com.google.android.gms:play-services:10.0.1'
}

Be sure you update this version number each time Google Play services
  is updated.  Check the docs for more info.


text:
Q: alias conflict namespace c# Looking for an explanation.
I have the same name space in two different assemblies.  Say
NsA.xxx.NsB

Now I created an alias to resolve the issue and called it xxx.
I left "global" as the alias namespace for the other assembly.
The trouble is that "xxx" as an alias conflicted with "xxx" namespace part.  I resolved the Issue by haveing my alias named "XXX".  Now there was no conflict and everyone returned to thinking happy thoughts.
This is unexpected (to me).  Is this a bug?

A: It's not a bug. That's how you resolve conflicts when multiple assemblies used in code have classes with the same name.

A: C# is case sensitive so there is a distinct difference between namespace xxx and namespace alias XXX.
Example:
using Company.People.Employee;
//using Contractor.People.Employee;
using PEOPLE = Contractor.People;

//People.Employee is not the same as PEOPLE.Employee, even though they look very similar


text:
Q: What does it mean for a field theory to be invariant? In this paper A. N. Schellekens, Conformal field theory p.8 they mention the following

If a field theory has a conserved, traceless energy momentum tensor, it is invariant
both under general coordinate transformations and Weyl transformations.

What is meant with 'a field theory is invariant'? Is the action invariant? The fields? The equations of motion? All of the above?

A: The action, yes. The equations of motion, therefore also yes. But the fields themselves, no. That's like expecting a rotation of axes to preserve Cartesian coordinates in Newtonian physics.


text:
Q: Add entries to web.config file of asp.net core application when web.config does not exist I have an asp.net CORE project targeting .NET Framework 4.71
There is an appsettings.json file but not web.config.
When I check the binaries of the deployed application service, then I see there is
a file literally called web.config.
I need to put some server header removal entries in that web.config but it seems
only to be available where it is deployed.
So who is creating that web.config file which is not available locally in the
code solution?

A: In regular .NET world, we have option to save settings in web.config or in app.config file. But in .NET Core, you have option to save them in few other locations like appsettings.json , appsettings.<Environment>.json and in secrets.json.
One of the main reason settings are not saved in web.config file is, to avoid settings getting checked-into repo. By default appsettings.json file are ignored by repo clients.
As Kirk said, the dotnet-cli automatically creates this web.config based on the the csproj settings.


text:
Q: stackification commutes with finite limits? Suppose we work on the Grothendieck site $\mathcal{C}$ of all schemes in the fpqc topology. If it helps it is also fine with me to work only over affine schemes.
Let us denote the category of stacks over $\mathcal{C}$ by $Stacks(\mathcal{C})$. This is naturally a full subcategory of the category $Pre_{grpds}(\mathcal{C})$ of presheaves in groupoids over $\mathcal{C}$. This is equivalent to formulating stacks as being categories fibered in groupoids, fulfilling effective descent.
Now the inclusion $Stacks(\mathcal{C}) \to Pre_{grpds}(\mathcal{C})$ has a left adjoint called the stackification functor.
It is a classical fact that the sheafification functor on presheaves of sets commutes with finite limits. Is this also true for the mentioned stackification functor?
Precisely, I want to know if and if so, why, the stackification functor commutes with 2-categorical pullbacks, here is the precise setting.
Suppose we are given Hopf-algebroids $P_1,P_2,P$ and view them as presheaves in groupoids.
Suppose we are given two morphisms $P \to P_i$ and we construct the 2-pullback of functors $$Q = pullback(P_1 \to P \leftarrow P_2).$$
In my situation I can show that Q is equivalent to an affine scheme, and I want to conclude that the pullback of the stackified diagram is also equivalent to an affine scheme.
If I knew that stackification commuted with finite limits, this would be ok, since the (co)unit (I always mix them up) of the adjunction is an equivalence, i.e., if $X$ is a stack, and $st(X)$ is its stackification, then the natural map $X\to st(X)$ adjoint to the identity of $st(X)$ is an equivalence of stacks.
Any help and comments are appreciated, also if you could give references concerning these questions, that would be great.

A: The answer is yes, at least for $2$-fiber products. And fortunately there is an excellent reference online: Tag04Y1 in the Stacks Project. I quote:

Lemma 8.4. Let $C$ be a site. Let $f : X \to Y$ and $g : Z \to Y$ be morphisms of fibred categories over $C$. In this case the stackification of the 2-fibre product is the 2-fibre product of the stackifications.


text:
Q: Does the following operation on modular forms yield something modular? Let $f(z) = \sum_{n=0}^\infty a_nq^n$ be the fourier expansion of a (quasi-)modular form (with $q = e^{2\pi i z}$). Consider the following related functions:
$$f_{m,k}(z) = \sum_{n=0}^\infty a_{mn + k}q^n$$
$$g_{m,k}(z) = \sum_{n=0}^\infty a_{mn + k}q^{mn+k}$$
for, naturally, $0 \leq k < m$.
My question: are these in any way modular? For some congruence subgroup, etc. etc.?
What if we put some restrictions on $f(z)$? Or shift the powers of $q$ somewhat?
As an example of when we do retain (quasi-)modularity, consider the case $f(z) = E_2(z), m = 2$. Then it is not too hard to show that
$$
E_2(z) = g_{2,1}(z) + 3E_2(2z) - 2E_2(4z)
$$
and so it follows that $g_{2,1}(z)$ is indeed quasi-modular for $\Gamma_0(4)$. Since then $g_{2,0} = E_2(z) - g_{2,1}(z)$, this is also quasi-modular.
So is this in general true?

A: I know nothing about quasimodular forms, so let me answer the question for modular forms in the classical sense.
First, your $f_{m, k}$. If $k = 0$ this is essentially the image of $f$ under the Hecke operator $U_m$, so it is always going to be modular of some level (and if f has level $\Gamma$, then $f_{m, 0}$ will have level $ \Gamma \cap \Gamma_0(m)$ or something like that). If $k \ne 0$ then $f_{m, k}$ will not be modular, because $f_{m, k}(mz) = q^{-k} g_{m, k}(z)$, $g_{m, k}$ is modular, and dividing by a power of $q$ destroys modularity.
Now $g_{m, k}$. This is just a linear combination of the forms $f(z + j/m)$ for $j = 0, ..., m$ by finite Fourier theory, and all these are modular, so $g_{m, k}$ is modular (although if $g$ is modular of level $\Gamma_1(N)$, then $g_{m, k}$ will have level something like $\Gamma_1(mN) \cap \Gamma_0(m^2 N)$ in general).
The forms $g_{m, k}$ are closely related to the forms
$$ g_{\chi} = \sum_n \chi(n) a_n q^n $$
for Dirichlet characters $\chi$ modulo $m$, which are very interesting (and well-studied) objects; if $g$ is a Hecke eigenform then so are the forms $g_{\chi}$ (although the $g_{m, k}$ generally aren't).


text:
Q: Spring Cloud Function Composition I am trying spring cloud function with aws lambda.
Lets say, I have 5 different spring function (A,B,C,D,E) and function composition of like this A|B|C|D|E.
I specify which function to invoke using spring_cloud_function_definition in lambda,
so, spring_cloud_function_definition = A|B|C|D|E
Now, i want to route to other function (lets say F), from function A in certain scenario (lets say, on receive of some error code while executing in A) and not move to next functions in function composition.
What i would like to know:

*

*Is it possible to end execution in this function composition in middle based on certain parameters.? If yes, How do i achieve.
I tried MessgaeRoutingCallback but its not working for me. I created a class  that
implements MessgaeRoutingCallback. I returned "F" in functiondefinition.  I tried to
call this functiondefinition from function "A".
On execution of composition,it goes like this A -> functiondefinition (does not route to F) -> B ->C->D->E

A: Once again, (as it is explained here and in the previous post here some time back) composed function is not a chain or flow or a pipeline of any kind. It is a single function created using andThen or compose methods of Java Function.
It is as if you wrote a single function yourself combining the functionality of all 5 functions. So the real question should be "how do you stop execution of a single function in the middle of its execution?"


text:
Q: Selection Sort Swap Count I have an array including user's inputs. The program is about Bubble sort, Selection sort and Insertion sort. I couldn't manage to solve a problem in Selection part. Swap counter always gives me Array's length - 1. I know It's because of the first for loop but I couldn't find any solutions though.
int SComparison = 0;
int SSwaps = 0;

for (int i = 0; i < SorBag.length - 1; i++) {
        min = i;

        for (int j = i + 1; j < SorBag.length; j++) {
            SComparison++;

            if (SorBag[j] < SorBag[min]) {
                min = j;

            }
        }

        SSwaps++;
        temp2 = SorBag[i];
        SorBag[i] = SorBag[min];
        SorBag[min] = temp2;
    }

I tried putting SSwaps into "if", It gives me always 0. I tried making an "if" to find how many array elements are smaller than this first ones. Still the same. Where should put SSwaps++ ? Thank you !

A: check this code :
public class Test {

    public static void main(String[] args) {

        int SComparison = 0;
         int SSwaps = 0;
         int totalSwap=0;
        int min = 0;
        int temp = 0;
        int SorBag[] = { 1, 4, 3 };

        for (int i = 0; i < SorBag.length - 1; i++) {
            min = i;

            for (int j = i + 1; j < SorBag.length; j++) {
                SComparison++;

                if (SorBag[j] < SorBag[min]) {
                    min = j;
                    temp = SorBag[i];
                    SorBag[i] = SorBag[min];
                    SorBag[min] = temp;
                    SSwaps++;
                    totalSwap+=SSwaps;
                    System.out.println("swap count at "+j+" pass : "+SSwaps);
                }
            }
            SSwaps=0;

        }
        for (int i = 0; i < SorBag.length; i++)
            System.out.print(SorBag[i]+" ");

        System.out.println("\nTotal swap count :"+totalSwap);
    }

}

output :
swap count at 2 pass : 1
1 3 4
Total swap count :1

A: selection sort updates the min index by comparison (your if ...), and do the element swapping if it is needed.
You put the swapps++ at right position. but you should check , if min == i. You only want to do swap if min !=i. instead, you didn't check that, just swap anyway. that's why you got fixed length -1
P.S. please try to follow the java naming convention.

A: Whats the issue?
With your code this gives 4 swaps which is correct.
    int[] SorBag = new int[]{5 ,4 ,3 ,2 ,1};
    int min = 0;
    int SComparison = 0;
    int SSwaps = 0;

    for (int i = 0; i < SorBag.length - 1; i++) {
            min = i;

            for (int j = i + 1; j < SorBag.length; j++) {
                SComparison++;

                if (SorBag[j] < SorBag[min]) {
                    min = j;
                    SSwaps++;
                }
            }

            int temp2 = SorBag[i];
            SorBag[i] = SorBag[min];
            SorBag[min] = temp2;
        }
    System.out.println("sswaps : "+SSwaps);

    for(int i = 0; i<5;i++){
        System.out.println("SorBag["+i+"] = "+SorBag[i]);
    }
}


text:
Q: Maxima problem? this question is off a textbook, and I've been having a lot of trouble with it:
"A window consists of a rectangle surmounted by a semi-circle having its diameter the width of the rectangle. If the perimeter of the window is $t$ meters, find the greatest possible area of the window."
The final answer is:
$t^2 / 2(pi + 4)$
Could someone please explain how to do this step by step?
Thanks

A: We set things up, and leave the differentiation and conclusion to you.
Let us explore what happens if we let the radius be $x$. Then the curvy part of the semi-circle has perimeter $\pi x$. The base of the window has length $2x$. Since the whole perimeter is $t$, the two sides have combined length $t-\pi x-2x$. It follows that each side of the window has length
$$\frac{t-\pi x-2x}{2}.$$
Next we find a formula for the area $A(x)$ of the window.
The semi-circle has area $\frac{\pi}{2}x^2$.
The rectangular part of the window has area $(2x)\frac{t-\pi x-2x}{2}=x(t-\pi x -2x)$. It follows that
$$A(x)=\frac{\pi}{2}x^2 +x(t-\pi x -2x).$$
Now do the usual thing: find where $A'(x)=0$.
For completeness, we have to check  whether the maximum is at an end-point, or alternately look at the sign of $A'(x)$ when $A'(x)\ne 0$.

A: HINT:
If the width $=a$ unit, the height is $=b$ unit,
the perimeter $=\frac{\pi a}2+2b+a=t\implies b=\frac{2t-(\pi+2)a}4$
So, the total area $=\frac{\pi\left(\frac a2\right)^2}2+a\cdot b=\frac{\pi\left(\frac a2\right)^2}2+a\cdot\frac{2t-(\pi+2)a}4 =f(a)$ (say)
Use Second derivative test


text:
Q: What is causing this heap buffer overflow? This is the error in the terminal that I am getting
This is my code, what exactly is the issue that is causing this heap buffer overflow. To give context this code is a Run Length Encoder that I am programming in C. I am fairly new to it so I am still learning the ropes, but as far as syntax goes it is all correct anyways here is the code.
char* compress(char* str){

    int len = strlen(str);

    char build= (char*)malloc(2*len);

    int i;

    for(i=0; i<len;i++){

            int count =1;

            while ((i<len-1) && (str[i]==str[i+1])){

                count++;
                i++;
            }

            strncat(build, &str[i], 1);
            //delete later
            printf("%s\n", build);

            char *c = count+ "0";

            strcat(build, c);
            //delete later
            printf("%s\n", build);
    }

    return build;

    free(build);

}

int compareLength(int str1, int str2){

    if(str1>str2){

        return 0;

    } else {

        return 1;
    }
}

int containsDigit(char* input){

    int i;
    int len = strlen(input);
    int isDigit=0;

    for(i=0;i<len;i++){

        if(isdigit(input[i])==0)

            isDigit++;
    }

    if(isDigit>0){

        return 1;
    }else{

        return 0;
    }

}

int main(int argc, char** argv){

    char *input = argv[1];

    int inputLen = (strlen(input));
    int compressLen = (strlen(compress(input)));

    if(containsDigit(input)==1){

        printf("%s\n", "error");

    } else {

        if(compareLength(inputLen, compressLen)==1){

            printf("%s\n", input);
        }else{

            printf("%s\n", compress(input));
        }
    }
}


text:
Q: Pass data from one design tab to another tab I am using material design tabs as follows :
Following is my MainActivity.class :
 public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {

    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(this);
        tabLayout.setupWithViewPager(viewPager);

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        System.out.println("onPageSelected Called");
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

My ViewPagerAdapter is as follows :
    public class ViewPagerAdapter extends FragmentPagerAdapter {

    private static int count = 2;

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                 return new FragmentOne();
            case 1:
                return new FragmentTwo();
        }
        return null;
    }

    @Override
    public int getCount() {
        return count;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position)
        {
            case 0 :
                return "Tab One";
            case 1 :
                return "Tab Two";
        }
        return null;
    }
}

and here are my Fragments :
This is my first fragment name is FragmentOne :
    public class FragmentOne extends Fragment {

    private EditText editText;
    private Button btnSendData;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("IN FRAGMENT ONE");
        View view = inflater.inflate(R.layout.fragment_one,container,false);

        editText = (EditText) view.findViewById(R.id.et_name);
        btnSendData = (Button) view.findViewById(R.id.btn_send);

        btnSendData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                FragmentTwo fragment = new FragmentTwo();
                Bundle bundle = new Bundle();
                bundle.putString("username",editText.getText().toString());
                fragment.setArguments(bundle);
                getFragmentManager.beginTransaction.replace(R.id.frag_second,fragment).commit();

            }
        });

        return view;
    }
}

and here is another fragment with name FragmentTwo :
 public class FragmentTwo extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("IN FRAGMENT TWO");
        View view = inflater.inflate(R.layout.fragment_two,container,false);
        Bundle bundle = getArguments();
        if(bundle!= null)
        {
            String value = getArguments().getString("username");
        }
        return  view;
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("onResume gets called");
    }
}

In the second fragment i am getting data buts its adding another view with previous one.
see the image :

so I want to pass data from FragmentOne to FragmentTwo in two scenario :
1. I want to pass the data when i click on button and
2. When I swipe to FragmentTwo data should be passed
Also when I try to swipe to FragmentTwo nothing gets called in FragmentTwo ? why is it so ?
Also when I click to second tab nothing gets called .
Please help me how should i pass data to FragmentTwo on button click ?
following are layout files:
here is fragment_one
<LinearLayout
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:gravity="center"
       android:orientation="vertical">
           <EditText
               android:layout_marginLeft="16dp"
               android:layout_marginRight="16dp"
               android:id="@+id/et_name"
               android:hint="Username"

               android:layout_width="match_parent"
               android:layout_height="wrap_content"/>

           <Button
                android:padding="16dp"
                android:text="Send Data"
                android:layout_marginLeft="16dp"
                android:layout_marginRight="16dp"
                android:id="@+id/btn_send"
                android:layout_height="wrap_content"
                android:layout_width="match_parent"/>

and second fragment , fragment_second.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/second_frag"
android:gravity="center">
<TextView
    android:textSize="24sp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="Fragment Two"
    android:id="@+id/textView2" />

A: Each fragment is associated with the parent activity. so you can't directly communicate from one fragment to another fragment. You will need to go through Parent Activity using interface.
Check this docs : https://developer.android.com/training/basics/fragments/communicating.html
On button click pass the value to methods in your custom interface and access those methods in second fragment.

when I try to swipe to FragmentTwo nothing gets called in FragmentTwo

For this you need to implement fragment life cycle - https://developer.android.com/reference/android/app/Fragment.html
UPDATE
Done with some modification in you code, just look at the foll. code -
Manifex.xml
<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:theme="@style/Theme.AppCompat.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

MainActivity.java
package com.app.onkar.tabdemo;

import android.support.v4.app.Fragment;
import android.support.design.widget.TabLayout;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);

        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        adapter.addFragment(new FragmentOne(), "ONE");
        adapter.addFragment(new FragmentTwo(), "TWO");
        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(this);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        System.out.println("onPageSelected Called");
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    public static class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();
        private static int count = 2;

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    return new FragmentOne();
                case 1:
                    return new FragmentTwo();
            }
            return null;
        }

        @Override
        public int getCount() {
            return count;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Tab One";
                case 1:
                    return "Tab Two";
            }
            return null;
        }
    }
}

FragmentOne.java
package com.app.onkar.tabdemo;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class FragmentOne extends Fragment {
    private EditText editText;
    private Button btnSendData;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("IN FRAGMENT ONE");
        View view = inflater.inflate(R.layout.fragment_one,container,false);

        editText = (EditText) view.findViewById(R.id.et_name);
        btnSendData = (Button) view.findViewById(R.id.btn_send);

        btnSendData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                FragmentTwo fragment = new FragmentTwo();
                Bundle bundle = new Bundle();
                bundle.putString("username",editText.getText().toString());
                fragment.setArguments(bundle);
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.second_frag,fragment).commit();
            }
        });

        return view;
    }
}

FragmentTwo.java
package com.app.onkar.tabdemo;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FragmentTwo extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        System.out.println("IN FRAGMENT TWO");
        View view = inflater.inflate(R.layout.fragment_two,container,false);
        TextView txt2 = (TextView) view.findViewById(R.id.textView2);
        Bundle bundle = getArguments();
        if(bundle!= null)
        {
            String value = getArguments().getString("username");
            txt2.setText(value);
        }
        return  view;
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("onResume gets called");
    }

}

No change in Layout files. Just try above code - it is working exactly as you want. Hope it will help!
SCREENS

A: ViewPagerAdapter class
public class ViewPagerAdapter extends FragmentPagerAdapter {

private static int count = 2;

public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int position) {

switch (position) {
    case 0:
         Fragment fragmentone = new FragmentOne();
         Bundle args = new Bundle();
         args.putInt("code", 1);
         fragmentone.setArguments(args);
         return fragmentone;
    break;
    case 1:
        Fragment fragmenttwo = new FragmentTwo();
         Bundle args = new Bundle();
         args.putInt("code", 2);
         fragmenttwo.setArguments(args);
         return fragmenttwo ;
      break;
}
return null;
}

@Override
public int getCount() {
return count;
}

@Override
public CharSequence getPageTitle(int position) {
switch (position)
{
    case 0 :
        return "Tab One";
    case 1 :
        return "Tab Two";
}
return null;
}
}

args is the bundle object, you can put String int and other values to use these values in fragment use below code in onCreateView method of Fragment.
int codeForthisFragment = getArguments().getInt("code");

for button click:
      FragmentTransaction ft = getFragmentManager().beginTransaction();
                        Fragment secondFragment = new FragmentTwo();
                    Bundle args = new Bundle();
                    args.putInt("code", 2);
                    secondFragment.setArguments(args);
                    ft.replace(R.id.content_frame, secondFragment);
                    ft.commit();

A:
In the second fragment i am getting data buts its adding another view with previous one. see the image

With reference to the answer by @Roy Miller(https://stackoverflow.com/users/5255021/roy-miller),
you can solve it by doing the follwing changes:
In MainActivity.java ,replace the follwing switch:
 @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                return new FragmentOne();
            case 1:
                return new FragmentTwo();
        }
        return null;
    }

With:
@Override
public Fragment getItem(int position) {

    switch (position){
        case 0:
            return mFragmentList.get(0);
        case 1:
            return mFragmentList.get(1);
        case 2:
            return mFragmentList.get(2);
        default:
            return null;
    }

}

And then, in FragmentOne.java
Replace this:
btnSendData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FragmentTwo fragment = new FragmentTwo();
            Bundle bundle = new Bundle();
            bundle.putString("username",editText.getText().toString());
            fragment.setArguments(bundle);
            getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.second_frag,fragment).commit();
        }
    });

With:
btnSendData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

/*This one FragmentCollection is a Singleton class that contains list of fragments, set it during initialization itself(code is attached below this code)*/
FragmentCollection fragmentCollection=FragmentCollection.getInstance();

            FragmentTwo fragment = (FragmentTwo) FragmentCollection.getmFragmentList().get(2); //getting the second fragment

             fragment.setText(editText.getText().toString());  //add this method in fragment two

        }
    });

Now inside FragmentTwo.java
Add the method:
public void updateTextView(String data){
    Log.d("TabTwo","Update Text view");
    TextView txt = (TextView)view.findViewById(R.id.textView2);
    txt.setText(data);
}

At last, the singleton class i mentioned above:
public class FragmentCollection {
static FragmentCollection fragmentCollection=new FragmentCollection();
private final List<Fragment> mFragmentList = new ArrayList<>();
private FragmentCollection(){}
public static FragmentCollection getInstance(){
    if(fragmentCollection!=null) {
        return fragmentCollection;
    }else {
        return new FragmentCollection();
    }
}
public void setmFragmentList(List<Fragment> mFragmentList){
    this.mFragmentList.addAll(mFragmentList);
}
public List<Fragment> getmFragmentList(){
    return mFragmentList;
}
}

The issue of getting older views overlapping is because of initializing the fragment again and again
like new FragmentTwo(); in more than one place.
So here we put it in a list and access it so only a single fragment is altered.

A: I am not able to go to first fragment from Second fragment . I am using tab layout
This is my code
By clicking button from 2nd Fragment
            Bundle bundle = new Bundle();
            bundle.putString("uniqueList1", uniqueList.get(0));
            bundle.putString("uniqueList2", uniqueList.get(1));
            bundle.putString("kycUniquesNo", kycUniqueNum);
            CustBasicFormFragement fragObj = new CustBasicFormFragement();
            fragObj.setArguments(bundle);

In 1st Fragment
   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
     savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    binding = DataBindingUtil.inflate(inflater, R.layout.cust_basic_form_fragment, container, false);
    view = binding.getRoot();

    if (getArguments() != null) {
         string1 = getArguments().getString("uniqueList1");
         string2 = getArguments().getString("uniqueList2");
         kycUnique=getArguments().getString("kycUniquesNo");
        System.out.print(string1);
        System.out.print(string2);
        System.out.print(kycUnique);
    return view;

}


text:
Q: What is $\frac{\partial}{\partial x_1} [f(g(x_1,x_2))]$ in terms of components of $f$ and $g$?
Question: Let $f,g:\mathbb{R}^2 \to \mathbb{R}^2 $ be continously differentiable functions where $f\circ g$ is defined.
  Let
  $$f = (f_1,f_2)\quad\text{and}\quad g=(g_1,g_2)$$
  where all $f_1,f_2,g_1,g_2:\mathbb{R}^2\to\mathbb{R}$ are functions.
  What is
  $$\frac{\partial}{\partial x_1} [f(g(x_1,x_2))]?$$

I think the derivative should be a function from $\mathbb{R}^2$ to $\mathbb{R}^2$ as well.
Let $x =(x_1,x_2).$
By multivariate chain rule, we have
$$\frac{\partial}{\partial x_1} [f(g(x_1,x_2))] = \frac{\partial}{\partial x_1} [f(g_1(x),g_2(x))] =  \frac{\partial f}{\partial g_1} \cdot \frac{\partial g_1}{\partial x_1} + \frac{\partial f}{\partial g_2} \cdot \frac{\partial g_2}{\partial x_1}.$$
I am not sure whether the equation above is correct.
I notice that the multiplication in the RHS of the equation above is scalar multiplication.
This means that both
$$\frac{\partial f}{\partial g_1}\quad\text{and}\quad \frac{\partial f}{\partial g_2}$$
is a vector in $\mathbb{R}^2.$
But I do not understand its meaning.

A: Given a point $p\in{\mathbb R}^2$ the chain rule says that
$$d(f\circ g)(p)=df\bigl(g(p)\bigr)\circ dg(p)\ ,$$
in Jacobian matrix terms: $$J_{f\circ g}(p)=J_f(g(p)\bigr)\cdot J_g(p)\ .$$ This implies
$${\partial\over\partial x_1}(f\circ g)(p)=d(f\circ g)(p).e_1=\bigl(df\bigl(g(p)\bigr)\circ dg(p)\bigr).e_1=df\bigl(g(p)\bigr)\bigl(dg(p).e_1\bigr)\ .$$
Now $dg(p).e_1$ is the first column of the matrix $J_g(p)$; therefore we obtain
$${\partial\over\partial x_1}(f\circ g)(p)=\left[\matrix{f_{1.1}&f_{1.2}\cr f_{2.1}&f_{2.2}\cr}\right]_{g(p)}\left[\matrix{g_{1.1}\cr g_{2.1}\cr}\right]_p\ ,$$
where $f_{i.k}$ means that that the component $f_i$ of $f$ is partially differentiated with respect to $x_k$.


text:
Q: Tag folders/files in Linux and Windows I'm trying to create a simple bash script to copy a lot of files to another disk, like a backup. I know I can create a database to keep track of which files I already copied but I would like to know if there is a way to tag those files/folders, then I can just check: the tag=copied exist. If yes, just ignore it and go to the next file.
I'm just trying to find a better way to copy file/folders using the Operation System features instead of creating something myself.


text:
Q: Alternative to casting UTC Date in Javascript? I wish to create a new Date in JS, but have it be cast as UTC time. For example, suppose castAsUTC() produces the following desired effect:
var x = new Date('2019-01-01T00:00:00') // In local time (PST)
castAsUTC(x).toISOString(); // => '2019-01-01T00:00:00Z'
// x.toISOString() gives us '2019-01-01T08:00:00Z', which is undesired

Currently, my function looks like this:
function castAsUTC(date) {
  return new Date(x.toLocaleString() + '+00:00');
}

Is there a cleaner/nicer way of producing the same effect? Thanks in advance!
EDIT: To be more specific, I'm interested in transforming the date's timezone, without changing its actual value with as little arithmetic as possible. So calling .toISOString() will produce the same date as it is in local time.
I am currently using the moment-timezone library, but I can't seem to get the desired effect using that, either. I would definitely accept an answer that uses Moment.js

A: You can switch a Moment instance to UTC using the utc function. Then just use format to get whatever the specific output you want from it.

A: tl;dr;
You formatted the date wrong.  Add the letter "Z" to the end of your date string and it will be treated as UTC.
var x = new Date('2019-01-01T00:00:00Z')    // Jan 1, 2019 12 AM UTC

These formatting issues are easier to manage with a library like momentjs (utc and format functions) as described in other answers.  If you want to use vanilla javascript, you'll need to subtract out the timezone offset before calling toISOString (see warnings in the longer answer below).
Details
Date in javascript deals with timezones in a somewhat counter intuitive way.  Internally, the date is stored as the number of milliseconds since the Unix epoch (Jan 1, 1970).  That's the number you get when you call getTime() and it's the number that's used for math and comparisons.
However - when you use the standard string formatting functions (toString, toTimeString, toDateString, etc) javascript automatically applies the timezone offset for the local computers timezone before formatting.  In a browser, that means it will apply the offset for the end users computer, not the server.  The toISOString and toUTCString functions will not apply the offset - they print the actual UTC value stored in the Date.   This will probably still look "wrong" to you because it won't match the value you see in the console or when calling toString.
Here's where things really get interesting.  You can create Date's in javascript by specifying the number of milliseconds since the Unix epoch using new Date(milliseconds) or by using a parser with either new Date(dateString).  With the milliseconds method, there's no timezone to worry about - it's defined as UTC.   The question is, with the parse method, how does javascript determine which timezone you intended?  Before ES5 (released 2009) the answer was different depending on the browser!  Post ES5, the answer depends on how you format the string!  If you use a simplified version of ISO 8601 (with only the date, no time), javascript considers the date to be UTC.  Otherwise, if you specify the time in ISO 8601 format, or you use a "human readable" format, it considers the date to be local timezone.  Check out MDN for more.
Some examples.  I've indicated for each if javascript treats it as a UTC or a local date.  In UTC, the value would be Jan 1, 1970 at midnight.  In local it depends on the timezone.  For OP in pacfic time (UTC-8), the UTC value would be Jan 1, 1970 at 8 AM.
new Date(0)                    // UTC (milliseconds is always UTC)
new Date("1/1/1970");          // Local - (human readable string)
new Date("1970-1-1");          // Local (invalid ISO 8601 - missing leading zeros on the month and day)
new Date("1970-01-01");        // UTC (valid simplified ISO 8601)
new Date("1970-01-01T00:00");  // Local (valid ISO 8601 with time and no timezone)
new Date("1970-01-01T00:00Z"); // UTC (valid ISO 8601 with UTC specified)

You cannot change this behavior - but you can be pedantic about the formats you use to parse dates.  In your case, the problem was you provided an ISO-8601 string with the time component but no timezone.  Adding the letter "Z" to the end of your string, or removing the time would both work for you.
Or, always use a library like momentjs to avoid these complexities.
Vanilla JS Workaround
As discussed, the real issue here is knowing whether a date will be treated as local or UTC.  You can't "cast" from local to UTC because all Date's are UTC already - it's just formatting.  However, if you're sure a date was parsed as local and it should really be UTC, you can work around it by manually adjusting the timezone offset.  This is referred to as "epoch shifting" (thanks @MattJohnson for the term!) and it's dangerous.  You actually create a brand new Date that refers to a different point in time!  If you use it in other parts of your code, you can end up with incorrect values!
Here's a sample epoch shift method (renamed from castAsUtc for clarity).  First get the timezone offset from the object, then subtract it and create a new date with the new value.  If you combine this with toISOString you'll get a date formatted as you wanted.
function epochShiftToUtc(date) {
    var timezoneOffsetMinutes = date.getTimezoneOffset();
    var timezoneOffsetMill = timezoneOffsetMinutes * 1000 * 60;
    var buffer = new Date(date.getTime() - timezoneOffsetMill);

    return buffer;
}

epochShiftToUtc(date).toUTCString();

A: If indeed the string you have is like the one shown, then the easiest thing to do would be to append a Z to indicate UTC.
var input = '2019-01-01T00:00:00';
var date = new Date(input + 'Z');
var output = date.toISOString();

Or, if you would like to use Moment.js, then do this:
var input = '2019-01-01T00:00:00';
var m = moment.utc(input);
var output = m.format();

You do not need moment-timezone for this.


text:
Q: how can i check if my activity is partially visible not completely? I have two activities A and B.A is app type activity and B is dialog type.when A is in foreground and B is called A goes to foreground and it's onPause is called but not onStop. so is there a way if i get to know in my onPause if my activity is partially visible not completely visible ?

A: When your activity is visible and if any other dialog opens then your activity will be Pause  and onPause() method of the activity will be called. If your activity is completely invisible then onStop() method of the activity will be called.


text:
Q: Redshift Dynamic cases I have a table that I would like to pivot using cases in Redshift.
CREATE TABLE SurveyResponses (
    id int,
    question varchar(255),
    answer varchar(255)
);

INSERT INTO SurveyResponses (id, question, answer)  values (1, 'Dummy question 1', 'responseX');
INSERT INTO SurveyResponses (id, question, answer)  values (2, 'Dummy question 1', 'responseY');
INSERT INTO SurveyResponses (id, question, answer)  values (3, 'Dummy question 1', 'responseZ');
INSERT INTO SurveyResponses (id, question, answer)  values (4, 'Dummy question 2', 'responseA');
INSERT INTO SurveyResponses (id, question, answer)  values (5, 'Dummy question 2', 'responseB');
INSERT INTO SurveyResponses (id, question, answer)  values (6, 'Dummy question 3', 'responseC');

I tried the following case approach which does not work. I get repeated rows.
Select id,
Case
When question = 'Dummy question 1' then answer Else '' End as question_1,
Case
When question = 'Dummy question 2' then answer Else '' End as question_2,
Case
When question = 'Dummy question 3' then answer Else '' End as question_3
FROM SurveyResponses;

ID
QUESTION_1
QUESTION_2
QUESTION_3

1
responseX
-
-

2
responseY
-
-

3
responseZ
-
-

4
-
responseA
-

5
-
responseB
-

6
-
-
responseC

1
responseX
-
-

2
responseY
-
-

3
responseZ
-
-

4
-
responseA
-

5
-
responseB
-

6
-
-
responseC

1
responseX
-
-

2
responseY
-
-

3
responseZ
-
-

4
-
responseA
-

5
-
responseB
-

6
-
-
responseC

Also, in my real table, I will have 5000+ questions. I would not like to write the case statement for every question. Also, I wanted my column name to be the question text.
Could someone help me in making it Dynamic?


text:
Q: What happens to a Trader in production if I lose Trade Route capacity? I know that it isn't possible to start production of a Trader if you don't have enough Trade Route capacity, but what happens if I'm already producing a Trader when I lose the capacity?
I'd like to know if the production continues and if it doesn't, if the spent production is lost or if it carries over. Based on what I've read elsewhere, excess traders become idle and can't establish trade routes until the capacity is increased, but that's for existing traders and not for traders in production.
To give you some context, I'm currently running a Merchant Republic and I'm considering switching to Monarchy, because most of my cities are short on housing and most of them have walls.

A: From personal experience, as this happens quite a lot in the newest expansion. The trader will still be created but you can not send it anywhere. The best thing to do is to let the trader sleep until you get another trade route, just remember that you have one.
From the fandom wiki:

Each Trader services one Trade Route. For this reason, when the number of traders reaches the trading capacity you can't build more Traders. Still, there are exceptional situations in which the number of Traders can exceed the trading capacity. This happens when your Trading Capacity suddenly decreases below the number of Traders you have. Trading Capacity may decrease for example in vanilla Civilization VI when you change governments from Merchant Republic to something else (which reduces your Trading Capacity by 2); or when you lose cities with commercial infrastructure. All the Trade Routes that were active when the decrease in Trading Capacity happened remain active. This means that the number of Trade Routes can actually exceed the Trading Capacity for a few turns. However, the next Trader (or Traders) to finish a Trade Route will be unable to start a new route and will be forced to stay inactive. They will recover their ability to create Trade Routes once you increase your Trading Capacity again.


text:
Q: Can I use ExtJS table layout for this? I want to put five textareafield components into a container such that they fill the whole container:
    33%       33%       33%
+---------+---------+---------+
|         |         |         | 50%
|         |         |         |
|         +---------+---------+
|         |         |         | 50%
|         |         |         |
+---------+---------+---------+

Is there any better layout to use than two vbox containers inside a hbox container?
This looks more like a tabular layout. But how can I tell textareas to fill the whole screen inside a table layout, and the table columns that they should take 33% width?

A: I would use a main box container with three panels inside, one fit and two vbox, always setting flex:1.
Look, you could use a table layout but that would be better if you knew the exact dimension of every container inside your table, if you want to work with proportions, hbox, fit a and vbox is the best way (That is why they are there).
Ext.define('Fiddle.view.MyPanel', {
        extend: 'Ext.panel.Panel',

        requires: [
            'Ext.panel.Panel',
            'Ext.form.field.TextArea'
        ],

        height: 400,
        width: 600,
        title: 'My textarea table',

        layout: {
            type: 'hbox',
            align: 'stretch'
        },
        items: [
            {
                xtype: 'panel',
                flex: 1,
                layout: 'fit',
                items: [
                    {
                        xtype: 'textareafield',
                        fieldLabel: 'Label'
                    }
                ]
            },
            {
                xtype: 'panel',
                flex: 1,
                layout: {
                    type: 'vbox',
                    align: 'stretch'
                },
                items: [
                    {
                        xtype: 'textareafield',
                        flex: 1,
                        fieldLabel: 'Label'
                    },
                    {
                        xtype: 'textareafield',
                        flex: 1,
                        fieldLabel: 'Label'
                    }
                ]
            },
            {
                xtype: 'panel',
                flex: 1,
                layout: {
                    type: 'vbox',
                    align: 'stretch'
                },
                items: [
                    {
                        xtype: 'textareafield',
                        flex: 1,
                        fieldLabel: 'Label'
                    },
                    {
                        xtype: 'textareafield',
                        flex: 1,
                        fieldLabel: 'Label'
                    }
                ]
            }
        ]

    });

    Ext.create('Fiddle.view.MyPanel',{
        renderTo: Ext.getBody()
    });


text:
Q: What is the logical way of querying for Rooms in Firebase I am not sure if I'm asking this question the right way, but I'll try to explain.
So I am making a mobile application in which a user can create a room with the credentials roomname and roompassword:

*

*get the roomname and the roompassword from a Form

*create a document with the given roomname: /rooms/roomname/users/uid/. If roomname exists, don't create the room.

And a user can enter a room like this:

*

*get the roomname and the roompassword from a Form

*query if roomname document exists in /rooms collection, check if password field matches with the roompassword you get from the form, if true, add the user to room.

So I am wondering if I should keep the roomname automatically generated and create a field called roomname that I can query, or the way I do it is fine? Also security is not a priority.

A: I think using the room name as a field or as an identifier is the same thing. It depends on how you want to handle your code. Because if the roomname is a field then you'll have to loop through the all the rooms and check for the room field == to the one you want the user to enter. However, if the roomname is the key, then all you do is get it from room list and compare. But i usually try to avoid the automatically generated stuff, they make disasters.
wish you good luck


text:
Q: Intercept all JDBC calls using AspectJ within a request scope and returning as response I am having trouble implementing a query profiler for my dataservice (Spring boot application) for debugging purpose. Any help would be appreciated.
Problem statement:
I need to return all the database queries being executed for a particular endpoint along with response.
My approach:
I have created a request scope component and autowired in the aspect, populating the queries in the request scope object and injecting it with the response. I have provided all the files required below.
Issue:
Some of the endpoints execute query in multiple threads. I was getting error but was able to fix the errors using simpleThreadScope. However I am not able to see any of the queries executed by threads (I can see queries executed outside threads). Could you help me get queries executed inside thread in the response as well?
AspectJ configuration:
<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <executions>
                <execution>
                    <id>default-compile</id>
                    <phase>none</phase>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.7</version>
            <configuration>
                <aspectDirectory>aspect</aspectDirectory>
                <complianceLevel>1.8</complianceLevel>
            </configuration>
            <dependencies>
                <dependency>
                    <groupId>org.aspectj</groupId>
                    <artifactId>aspectjtools</artifactId>
                    <version>1.8.10</version>
                    <scope>compile</scope>
                </dependency>
            </dependencies>
            <executions>
                <execution>
                    <!-- Compile and weave aspects after all classes compiled by javac -->
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

Aspect:
@Aspect
@Component
public class QueryProfilerAspect {
    private static final Logger logger = LoggerFactory
            .getLogger(QueryProfilerAspect.class);
    private static String TIME_FORMAT = "HH:mm:ss.SSS";
    private static String QUERY_PROFILER = "QueryProfiler";

    @Autowired
    QueryProfile queryProfile;

    @Pointcut("(call(* org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations.query*(..)) && args(query,params,..))")
    public void anyJDBCOperations(String query, Map params) {
    }

    @Pointcut("execution(* *(..)) && @annotation(org.springframework.web.bind.annotation.PostMapping) || @annotation(org.springframework.web.bind.annotation.PutMapping) || @annotation(org.springframework.web.bind.annotation.DeleteMapping) || @annotation(org.springframework.web.bind.annotation.GetMapping)")
    private void anyGetPutPostDeleteMappingMethodPointCut() {
        // pointcut
    }

    @Pointcut("execution(* *(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    private void anyRequestMappingMethodPointCut() {
        // pointcut
    }

    @Around("anyJDBCOperations(sqlQuery, params)")
    public Object log(ProceedingJoinPoint jp, String sqlQuery, Map params)
            throws Throwable {
            long start = System.currentTimeMillis();
            Object output = jp.proceed();
            long elapsedTime = System.currentTimeMillis() - start;

            DataSource dataSource = ((JdbcTemplate) ((NamedParameterJdbcOperations) jp
                    .getTarget()).getJdbcOperations()).getDataSource();

            if (params instanceof Map && !params.isEmpty()) {
                logger.debug("inside instance of MAP!!!! ::param {}", params);
                sqlQuery = replaceMap(sqlQuery, (Map<?, ?>) params);
            }

            queryProfile.getQuery().add(sqlQuery);
            logger.info("Intercepted Query is::: {}", sqlQuery);
            return output;
    }

    @AfterReturning(value = "anyRequestMappingMethodPointCut() || anyGetPutPostDeleteMappingMethodPointCut()", returning = "returnVal")
    public void anyPublicControllerMethod(JoinPoint jp,
            ResponseEntity returnVal)
            throws Throwable {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                    .currentRequestAttributes()).getRequest();

            QueryProfile qp = new QueryProfile(queryProfile);
            qp.setRequestURL(request.getRequestURL().toString());
            qp.setHostName(getHostName());

            Object responseBody = returnVal.getBody();
            if (responseBody instanceof ResponseDTO) {
                List<QueryProfile> profileList = new ArrayList<>();
                if (((ResponseDTO) responseBody).getMeta().get(QUERY_PROFILER)
                        != null) {
                    profileList.add((QueryProfile) ((ResponseDTO) responseBody)
                            .getMeta().get(QUERY_PROFILER));
                }
                profileList.add(qp);
                ((ResponseDTO) responseBody)
                        .addMeta(QUERY_PROFILER, profileList);
            }
    }
}

Request Scope object:
@Component
@Scope(value = "simpleThreadScope", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class QueryProfile {
    private String hostName;
    private String requestURL;
    private Long duration;
    private String time;
    private String dataSource;
    private List<String> query = new ArrayList<>();

    public QueryProfile() {
        //Default constructor
    }

    public QueryProfile(QueryProfile qp) {
        setHostName(qp.getHostName());
        setRequestURL(qp.getRequestURL());
        setDataSource(qp.getDataSource());
        setDuration(qp.getDuration());
        setTime(qp.getTime());
        setQuery(qp.getQuery());
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public String getRequestURL() {
        return requestURL;
    }

    public void setRequestURL(String requestURL) {
        this.requestURL = requestURL;
    }

    public Long getDuration() {
        return duration;
    }

    public void setDuration(Long duration) {
        this.duration = duration;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getDataSource() {
        return dataSource;
    }

    public void setDataSource(String dataSource) {
        this.dataSource = dataSource;
    }

    public List<String> getQuery() {
        return query;
    }

    public void setQuery(List<String> query) {
        this.query = query;
    }
}

SimpleTheradScope configuration:
@Configuration
public class MainConfig implements BeanFactoryAware {

    private static final Logger logger = LoggerFactory.getLogger(MainConfig.class);

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        if (beanFactory instanceof ConfigurableBeanFactory) {

            logger.info("MainConfig is backed by a ConfigurableBeanFactory");
            ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) beanFactory;

            /*Notice:
             *org.springframework.beans.factory.config.Scope
             * !=
             *org.springframework.context.annotation.Scope
             */
            org.springframework.beans.factory.config.Scope simpleThreadScope = new SimpleThreadScope();
            cbf.registerScope("simpleThreadScope", simpleThreadScope);

            /*why the following? Because "Spring Social" gets the HTTP request's username from
             *SecurityContextHolder.getContext().getAuthentication() ... and this
             *by default only has a ThreadLocal strategy...
             *also see http://stackoverflow.com/a/3468965/923560
             */
            SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
        }
        else {
            logger.info("MainConfig is not backed by a ConfigurableBeanFactory");
        }
    }
}

My thread executor class: in the class, I am creating a list of Runnable tasks (that call DAO method to execute queries) and calling below class method to execute them in parallel.
public class ThreadUtils {
    protected static final Logger logger = LoggerFactory
            .getLogger(ThreadUtils.class);

    public static void executeInParallel(List<Runnable> runnableTasks) {
        ExecutorService executorService = new DelegatingSecurityContextExecutorService(
                Executors.newFixedThreadPool(5),
                SecurityContextHolder.getContext());

        CompletableFuture<?>[] futures = runnableTasks.stream()
                .map(task -> CompletableFuture.runAsync(task, executorService))
                .toArray(CompletableFuture[]::new);
        CompletableFuture.allOf(futures).join();
        executorService.shutdown();
    }

My response is as:
"data":{},
"meta": {
        "QueryProfiler": [
            {
                "hostName": "xxx.xx.com",
                "requestURL": "http://localhost:7010/abc/5",
                "duration": null,
                "time": null,
                "dataSource": null,
                "query": [
                    "SELECT * FROM table1",
                    "SELECT COUNT(1) FROM table2 WHERE abc = 1 AND def = 2"
                ]
            }
        ]
    }

A: I found solution to my problem by ditching the request scope object and implementing InheritableThreadLocal. This variable has the property of delegating the context to its child thread as well. so using a InheritableThreadLocal variable in my aspect and adding queries to the variable, I was able to inject the variable while returning the response.
Along with the above code, I added the following code to make it work:
private static InheritableThreadLocal<QueryProfile> queryProfile = new InheritableThreadLocal<>();
public static QueryProfile getQueryProfile(){
    if(queryProfile.get() == null){
        queryProfile.set(new QueryProfile());
        logger.info("Profiler is null. Setting with new value");
    }
    return queryProfile.get();
}
public static void setQueryProfile(QueryProfile qp){
    queryProfile.set(qp);
}

A: You can use Spring Boot DataSource Decorator for tracing database calls. You can integrated it with P6spy. P6Spy is a framework that enables database data to be seamlessly intercepted and logged with no code changes to existing application.
https://github.com/gavlyukovskiy/spring-boot-data-source-decorator
https://github.com/p6spy/p6spy
This framework is well defined and you don't need to do anything with application.


text:
Q: Passing AD authentication credentials to IE browser in C# Windows Form I have a Sharepoint site and I want to open this site in IE by using C# Windows Application. I successfully open the site in IE but my question is how do I send the UserCredentials to the site. It opens the site in IE with defalut credentials.
My defalut credentials are username: systemaccount password=123
but i want to open Sharepoint site in IE with some different credentials like username: abc password: 123 (I have "abc" as a AD and Sharepoint User)
here is my code for opening Sharepoint site in IE
SecureString sec = new SecureString();
             sec.AppendChar('1');
             sec.AppendChar('2');
             sec.AppendChar('3');

Process.Start("IEXPLORE.EXE", url,"abc",sec,"moss.local");

here is my Sharepoint site URL.......
abc is my username by which i want to login
sec is a password SecureString password
moss.local is my domain where "abc" AD user exists.....

A: Try this, it seems to be working for me and "user" gets to access the site, not the logged in one:
ProcessStartInfo startInfo = new ProcessStartInfo(@"c:\Program Files\Internet Explorer\iexplore.exe", "http://server/sites/spsite/page.aspx");
startInfo.UserName = @"user";
SecureString p = new SecureString();
p.AppendChar('p');
p.AppendChar('w');
p.AppendChar('d');
startInfo.Password = p;
startInfo.Domain = "mydomain";
startInfo.UseShellExecute = false;
Process.Start(startInfo);


text:
Q: TypeError: 'fn' must be callable (Prefect - Python) I'm starting to leart some prefect + python and I'm facing a strange error at the very beginning with a very easy script:

I have already tried it in two diferents PC.

A: It looks like you've installed Prefect 2, but are following instructions for Prefect 1.
I recommend starting with the first steps tutorial in the Prefect docs: https://docs.prefect.io/tutorials/first-steps/

A: the way with statements work is that the variable you're defining only exists within the indented code block underneath the with statement itself. The end of your code should be:
with Flow("prueba 1") as flow:
    carga()
    flow.run()


text:
Q: UWP CompactOverlay Mode (Picture-inPicture) IsViewModeSupported Exception Currently i'm testing the new CompactOverlay Mode, but there seems to be a Problem, when running the app not on the Creators Update (e.g. Anniversary Update). Here is a simplified Piece of Code
// Check if it is supported
if (ApplicationView.GetForCurrentView().IsViewModeSupported(ApplicationViewMode.CompactOverlay))
{
  // Supported
}
else
{
  // Not supported
}

But this gives me an exception, on versions of Windows before Creators Update:
System.InvalidCastException: 'Unable to cast object of type 'Windows.UI.ViewManagement.ApplicationView' to type 'Windows.UI.ViewManagement.IApplicationView4

Is this a bug, or do i need to check against something other?

A: This is expected. The API is new in the Creators Update and therefore won't work on earlier versions of the OS. The IsViewModeSupported API will tell you if the device you are running on (PC, phone, xbox, etc.) supports the respective viewmode. Before you can make that this check you should first check that the viewmode API itself is there. You can do this with the following APIs


text:
Q: Short story about a man in a synthetic body on Mars It was a short story about an old man who transfers his consciousness to a synthetic body, moves to Mars and falls in love with another robot. The female robot eventually chooses to die and the man is depressed. He is effectively immortal and I remember the story ending at the death of the universe. The old man also became some sort of scientist and invented FTL travel, I think. It wasn't a conventionally published story but posted on a blog, still it was very popular.
I remember reading this about 2-3 years ago. I think it had a name like 'traveler' or 'journeyman'; essentially something to do with traveling. I'd be grateful for any help. Thanks!

A: The Journeyman by Leon de la Garza (2015), also appeared on Reddit two days later, posted by u/Writes_Sci_Fi
Below are quotes from the story that match your description:
old man who transfers his consciousness to a synthetic body

"Oh well… I've been hearing that the only option for us old folk are the synthetics. If I had a choice I think I would have gotten the organic, but the synthetic will do."

moves to Mars

He left Earth and never went back, and though the ride to Mars was comfortable he noticed the stares from the other passengers, the organics.

falls in love with another robot.

Paul walked alongside Loren, the silver synthetic that had saved him from his wandering trance, to the city of Mars One.

The female robot eventually chooses to die

With a quick motion she slid her memory module out of place and Paul watched it drop next to her. The body that previously belonged to Loren became stiff, its eyes lost their glow and it fell to side of the mountain.

The old man also became some sort of scientist and invented FTL travel,

Paul discovered intergalactic travel and he left them all behind.

the story ending at the death of the universe.

For the first time in fifty billion years Paul looked at the sky above him and saw only darkness. On the other side of the world he inhabited, the last star of the universe shined.


text:
Q: How to assign the caps lock key to right-click in Windows? In my opinion this is the best use for the otherwise completely useless caps lock key (in my opinion). How can it be done in Windows?

A: It does not seem like there is any way to transparently remap keyboard events into mouse events.
But, you can make it work almost the same. Install SharpKeys, and add following keyboard mapping:
Special: Capslock (00_3A) => Special: Application (E0_5D)

(you will need to logoff and logon again).
This will make Capslock to work the same as right Menu key, which for most intents and purposes does the same job as mouse right click, or calling object properties.


text:
Q: WordPress DO i need an exit() after redirecting a url I have a gateway plugin and I added the code below to redirect the customer to a custom page when the payment fails.
My question is, do I need to add exit(); after the end of the redirect_url which is inside the if statement?
I have seen some codes with exit and some without.
else {
        //failed
        $this->msg['class'] = 'error';
        $this->msg['message'] = __( "Your Transaction Has Failed Due to Some Technical Error. Please Try Again.

", 'toBeTranslatd');
        $order->update_status('failed');
        $order->add_order_note('Failed');
        $order->add_order_note($this->msg['message']);
        $redirect_url = home_url( '/payment-faild/' );

        $lang_code = get_post_meta( $order_id, 'wpml_language', true );
        if ( $lang_code === ar ) {
            $redirect_url = apply_filters( 'wpml_permalink', $redirect_url, $lang_code );
            //exit(); // Do I need this or delete it?
        }
}

A: Wordpress provides two functions for this:

*

*wp_redirectDoc

and

*

*wp_safe_redirectDoc

And here's what wordpress recommends:

Note: wp_redirect() and wp_safe_redirect() do not exit automatically, and should almost always be followed by a call to exit;

A: wp_redirect() or wp_safe_redirect() does not exit or die automatically, and should almost always be followed by a call to exit or die();
Reference : https://developer.wordpress.org/reference/functions/wp_redirect
Thank you.