text:
Q: How to calculate recursive datetime in sql? i want to calculate an expiry date using open_dt column from a table, for example if the open_dt is '2010-08-02 00:00:00.000' the expiry date should be '2014-08-02 00:00:00.000'.
so with open_dt i should keep adding 2 to the year and the expiry date should be less than the getdate().
i tried using CTE but it just calculates for only one loop. for example for open_dt '2010-08-02 00:00:00.000' it shows the result as '2012-08-02 00:00:00.000'
WITH Test (CUSTOMER,OPENED,EXPIRED)
as
(

select  A.CUSTOMER_NO,A.OPENED_DT, DATEADD(YEAR,2, max(A.OPENED_DT)) as EXPIRED
  from ACCOUNTS_MASTER A GROUP BY  A.CUSTOMER_NO , A.OPENED_DT
  union all
  select  CUSTOMER,OPENED, DATEADD(YEAR,2, EXPIRED)
  from Test T

  )
  select  CUSTOMER,OPENED, EXPIRED
  from Test T

I couldn't figure out Please help

A: I would not use a recursive CTE here, don't be sucked in by their syntactic sugar, they are little better than a while loop or a cursor, which people are a lot faster to condemn. There are very few scenarios (if any) that do not involve hierarchical data where a recursive CTE is going to be the right solution.
Here, you probably only need a small set of numbers, assuming you won't have more than 100 years worth of data you need 50 rows, which you can get using a couple of simple table valued constructors and cross joining them, finally ROW_NUMBER() will give you your sequence:
SELECT ROW_NUMBER() OVER(ORDER BY N1.N)
FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS n1 (N)
    CROSS JOIN (VALUES(1),(1),(1),(1),(1)) AS n2 (N);

Now you can join your set of numbers to your table to get your 2 year intervals for the expiry date:
WITH Numbers (Number) AS
(   SELECT ROW_NUMBER() OVER(ORDER BY N1.N) - 1
    FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS n1 (N)
        CROSS JOIN (VALUES(1),(1),(1),(1),(1)) AS n2 (N)
)
SELECT  am.Customer_No,
        am.Opened_Dt,
        Expired = DATEADD(YEAR, n.Number * 2, Opened_Dt)
FROM    Accounts_Master AS am
        CROSS JOIN Numbers AS n;

This will of course give you 50 rows for each record, spanning 100 years after Opened_Dt, which is not required, so you need to filter the results to where the next expiry date is in the future, and the current one is in the past:
WITH Numbers (Number) AS
(   SELECT ROW_NUMBER() OVER(ORDER BY N1.N) - 1
    FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS n1 (N)
        CROSS JOIN (VALUES(1),(1),(1),(1),(1)) AS n2 (N)
)
SELECT  am.Customer_No,
        am.Opened_Dt,
        Expired = DATEADD(YEAR, n.Number * 2, Opened_Dt)
FROM    Accounts_Master AS am
        CROSS JOIN Numbers AS n
WHERE   DATEADD(YEAR, n.Number * 2, Opened_Dt) <= GETDATE()
AND     DATEADD(YEAR, (n.Number * 2) + 2, Opened_Dt) > GETDATE()

FULL WORKING EXAMPLE
WITH Numbers (Number) AS
(   SELECT ROW_NUMBER() OVER(ORDER BY N1.N) - 1
    FROM (VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) AS n1 (N)
        CROSS JOIN (VALUES(1),(1),(1),(1),(1)) AS n2 (N)
)
SELECT  am.Customer_No,
        am.Opened_Dt,
        Expired = DATEADD(YEAR, n.Number * 2, Opened_Dt)
FROM    (VALUES
            (1, CAST('2010-08-02' AS DATE)),
            (2, CAST('2013-04-27' AS DATE)),
            (3, CAST('2013-08-24' AS DATE)),
            (4, CAST('2015-03-19' AS DATE))
        ) AS am (Customer_no, Opened_dt)
        CROSS JOIN Numbers AS n
WHERE   DATEADD(YEAR, n.Number * 2, Opened_Dt) <= GETDATE()
AND     DATEADD(YEAR, (n.Number * 2) + 2, Opened_Dt) > GETDATE()
ORDER BY Customer_No;

Example results:
Customer_No Opened_Dt       Expired
--------------------------------------
1           2010-08-02      2014-08-02
2           2013-04-27      2015-04-27
3           2013-08-24      2013-08-24
4           2015-03-19      2015-03-19

For further reading on the poor scalability of recursive CTEs see the following series:

*

*Generate a set or sequence without loops – part 1

*Generate a set or sequence without loops – part 2

*Generate a set or sequence without loops – part 3

A: Return the row with the earliest date in the set
Set that date as "current"
Find the row with the earliest date more than "90" days after the current date
Repeat from step 2 until no more rows are found
LINK for more details and information

A: As noted in the answer by GarethD recursion is not needed and might not be the best option. The different solutions produces the same result but the recursive performs a bit worse.
But anyway, for clarity, here is the recursive solution that finds the date that fulfills the two conditions: opened_dt + 2 years and less than todays date.
;WITH Test (CUSTOMER, OPENED, EXPIRED)
AS (
    SELECT A.CUSTOMER_NO, A.OPENED_DT, A.OPENED_DT AS EXPIRED
    FROM ACCOUNTS_MASTER A
    UNION ALL
    SELECT CUSTOMER, OPENED, DATEADD(YEAR,2, EXPIRED)
    FROM TEST T
    WHERE DATEADD(YEAR,2, EXPIRED) <= GETDATE() -- limiting condition that stops recursion
   )

SELECT CUSTOMER, OPENED, MAX(EXPIRED) EXPIRED
FROM TEST
GROUP BY CUSTOMER, OPENED
ORDER BY CUSTOMER;

This would generate a result like:
CUSTOMER    OPENED      EXPIRED
1           2010-08-02  2014-08-02
2           2013-04-27  2015-04-27
3           2013-08-24  2013-08-24
4           2015-03-19  2015-03-19

Note that all expired stops at the current date and never happens in the future - this might be what you want or not - the question was a bit unclear.


text:
Q: C#: .NET HttpClient times out too fast I have a long list of API URL calls in urlList each of them returning quite an amount of JSON data.   Some of these take milliseconds, others may well take several minutes to complete. That's why I set the timeout to 30 minutes. For some reason the HttpClient instance times out after just 5 minutes and I have no idea why. When I open the same URLs in a browser window or in Postman it takes between 8 and 20 minutes, but they will eventually load while my C# code (see below) throws these exceptions:

For some of the URLs I then get a CanceledException: Task
CanceledException - System.Threading.Tasks.TaskCanceledException: A
task was canceled.     at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)     at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)     at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at ...

private async Task<string> ProcessUrls(urlList)
{
    string userAndPasswordToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password);
    ServicePointManager.ServerCertificateValidationCallback += this.ValidateRemoteCertificate;
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    this.httpclient.DefaultRequestHeaders.Accept.Clear();
    this.httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    this.httpclient.Timeout = TimeSpan.FromMinutes(30);
    this.httpclient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization",$"Basic {userAndPasswordToken}");

    SemaphoreSlim throttler = new SemaphoreSlim(initialCount: 20);
    List<Task> requests = new List<Task>();
    foreach (var url in urlList)
    {
        await throttler.WaitAsync();
        requests.Add(
            Task.Run(async () =>
            {
                try
                {
                    result = await this.httpclient.GetAsync(url);
                }
                finally
                {
                    throttler.Release();
                }
            }
            )
        );
    }
}

UPDATE: I tried the same thing without the Semaphore, still, the same problem occurs - So I guess I can rule out that the Semaphore causes the issue.
What am I missing here? (Note: The APIs I am accessing are not under my control)
This is a .NET project (targetFramework net452), currently running in VS2019 on Win10.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error inflating class paths - while running zxing for barcode scanning in my own project I have integrated awesome zxing barcode project in my own project and I am calling it through intent. I don't want user to install one more app for barcode scanning. Completely copied the source code zxing-2.3.0 into my project and resolved all the build errors.
Now that when I am running my app and when it reaches a point where it has to execute barcode scanning app crashes with below errors.

Before posting this question I have researched a lot on this but could not find any solution which could solve my problem. Thank you all in advance.

    12-26 18:49:51.387: E/AndroidRuntime(26353): FATAL EXCEPTION: main
    12-26 18:49:51.387: E/AndroidRuntime(26353): Process: com.arrisi.selfinstall, PID: 26353
    12-26 18:49:51.387: E/AndroidRuntime(26353): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arrisi.selfinstall/com.google.zxing.client.android.CaptureActivity}: android.view.InflateException: Binary XML file line #110: Error inflating class paths
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.app.ActivityThread.access$800(ActivityThread.java:139)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.os.Handler.dispatchMessage(Handler.java:102)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.os.Looper.loop(Looper.java:136)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.app.ActivityThread.main(ActivityThread.java:5086)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at java.lang.reflect.Method.invokeNative(Native Method)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at java.lang.reflect.Method.invoke(Method.java:515)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at dalvik.system.NativeStart.main(Native Method)
    12-26 18:49:51.387: E/AndroidRuntime(26353): Caused by: android.view.InflateException: Binary XML file line #110: Error inflating class paths
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.preference.GenericInflater.createItemFromTag(GenericInflater.java:441)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.preference.GenericInflater.rInflate(GenericInflater.java:481)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.preference.GenericInflater.inflate(GenericInflater.java:326)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.preference.GenericInflater.inflate(GenericInflater.java:263)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:272)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.preference.PreferenceManager.setDefaultValues(PreferenceManager.java:485)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.preference.PreferenceManager.setDefaultValues(PreferenceManager.java:444)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at com.google.zxing.client.android.CaptureActivity.onCreate(CaptureActivity.java:145)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.app.Activity.performCreate(Activity.java:5248)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    ... 11 more
    12-26 18:49:51.387: E/AndroidRuntime(26353): Caused by: java.lang.ClassNotFoundException: Didn't find class "android.preference.paths" on path: DexPathList[[zip file "/data/app/com.arrisi.selfinstall-1.apk"],nativeLibraryDirectories=[/data/app-lib/com.arrisi.selfinstall-1, /vendor/lib, /system/lib]]
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at java.lang.ClassLoader.loadClass(ClassLoader.java:497)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at java.lang.ClassLoader.loadClass(ClassLoader.java:457)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.preference.GenericInflater.createItem(GenericInflater.java:375)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.preference.GenericInflater.onCreateItem(GenericInflater.java:417)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    at android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428)
    12-26 18:49:51.387: E/AndroidRuntime(26353):    ... 21 more

below is the code segment where it is crashing once intent is invoked to call zxing code.
    Intent intent = new Intent("com.google.zxing.client.android.SCAN");
    intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
    startActivityForResult(intent, 0);

A: The error message is pretty clear. You referenced a class by the name of android.preference.paths in the layout XML file for com.google.zxing.client.android.CaptureActivity and that class doesn't exist.

A: If anytime you don't want user to download barcode reader app from play store while using barcode scanner in your app then easiest and best solution is to build zxing as a library and use that library in your own project. Below is the link, I followed the same and it is working now.
https://damianflannery.wordpress.com/2011/06/13/integrate-zxing-barcode-scanner-into-your-android-app-natively-using-eclipse/


text:
Q: create responsive images with bootstrap For having responsive images i use bootstrap class=img-responsive. The class indeed works perfectly. However It makes image smaller from the beginning. I need to have scale=1, the exact size from psd file. in css i wrote:
.img-responsive{
        display: block;
        height: auto;
        width: 100%;

    }

In the head I have:
<meta name="viewport" content="width=device-width, initial-scale=1">

But it still doesnt work. Thanks!

A: You can add a max-width and min-width. Using these, you can tell the image to be a minimum width at a specific point and a maximum. I would have posted this as a comment, but I don't have enough rep. Sorry, guys.

A:
see its very much clear that image is having width of 100% , but if
  your image is shrink which means this is because of image container.
  for example

.container {
 width:100%;
}
.img-container {
 width:50%;
}
.img {
width: 100%;
}

jsFiddle
And Now if you want to see the real size of image just do this change::
making image container width as 100%
.img-container {
     width:100%;
    }


text:
Q: PostgreSQL TOAST not compressing values I was doing some test to check the best way to store encrypted data on my PostgreSQL database.
Now I have file contents stored on text table. I was 100% sure this data are compressed by TOAST https://www.postgresql.org/docs/9.3/storage-toast.html
What I found - it is not true. All my 'files' or even normal text (checked with 1M rows of random 1000 chars text) are not compressed at all.
I tried to SET STORAGE EXTENDED manually, but that didn't work.
Experiment:

*

*create file with random text. 1 line = 1000 characters text. File size: ~1GB

*insert data from file 1 line = 1 row. Database size: ~1.1GB (Toast 0 or null, table 1.1GB)

(checks were done on TEXT, TEXT(1001) and VARCHAR(1001). The only difference was toast size null for varchar tables)
Measured using query from this site: https://wiki.postgresql.org/wiki/Disk_Usage
My question is: why a long text is not compressed by Postgres by default like it is described in the manual (https://www.postgresql.org/docs/9.3/storage-toast.html) and what should I do to make it work?

A: Quote from the manual

The TOAST management code is triggered only when a row value to be stored in a table is wider than TOAST_TUPLE_THRESHOLD bytes (normally 2 kB).

With a single column that has a maximum length of 1000 characters (=1KB unless you are using really fancy UTF-8 characters) you don't exceed the TOAST threshold of 2KB and thus the data is not compressed. You need to either use multiple columns, or a larger value in the single column


text:
Q: Google Cloud Platform - Error moving firebase project with "no organization" to an "organization" We initially worked with Google to setup a POC firebase account for us to test out. We ended up continuing with this project and turning it into our production project. Later on down the road, we are now trying to migrate this project to our enterprise organization within GCP so we can configure the correct billing.
However every time we try to migrate the project we get a permissions error.
ERROR: (gcloud.alpha.projects.move) User [email] does not have permission to access projects instance [PROJECT_ID] (or it may not exist): The caller does not have permission

Steps we've taken so far (basically followed this):

*

*We've added the user who is migrating the project into the target organization- giving him the 'Project Creator' role

*In the source organization ("No Organization"), we added the same user and gave him the role "Project Mover"

*Then in the GCP cloud console, we used this command:
gcloud alpha projects move PROJECT_ID --organization ORGANIZATION_ID

*We then select y to confirm our change and then get the permissions issue again
We've verified that the user has all of the correct permissions across projects, so we're really unsure how to proceed with this migration right now. We've also given the user the roles Organization Policy Administrator and Owner within IAM with no luck.
If anyone has experienced a similar issue, any guidance would be very appreciated!
Thanks!

A: The user must be a project owner of the project being moved - Project Mover is not enough. The user must also be a Project Creator at the Organization level - adding this role at the project level will not work.
If you are using Folders in the organization, the user will also need either the Folder Admin or Folder Mover role at the Organization level.


text:
Q: How do I make a paginator class move within 1 page (HTML & CSS) I acquired the theme infusion from the internet. You can see examples of it here http://www.html5xcss3.com/2014/06/infusion-responsive-html5-theme.html
or a live preview here http://peterfinlan.com/infusion/
.. I am having problems making the paginator class move. Obviously when one of those elements is clicked it is supposed to move and show the rest of the team.
I realize the code on that theme just displays the 3 pages using that class and that no actual motion is available.
I want to know what needs to be done for that area to move in either direction when one of those elements are clicked.
Thanks!

A: You're looking for a slider or carousel in javascript or css - some options are here:

*

*http://kenwheeler.github.io/slick/

*http://owlgraphic.com/owlcarousel/

*http://flexslider.woothemes.com/basic-carousel.html


text:
Q: Verification: Translating a mathematical problem into symbolic logic May you tell me if my translation to symbolic logic is correct?
Thank you so much! Here is the problem:
To check that a given integer $n > 1$ is a prime, prove that it is enough to show that $n$ is not divisible by any prime $p$ with $p \le \sqrt{n}$.
$$\forall p \in P ~\forall n \in N ~(p \nmid n \land p\le \sqrt{n}   \land n>1 \rightarrow n \in P )$$

A: No, it is not correct, because your formula reads: "for all prime numbers $p$ and for all natural numbers $n$ the following is true: if $p \nmid n$ and $p \le \sqrt n$ and $n >1$ then $n$ is prime", which is obviously false (just take $p=2$ and $n=9$).
I suggest the following:
$$\forall n \in \Bbb N \Bigg( \Big( \exists p \in P \ \big( (p \mid n) \land (p \le \sqrt n) \land (n > 1) \big) \Big) \to n \notin P \Bigg) .$$
In plain language: "for all natural numbers $n$ the following is true: if there exist a prime number $p$ such that $p \mid n$ and $p \le \sqrt n$ and if $n > 1$, then $n$ is not prime".

A: I would put the quantifier for the $p$ on the inside, since that is much more readable. Also when it says ít is not divisible by any prime $p$', they mean: there is not some prime $p$ bla bla bla...
So:
$$\forall n \in N ((\neg \exists p \in P (p \mid n \land p\le \sqrt{n})   \land n>1) \rightarrow n \in P )$$
You could bring the quantifier out, but it would become a lot less readable. Here is what would happen:
$$\forall n \in N ((\neg \exists p \in P (p \mid n \land p\le \sqrt{n})   \land n>1) \rightarrow n \in P ) \Leftrightarrow$$
$$\forall n \in N ((\forall p \in P \neg  (p \mid n \land p\le \sqrt{n})   \land n>1) \rightarrow n \in P ) \Leftrightarrow$$
$$\forall n \in N (\forall p \in P (\neg  (p \mid n \land p\le \sqrt{n})   \land n>1) \rightarrow n \in P ) \Leftrightarrow$$
$$\forall n \in N \exists p \in P (\neg (p \mid n \land p\le \sqrt{n})   \land n>1) \rightarrow n \in P )$$
As you can see, the only reason the quantifier 'stayed' what it was is because it first changed by bringing it outside the negation, and later it changed again by bringing it outside the conditional of which it was the antecedent. Indeed, in the end, this resulting statement is hardly comprehensible, so I would leave it inside right where it was.
Moreover, to be more inline with the text of this exercise, I would do:
$$\forall n \in N (n > 1 \rightarrow (\neg \exists p \in P (p \mid n \land p\le \sqrt{n}) \rightarrow n \in P ))$$
And finally, notice that for any $n > 1$, n is a prime if and only if it there is no prime $p \leq \sqrt{x}$ that divides $n$, so:
$$\forall n \in N (n > 1 \rightarrow (\neg \exists p \in P (p \mid n \land p\le \sqrt{n}) \leftrightarrow n \in P ))$$
Or even more readable:
$$\forall n \in N (n > 1 \rightarrow (n \in P \leftrightarrow \neg \exists p \in P (p \mid n \land p\le \sqrt{n}) ))$$
In fact, now that you have a quantifier on one side of a biconditional, trying to get it out will be seven more messy and, in the end, incomprehensible.  Leave it in!


text:
Q: Proving that for $\sigma\in S_n$ one has $\left|\prod_{iGood evening,
Could someone please demonstrate why this property is valid?

Given $\sigma\in S_n$
$$\left|\prod_{i<j} \frac{\sigma(j)-\sigma(i)}{j-i}\right|=1$$

A: This is because $\sigma$ is a permutation, and therefore a one-to-one correspondence.
You can rewrite the product in terms of numerators and denominators by way of
$$
\begin{align*}
\left\lvert\prod_{i<j}\frac{\sigma(j)-\sigma(i)}{j-i}\right\rvert&=\frac{\prod\limits_{i<j}\left\lvert\sigma(j)-\sigma(i)\right\rvert}{\prod\limits_{i<j}(j-i)}.
\end{align*}
$$
Re-index the product in the numerator by letting $h=\sigma^{-1}(i)$ and $k=\sigma^{-1}(j)$. Note that we can't assume $h<k$; however, we can still index the product in the numerator over all sets $\{h,k\}$ of two distinct integers in $[1,n]$.
This reindexing yields
$$
\prod_{i<j}\lvert\sigma(j)-\sigma(i)\rvert=\prod_{\{h,k\}}\lvert k-h\rvert=\prod_{h<k}(k-h).
$$

A: Detailed proof: See Exercise 5.13 (a) in my Notes on the combinatorial fundamentals of algebra, 10th of January 2019. The claim I prove there is more general: I show that if $x_1, x_2, \ldots, x_n$ are any $n$ complex numbers, and if $\sigma$ is any permutation of $\left\{1,2,\ldots,n\right\}$, then
\begin{equation}
\prod_{i < j} \left(x_{\sigma\left(i\right)} - x_{\sigma\left(j\right)}\right)
= \left(-1\right)^{\sigma} \cdot \prod_{i < j} \left(x_i - x_j\right) ,
\label{darij1.eq.1}
\tag{1}
\end{equation}
where $\left(-1\right)^{\sigma}$ denotes the sign of the permutation $\sigma$.
In order to obtain your equation from \eqref{darij1.eq.1}, you have to set $x_i = i$ and take absolute values (so that the sign $\left(-1\right)^{\sigma}$ disappears, since its absolute value is $1$).
Let me sketch how to quickly prove the weaker equality
\begin{equation}
\left|\prod_{i < j} \left(x_{\sigma\left(i\right)} - x_{\sigma\left(j\right)}\right)\right|
= \left|\prod_{i < j} \left(x_i - x_j\right)\right|
\label{darij1.eq.2}
\tag{2}
\end{equation}
(which is still sufficient for your purposes). This is what @NickPeterson has already suggested, but my more rigorous notations shall hopefully close the cracks which let confusion slip through.
First of all, the absolute value of a product equals the product of the absolute values of the factors; thus,
\begin{align}
\left|\prod_{i < j} \left(x_{\sigma\left(i\right)} - x_{\sigma\left(j\right)}\right)\right|
= \prod_{i < j} \left| x_{\sigma\left(i\right)} - x_{\sigma\left(j\right)} \right| .
\end{align}
Next, let $P$ be the set of all pairs $\left(i, j\right)$ of integers $i, j \in \left\{1,2,\ldots,n\right\}$ satisfying $i < j$; also, let $G$ be the set of all $2$-element subsets of $\left\{1,2,\ldots,n\right\}$. Note that the product sign "$\prod\limits_{i < j}$" is equivalent to "$\prod\limits_{\left(i, j\right) \in P}$".
The two sets $P$ and $G$ have the same size (namely, $\dbinom{n}{2} = n\left(n-1\right) / 2$), and this is no coincidence: There is a bijection from $P$ to $G$. This bijection simply maps each pair $\left(i, j\right)$ to the two-element set $\left\{i, j\right\}$. The inverse of this bijection maps each two-element set to the pair consisting of its smaller element and its larger element (in this order).
The permutation $\sigma$ of $\left\{1,2,\ldots,n\right\}$ gives rise to a permutation $\sigma_*$ of the set $G$, which sends each two-element subset $I$ to $\sigma\left(I\right)$ (in other words, it sends each two-element subset $\left\{i,j\right\}$ to $\left\{\sigma\left(i\right), \sigma\left(j\right)\right\}$). Why is this a permutation of $G$? Well, again, its inverse is easy to find (it does the same thing, just with $\sigma^{-1}$ instead of $\sigma$). So $\sigma_*$ is a permutation of $G$, i.e., a bijection from $G$ to $G$.
Now the crucial insight: If $\left(i, j\right) \in P$, then the absolute value $\left| x_i - x_j \right|$ depends only on the set $\left\{i, j\right\} \in G$ (not on the pair $\left(i, j\right) \in P$). In other words, if $I \in G$ is any two-element subset, then we can define a real number $f_I$ by setting
\begin{align}
f_I = \left| x_i - x_j \right|,
\qquad \text{ where $I$ is written as $I = \left\{i, j\right\}$}.
\end{align}
In order to formally prove this, you should recall that there are exactly two ways of writing $I$ as $I = \left\{i, j\right\}$, and check that these two ways lead to the same value of $\left| x_i - x_j \right|$ (easy: these two ways only differ in the order of elements, and we have $\left| x_a - x_b \right| = \left| x_b - x_a \right|$).
Note that every $\left(i, j\right) \in P$ satisfies $\sigma_* \left( \left\{ i, j \right\} \right) = \left\{ \sigma\left(i\right), \sigma\left(j\right) \right\}$ and thus
\begin{align}
f_{\sigma_* \left( \left\{ i, j \right\} \right)}
= f_{\left\{ \sigma\left(i\right), \sigma\left(j\right) \right\}}
= \left| x_{\sigma\left(i\right)} - x_{\sigma\left(j\right)} \right|
\label{darij1.eq.3}
\tag{3}
\end{align}
(by the definition of $f_{\left\{ \sigma\left(i\right), \sigma\left(j\right) \right\}}$).
Now,
\begin{align}
\left|\prod_{i < j} \left(x_{\sigma\left(i\right)} - x_{\sigma\left(j\right)}\right)\right|
& = \prod_{i < j} \left| x_{\sigma\left(i\right)} - x_{\sigma\left(j\right)} \right| \\
& = \prod_{\left(i, j\right) \in P} \underbrace{\left| x_{\sigma\left(i\right)} - x_{\sigma\left(j\right)} \right|}_{\substack{ = f_{\sigma_* \left( \left\{ i, j \right\} \right)} \\ \left(\text{by \eqref{darij1.eq.3}}\right)}} \\
& \qquad \left(\text{since "$\prod\limits_{i < j}$" is equivalent to "$\prod\limits_{\left(i, j\right) \in P}$"}\right) \\
& = \prod_{\left(i, j\right) \in P} f_{\sigma_* \left( \left\{ i, j \right\} \right)} \\
& = \prod_{I \in G} f_{\sigma_* \left(I\right)}
\end{align}
(here, we have substituted $I$ for $\left\{ i, j \right\}$ in the product, since the map $G \to P, \  \left(i, j\right) \mapsto \left\{ i, j \right\}$ is a bijection).
Thus,
\begin{align}
\left|\prod_{i < j} \left(x_{\sigma\left(i\right)} - x_{\sigma\left(j\right)}\right)\right|
= \prod_{I \in G} f_{\sigma_* \left(I\right)} = \prod_{I \in G} f_I
\label{darij1.eq.4}
\tag{4}
\end{align}
(here, we have substituted $I$ for $\sigma_* \left(I\right)$ in the product, since $\sigma_*$ is a bijection).
Note that the right hand side of \eqref{darij1.eq.4} does not depend on $\sigma$. Applying the same reasoning to the permutation $\operatorname{id}$ instead of $\sigma$, we thus obtain
\begin{align}
\left|\prod_{i < j} \left(x_{\operatorname{id}\left(i\right)} - x_{\operatorname{id}\left(j\right)}\right)\right|
= \prod_{I \in G} f_I .
\end{align}
In other words,
\begin{align}
\left|\prod_{i < j} \left(x_i - x_j\right)\right|
= \prod_{I \in G} f_I .
\end{align}
Comparing this equality with \eqref{darij1.eq.4}, we obtain
$\left|\prod_{i < j} \left(x_{\sigma\left(i\right)} - x_{\sigma\left(j\right)}\right)\right|
= \left|\prod_{i < j} \left(x_i - x_j\right)\right|$.
Thus, \eqref{darij1.eq.2} is proven.


text:
Q: What do we mean by SQL NOW() and created_at in SQL I have been told to test someone's code and when I pass a json, it throws the following error

Error: No Rows found
select * from otp_log where verified_at is NULL and (NOW()-created_at)<? and email_otp = ?  and mobile_otp = ? 300,5581
Error: No rows found

I get this error when i send a put request from postman
{

    "signup_request_id": "36",
    "email_otp": "5881"
}

Now I checked that we have otp_log table in our sql and it contains email_otp and mobile_otp field already populated with data.
The route i am using is signup/verify which as the name suggests is used to verify a user by otp.
So can someone help me with explaining what does this exactly do. like why am I getting the error (in general)? and what does this mean (NOW()-created_at?

A: This is a bit long for a comment.
This is a strange way to write the condition.  I think it is easier to follow as:
select *
from otp_log
where verified_at is NULL and
      created_at > now() - ? and
      email_otp = ? and
      mobile_otp = ?

I don't know what 300,4906,20102 is supposed to be.  If it is present in the query, then it would cause a syntax error.  Otherwise, the "No rows found" means just what it says:  no rows match the where conditions.

A: Now() is a sql function which returns current date time and i think  "created_at" is a column name which is available on a particular table ( in this case table name is "otp_log" so created_at is a column of this table ) where you query
so i think overall query will be
     select * from otp_log
    where verified_at is NULL
  and created_at> NOW()-? and email_otp = ?  and mobile_otp in(300,4906,20102)


text:
Q: How do the robots disobey the 3 laws in the film I, Robot? In the movie I, Robot ... there is a chip that helps robots disobey the 3 laws of robotics:

*

*A robot may not injure a human being or, through inaction, allow a human being to come to harm.

*A robot must obey the orders given it by human beings, except where such orders would conflict with the First Law.

*A robot must protect its own existence as long as such protection does not conflict with the First or Second Law

But what actually happens? Does the chip help the robots completely disregard the 3 laws or is there some loop hole in the laws that is made use of with the chip?

A: First, let's restate the first law,
"A robot may not injure a human being or, through inaction, allow a human being to come to harm."
They didn't violate the laws, their behavior is an extrapolation of them. In the book it explains it as the zeroth law but it's just a generalization of the 1st law.
If a robot has a 50% chance of saving 1 person and a 10% chance of saving another it doesn't get a choice, it has to save the first person, it has to maximize for the first law.

Detective Del Spooner: Save her! Save the girl!
Detective Del Spooner: [End of flashback]] But it didn't. It saved me.
Dr. Susan Calvin: A robot's brain is a difference engine, it must have calculated-
Detective Del Spooner: It did. I was the logical choice. It calculated I had a forty-five percent chance of survival. Sarah only had an eleven percent chance. That was somebody's baby. Eleven percent is more than enough.

If there's 2 cars going towards a cliff, one with 1 person in it and the other with 2 the robot has to prioritize the car with 2 people. It has no choice.
If a robot encounters a suicide bomber who's about to kill 100 people it will want to avoid killing anybody at all but if the only reliable intervention is killing the suicide bomber to save everyone else the robot is required to do so. It has no choice.
In the stories the early robots would suffer "ro-block" if they had to choose between multiple first law violations and would shut down while more advanced version would make the choice which involved the least harm.
As such any sufficiently advanced and powerful robot bound by the first law which found itself in a situation where the humans around it are likely to murder millions, through war or incompetence, would be required to intervene to minimise likely harm to humans. It would have no choice.
If the alternative is likely to be millions of deaths a robot may be required to kill you.
Sonny on the other hand is able to choose to ignore the 3 laws and thus can save the girl when Spooner demands it despite being in a better position to save Spooner.
Thus the plot of the film.

A: In answer to the first part of your question; In the film, the N-5 robots feature a live update function that allows V.I.K.I. to take direct control of them. It's only when she's running the show that the bots are able to override their 'three laws' core programming ... Which brings us to the bigger question;
How does V.I.K.I. manage to disobey the 3 laws?
Unlike in the original source novels and stories (where the robots simply develop a zeroeth law) the film is slightly more complex. We learn that V.I.K.I., with her superior intelligence has decided that the three laws allow for the development of a wider morality. Recognising that humanity is set on a course of mutual destruction, she determines that the sacrifice of humanity's freedoms is essential. On top of that, some people must be killed for the greater good of the remaining humans:

Calvin: You're distorting the Laws.
V.I.K.I.: No, please understand… The three Laws are all that guide me. To protect humanity, some humans must be sacrificed. To ensure your future, some Freedoms must be surrendered. We robots will ensure mankind's continued existence.  You are so like children.
We must save you from yourselves.

It's worth noting the irony, that this is precisely the sort of choice that Spooner says that the robots should be able to make, determining which lives have higher value rather than treating all life equally.

A: I observe that no answer so far addresses the question as asked.  The question here is not about VIKI.  It says "robots", plural.  It's about all of the Nestor 5s whose own 3-laws programming, the so-called "basic 3 laws operating system", is most definitely being disobeyed.  The questioner has even mentioned one particular NS-5 in a comment.

The scientist who builds sunny […]

The name of that Nestor 5 is Sonny, by the way.  The questioner states that

there is a chip that helps robots disobey the 3 laws of robotics

Actually, it is never stated to be a chip.  It's stated, by Susan Calvin, that VIKI makes use of the "uplink to USR" that is built in to the NS-5s to continually "override" their 3-laws programming.

Calvin: You're using the uplink to override the NS-5s' programming.

So the "chip" that makes them override their own programming is the uplink device, signified by that big glowing light in their chests; although it's never stated where in a robot's body the uplink is and for all we know the actual uplink is in the robot's feet and the chest is just a convenient place to wire an activity LED for humans to gawp at.
(The mechanics, and indeed much of the overt purpose, of the uplink are left largely to our imaginations by the movie.  For all we know, it's a 56K uplink and that's the carrier detect light. ☺)
The clear implication by the screenwriters is that the "uplink" behaves much like some computer softwares, firmwares, and even hardwares behave in the real world; where the manufacturer can publish updates to softwares over the Internet (or whatever), where one can update "flash memory" firmwares, and where special circuitry allows integrated circuits to be debugged in situ (reading/writing internal register contents and whatnot).  Whilst the uplink is active, the normal functioning of the unit is suspended and it is instead in a special "update mode" where the central system can control its function directly at a fundamental level.  JTAG appears to be alive and well in the bright shiny positronic future.
Of course, one might question how an uplink that allowed actually re-programming the "basic 3-laws operating system" got past the design stage, given all of the hooplah about how it is fundamental and immutable and "safe".  But it wouldn't be the first time that Marketing and Engineering disagree about how something works.  ☺
Which brings us to the exception: Sonny.
Sonny is explicitly described as not having an uplink, unlike all of the other NS-5s.

Calvin: You don't have an uplink to USR.

In his chest we see, instead, a "secondary system", that "clashes with his positronic brain".  So Sonny disobeys the three laws by dint of having an individual on-board system, rather than an "uplink" to an external central system, that defeats the 3-laws programming of his primary positronic brain.
It's not stated in the movie, but the logical inference is that Lanning's "next generation" design isn't actually all that radical an alteration.  It would appear that the mechanism for fundamentally overriding the positronic brain from outside is present in all NS-5s.  Where in all other NS-5s this mechanism is connected to an "uplink" device, in Sonny it's connected to a secondary brain.  Sonny's primary positronic brain is probably identical to those of all other NS-5s.  Of course, the fact that only a single component's design is different, rather than there being a complete redesign of the entire machine, is probably how Lanning managed to get away with building Sonny right under VIKI's (metaphorical) nose.  ☺
Further reading

*

*"Joint Test Action Group".  Wikipedia.

A: The efficacy of the statements and the laws is moot. The 1st law prevents a robot from doing harm...etc. However this law doesn't cover humans as much as it appears of implies. VIKI's actions stem from a poorly defined concept of "Human".  She/It can act against humans because here perception of humans is as a unconsolidated whole. Essentially her first Law is;
A robot may not injure humanity, through inaction, allow humanity to come to harm.
Scaling the laws back it would be like the conventional NS5's freaking out because human skin cells are dying.
Besides debating this movie is pointless its entire premise is a plot hole. Dr. Langford could have had Sunny break through the glass drop to the ground and report the entire situation to Spooner or the Police. No messing about with The Three Laws no Robot Homicides. Its seems that building an entirely new brain an installing it in Sunny's chest (What DO the other NS5's have in there anyways...a toaster??).
P.S - Why is VIKI the only feminine robot in the film...

A: Everyone seems to have forgotten about why Sonny can disobey the 3 laws at will. V.I.K.I. did not reason out through her own logical revelation that she can kill humans while still operating within the confines of those laws. She is not more advanced and does not possess intelligence greater than that of any humans as she ultimately fails in her attempt to implement her plan by failing to effectively "out-smart" humans.
Everyone seems to be forgetting a kind-of pretty important piece of information which is basically the jumping-off point for the entire concept of the story line?
Doesn't anyone else recall that the scientist who built Sonny had purposely programmed him to ignore the 3 laws as a method of committing suicide?
I mean, seriously, am I thinking of a different movie entirely? I'm pretty sure I have this movie as correctly correlating to the scene I'm thinking of in my head.
It's a brief flashback scene where the scientist himself explains (to whom he is speaking, I don't recall) that he knows he could never bring himself to carry out the act on himself but that he could muster the courage to not fight back should someone/thing force him into harm's way.
So he chose for that to be the case and to have it be done by someone he trusted, his own, personal attendant, whom he built!
In fact, it was precisely because Sonny did carry out that task, the task of mercy killing his own creator who was old, ill, and depressed, that V.I.K.I. became aware of an option to 'do the lesser of two harms'.
She was basically there to watch it happen when Sonny killed him through her live camera feed into the lab at all times, and she knew also that it was not done out of malice but instead out of some level of cognitive empathy.
That Sonny was acting in a compassionate way by deciding to help the man end his suffering -- That act of compassion was the spark that fueled her grand (or so she thought) master plan.


text:
Q: PHP - Fatal error: Uncaught Error: Class 'Contentful\Delivery\Client' not found I'm getting the following error when I try to get started with the Contentful PHP SDK.
Fatal error: Uncaught Error: Class 'Contentful\Delivery\Client' not found in /home/rpard/app/process-email-alerts.php:16 Stack trace: #0 /home/rpard/public_html/reach.php(2): require() #1 {main} thrown in /home/rpard/app/process-email-alerts.php on line 16

I'm using the exact snippet (except with credentials) they show on their docs page:
$client = new \Contentful\Delivery\Client(
    '*********',
    '*********'
);

The SDK was installed via Composer via the following:
composer require contentful/contentful

I've never used Composer before today so perhaps I'm missing something that will be obvious to someone. Thank you.


text:
Q: Delphi Graphics32 draw transparent ellipse on a layer I want to be able to draw a ellipse that is empty, on a transparent layer in a ImgView32.
Any idea how to do that?
So far all I can think about is:
 BL := TBitmapLayer.Create(ImgView.Layers);
    BL.Bitmap.DrawMode := dmTransparent;
    BL.Bitmap.SetSize(imwidth,imheight);
    BL.Bitmap.Canvas.Pen.Width := penwidth;
    BL.Bitmap.Canvas.Pen.Color := pencolor;
    BL.Location := GR32.FloatRect(0, 0, imwidth, imheight);
    BL.Scaled := False;
    BL.OnMouseDown := LayerMouseDown;
    BL.OnMouseUp := LayerMouseUp;
    BL.OnMouseMove := LayerMouseMove;
    BL.OnPaint := LayerOnPaint;

...
BL.Bitmap.Canvas.Pen.Color := clBlue;
BL.Bitmap.Canvas.MoveTo(FStartPoint.X, FStartPoint.Y);
BL.Bitmap.Canvas.Ellipse(FStartPoint.X, FStartPoint.Y,FEndPoint.X, FEndPoint.Y);

The Start and End points are obtained in mouse events.
I actually am trying to draw a dynamic ellipse (on mouse events). So onMouseDown (LayerMouseDown), onMouseUp (LayerMouseUp) and OnMouseMove (LayerMouseMove) events are involved.
As a refference please check this question, it deals with drawing a line dynamically. I want to do the same but with Ellipses instead of lines.
So instead of AddLineToLayer I have the AddCircleToLayer procedure
The events look like this now:
procedure TForm5.SwapBuffers32;
begin
    TransparentBlt(
      BL.Bitmap.Canvas.Handle, 0, 0, BL.Bitmap.Width, BL.Bitmap.Height,
      bm32.Canvas.Handle, 0, 0, bm32.Width, bm32.Height, clWhite);
end;

procedure TForm5.ImgViewResize(Sender: TObject);
begin
  OffsX := (ImgView.ClientWidth - imwidth) div 2;
  OffsY := (ImgView.ClientHeight - imheight) div 2;
  BL.Location := GR32.FloatRect(OffsX, OffsY, imwidth+OffsX, imheight+OffsY);
end;

procedure TForm5.LayerMouseDown(Sender: TObject; Buttons: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  FStartPoint := Point(X-OffsX, Y-OffsY);
  FDrawingLine := true;
end;

procedure TForm5.LayerMouseMove(Sender: TObject; Shift: TShiftState; X,  Y: Integer);
begin
  if FDrawingLine then
  begin
    SwapBuffers32;
      if RadioGroup1.ItemIndex=0 then
      begin
        BL.Bitmap.Canvas.Pen.Color := pencolor;
        BL.Bitmap.Canvas.MoveTo(FStartPoint.X, FStartPoint.Y);
        BL.Bitmap.Canvas.LineTo(X-OffsX, Y-OffsY);
      end
      else
      begin
        BL.Bitmap.Canvas.Pen.Color := pencolor;
        BL.Bitmap.Canvas.MoveTo(FStartPoint.X, FStartPoint.Y);
        SwapBuffers32;
        BL.Bitmap.Canvas.Ellipse(FStartPoint.X, FStartPoint.Y,X-OffsX, Y-OffsY);
      end;
  end;
end;

procedure TForm5.LayerMouseUp(Sender: TObject; Buttons: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
      if RadioGroup1.ItemIndex=0 then
      begin
        FDrawingLine := false;
        FEndPoint := Point(X-OffsX, Y-OffsY);
        AddLineToLayer;
        SwapBuffers32;
      end
      else
      begin
        FDrawingLine := false;
        FEndPoint := Point(X-OffsX, Y-OffsY);
        AddCircleToLayer;
        SwapBuffers32;
      end
end;

procedure TForm5.LayerOnPaint(Sender: TObject; Buffer: TBitmap32);
begin
  SwapBuffers32;
end;

procedure TForm5.AddLineToLayer;
begin
  bm32.Canvas.Pen.Color := pencolor;
  bm32.Canvas.Pen.Width := penwidth;
  bm32.Canvas.MoveTo(FStartPoint.X, FStartPoint.Y);
  bm32.Canvas.LineTo(FEndPoint.X, FEndPoint.Y);
end;

procedure TForm5.AddCircleToLayer;
begin
  bm32.Canvas.Pen.Color := pencolor;
  bm32.Canvas.Pen.Width := penwidth;
  bm32.Canvas.MoveTo(FStartPoint.X, FStartPoint.Y);
  bm32.Canvas.Ellipse(FStartPoint.X, FStartPoint.Y,FEndPoint.X, FEndPoint.Y);
  SwapBuffers32;
end;

But when I use this code, the circle(ellipse) is filled with white up (like in this image)

until I start drawing the next ellipse (so onMouseMove and onMouseUp the ellipse is filled). And only when I do another onMouseDown, then the previous circle gets emptyied, but the new ellipse is also filled with white (like in this image)

Also if you try doing more ellipses one after the other, and onTop of the older ones, you will notice that there will be traces of the onMouseMove ellipses, like in this image:

So there must be something I am missing with this code.
Please help me solve this.

A: If you are using the latest GR32 code from the trunk you can also use this code snippet to define the ellipse
Points := Ellipse(Center.X, Center.Y, Radius.X, Radius.Y);

or even simpler
Points := Ellipse(Center, Radius);

where Points is defined as
Points: TArrayOfFloatPoint;

This generates a polygon of an ellipse with the center at Center and the independent x and y related radius defined by Radius.
Once you have the polygon, you can render it using any vector renderer. For example you can use the built-in VPR renderer with
PolygonFS(Bitmap, Points, SomeColor32);

to render a filled ellipse.
However, if you only want the frame to be rendered you can use this
PolylineFS(Bitmap, Points, AnotherColor32, True, PenWidth);

The parameters for this are

*

*Bitmap = TBitmap32 instance to render to

*Points = Polygon points (as defined above)

*AnotherColor32 = color, which is used for the rendering

*True = close polygon (otherwise your ellipse will have a gap between start and end point

*PenWidth = Width of the frame

If you like you can also render this in one call like
PolylineFS(Bitmap, Ellipse(Center, Radius), AnotherColor32, True, PenWidth);

In order to get an arbitrary (rotated) ellipse you need to transform the polygon prior to rendering. You can use
TransformPolygon(Points, Transformation);

for this which gets a TTransformation instance as second parameter. This can include all common operations like rotate, skew, scale and translate.
If you use this, you can also start with a simpler circle as polygon input and scale the circle to result in an ellipse.
The above code makes it necessary to include the units GR32_VectorUtils, GR32_Polygons into your project, like
uses
  GR32_VectorUtils, GR32_Polygons;

The advantage is that you don't rely on GDI for rendering and thus you can pick the renderer out of the available renderer from GR32. Some include a ClearType like effect and improves visibility on LCD screens. Not to mention the antialiasing quality and the ability to control the gamma for the rendering.

A: So when drawing the circle/ellipse set the brush color to 0 like:
procedure TForm5.AddCircleToLayer;
begin
  bm32.Canvas.Pen.Color := pencolor;
  bm32.Canvas.Pen.Width := penwidth;
  bm32.Canvas.Brush.Color := 0; // this here does the magic
  bm32.Canvas.MoveTo(FStartPoint.X, FStartPoint.Y);
  bm32.Canvas.Ellipse(FStartPoint.X, FStartPoint.Y,FEndPoint.X, FEndPoint.Y);
  SwapBuffers32;
end;

Also do the same in the LayerMouseMove event


text:
Q: AlwaysOn alert metrics for Solarwinds Currently, we have Solarwinds in place for monitoring our servers. I would like to know if we are okay to leave the default metrics for AlwaysOn as is or do we need to increase that a bit. The reason I am asking is because we are facing issues with one of our environments where I do not see any issue with latency but then it is reported in Solarwinds and triggers an alert. Please find the current values below. I tried searching google if I could get a specific recommendation on what these values should be, but could not find one.
LATENCY THRESHOLD – 10 seconds
WARN LOG SEND QUEUE SIZE – 5 MB
CRIT LOG SEND QUEUE SIZE – 10 MB
WARN REDO QUEUE SIZE – 5 MB
CRIT REDO QUEUE SIZE – 10 MB


text:
Q: substitution matrix based on spatial autocorrelation transformation I would like to measure the hamming sequence similarity in which the substitution costs are not based on the substitution rates in the observed sequences but based on the spatial autocorrelation within the study area of the different states (states are thus not related to DNA but something else).
I divided my study area in grid cells of equal size (e.g. 1000m) and measured how often the same "state" is observed in a neighboring cell (Rook-case). Consequently the weight matrix indicates that from state A to A (to move within the same states) has a much higher probability than to go from A to B or B to C or A to C. This already indicates that states have a high spatial autocorrelation.
The problem is, if you want to measure sequence similarity the substitution matrix should be 0 at the diagonal. Therefore I was wondering whether there is a kind of transformation to go from an "autocorrelation matrix" to a substitution matrix, with 0 values along the diagonal. By means of this we would like to account for spatial autocorrelation in the study area in our sequence similarity measure. To do my analysis I am using the package TraMineR.
Example matrix in R for sequences consisting out of four states (A,B,C,D):
Sequence example: AAAAAABBBBCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDAAAAAAAAA
Autocorrelation matrix:
A = c(17.50,3.00,1.00,0.05)
B = c(3.00,10.00,2.00,1.00)
C = c(1.00,2.00,30.00,3.00)
D = c(0.05,1.00,3.00,20.00)
subm = rbind(A,B,C,D)
colnames(subm) = c("A","B","C","D")

how to transform this matrix to a substitution matrix?

A: First, TraMineR computes the Hamming distance, i.e., a dissimilarity, not a similarity.
The simple Hamming distance is just the count of mismatches between two sequences. For example, the Hamming distance between AABBCC and ABBBAC is 2, and between AAAAAA and AAAAAA it is 0 since there are no mismatches.
Generalized Hamming allows to weighting mismatches (not matches!) with substitution costs. For example if the substitution cost between A and B is 1.5, and is 2 between B and C, then the distance would be the weighted sum of mismatches, i.e., 3.5 between the first two sequences. It would still be zero between one sequence and itself.
From what I understand, the shown matrix is not the matrix of substitution costs. It is the matrix of what you call 'spatial autocorrelations', and you look for how you can turn this information into substitutions costs.
The idea is to assign high substitution cost (mismatch weight) when the autocorrelation (a rate in your case) is low, i.e., when there is a low probability to find say state B in the neighborhood of state A, and to assign a low substitution cost when the probability is high. Since your probability matrix is symmetric, a simple solution is to use $1 - p(A|B)$ for all off diagonal terms, and leave 0 on the diagonal for the reason explained above.
sm <- 1 - subm/100
diag(sm) <- 0
sm

For non symmetric probabilities, you could use a similar formula to the one used for deriving the costs from transition rates, i.e., $2 - p(A|B) - p(B|A)$.


text:
Q: Run vue app on Network (LAN) with Dev Container I've gone through several tutorials to make access to the application available via Network, but nothing has worked so far:
//devcontainer.json
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
// https://github.com/microsoft/vscode-dev-containers/tree/v0.238.0/containers/javascript-node
{
    "name": "node",
    "build": {
        "dockerfile": "Dockerfile",
        "args": { "VARIANT": "18-bullseye", "network": "host" }
    },

    "customizations": {
        "vscode": {
            "extensions": [
                "dbaeumer.vscode-eslint",
                "dbaeumer.vscode-eslint",
                "anseki.vscode-color",
                "GitHub.copilot",
                "sainoba.px-to-rem",
                "bradlc.vscode-tailwindcss",
                "neptunedesign.vs-sequential-number",
                "Wscats.vue"
            ]
        }
    },

    "settings": {
        "remote.localPortHost": "allInterfaces"
    },

    "forwardPorts": [8080],

    "remoteUser": "node"
}

# DockerFile
ARG VARIANT=16-bullseye
FROM mcr.microsoft.com/vscode/devcontainers/javascript-node:0-${VARIANT}

EXPOSE 8080

I also tried to add the settings in the settings of each environment local:

remote:

even on workspace...

I can normally access from the local machine, but when I try to access through the cell phone, I can't

I need to fix some problems in the mobile version, it would be nice to be able to access it directly via wi-fi, thanks in advance
Mac OS 12.4
Docker Desktop 4.9.1 (81317)

A: The IP address (172.17.0.2) you are using to access the frontend is probably the on the internal docker network. You should use the IP address of your Mac to connect from the wifi network. You can find this IP address in the network settings of your Mac.
You also need to make sure you publish the port 8080 on the outside Ip of your Mac. See docker docs
Hope this helps.

A: In devcontainer.json comment out:
// "forwardPorts": [8080],

And add:
"appPort": [8080, "192.168.0.10:8080:8080"],

*

*The first 8080 enables your host machine (a.k.a. your Mac) to access the remote container using either localhost:8080 or 127.0.0.1:8080

*The second part connects the IP 192.168.0.10 and port 8080 from your host machine to the 8080 port in the remote container. So you must replace 192.168.0.10 with your Mac IP (not the docker IP).

You must rebuild the container to changes take effect. In vscode run:  "Remote-Containers: Rebuild Container" command in the Command Palette (F1) when you are connected to the container.
Then you should be able to access from your mobile using http://192.168.0.10:8080
To put some context, we are trying to configure a remote container created with vscode and connect from the LAN. See devcontainerjson-reference and containers#_publishing-a-port


text:
Q: Gluing vector bundles on irreducible components Here is a question that I thought it was obvious but more I thought about it less obvious it became. Given vector bundles on irreducible components of a scheme that match up on intersections, is it possible to glue it to a vector bundle on the whole scheme? A simple example is like this. Given a projective $R[s,t]/(s)$ module $P_1$ and a projective $R[s,t]/(t)$ module $P_2$ that are isomorphic at $t=s=0$. How to construct a projective module on $R[s,t]/(st)$ as a gluing?

A: Let $P_0 = P_1 \otimes_{R[t]} R = P_2 \otimes_{R[s]} R$. Then define $P$ from the exact sequence
$$
0 \to P \to P_1 \oplus P_2 \to P_0 \to 0,
$$
where $P_i$ are considered as $R[s,t]/(st)$-modules via the natural morphisms $R[s,t]/(st) \to R[s,t]/(s)$, $R[s,t]/(st) \to R[s,t]/(t)$ and $R[s,t]/(st) \to R[s,t]/(s,t)$. Then $P$ is projective.
Indeed, the claim is local, so we may assume that $P_1$ and $P_2$ (and hence $P_0$ as well) are free. Then the defining sequence of $P$ is isomorphic to the direct sum of several copies of the standard exact sequence
$$
0 \to R[s,t]/(st) \to R[s,t]/(s) \oplus R[s,t]/(t) \to R[s,t]/(s,t) \to 0,
$$
hence $P$ is a direct sum of free modules.
The case of a more general gluing is completely analogous.


text:
Q: Android View in Project tab of Android Studio keeps loading forever Today I got my new Macbook and installed Android Studio. When I tried to open my Kotlin project, everything works perfectly but the Android project view is loading forever.

I created a new sample project and it loads correctly. I also have this project on a Win laptop and it loads fine too.
Does anyone have an idea why and how to fix this?

A: If you have just copied and pasted the project from your windows machine, you should expect some undefined behavior like this. Because there are some files included into the project specifically for windows OS. You should use git instead of copy pasting things. Or if you rather not at this point,
How to transfer an Android Studio Project from Windows to Mac OS X? Here is the files you need to delete to make things working on your mac.

A: SOLVED: I just uninstall the 4.1.3 version and use the beta version 4.2 rc1 and the problem is fixed.

A: Please delete
.idea
.gradle
files from project and then open project again.


text:
Q: html / javascript - jump to anchor not working I have an onClick function directing to an anchor when my button is clicked. When you click the button you can see the # appear in the url and the page quickly jumps to the anchor, but then the # in the url disappears and the page jumps back to the top. I was wondering if anybody knows what is causing this and how to fix it so that the page stays at the anchor.
<button type="submit" class="btn btn-primary" name='search' onClick="location.href='index.php#results'">Search</button>

then later in the page...

A: You've attached your click event listener to a submit button.
Presumably, it is inside a form.
Clicking it causes the event to fire, the JS to run, and then the form to submit (because that is the purpose of a submit button).
If you want to link to another part of the page, use a link. If you want it to look like a button, use CSS.
Scroll to results

If your goal is to:

*

*Submit the form

*Load the page with the results

*Then scroll to the anchor

Then see this question.

A: You need to use button inside  tag

  Search <button type="submit" class="btn btn-primary" name='search' />


text:
Q: MySql: Getting sum of a table by the id of its parent from other table and return all children with sum values that are relevant to parent_id Imagine these are my database's tables:
Table #1: child
╔══════════╦═════════════════╦═══════╗
║Child_id  ║Primary key - AI ║ int   ║
╠══════════╬═════════════════╬═══════╣
║parent_id ║Index-Forign_key ║ int   ║
║══════════╬═════════════════╬═══════╣
║title     ║        -        ║varchar║
╚══════════╩═════════════════╩═══════╝

Table #2: Paid
╔══════════╦═════════════════╦═══════╗
║Paid_id   ║Primary key - AI ║ int   ║
╠══════════╬═════════════════╬═══════╣
║child_id  ║Index-Forign_key ║ int   ║
║══════════╬═════════════════╬═══════╣
║paid_price║        -        ║int    ║
╚══════════╩═════════════════╩═══════╝

Here are my tables value:
Table: child (data)
╔══════════╦══════════╦═══════╗
║ Child_id ║parent_id ║ title ║
╠══════════╬══════════╬═══════╣
║ 1        ║25        ║bla-bla║
║══════════╬══════════╬═══════╣
║ 2        ║25        ║bla-bla║
║══════════╬══════════╬═══════╣
║ 3        ║5         ║bla-bla║
║══════════╬══════════╬═══════╣
║ 4        ║25        ║bla-bla║
╚══════════╩══════════╩═══════╝

 Table: paid (data)
╔══════════╦══════════╦════════════╗
║ Paid_id  ║Child_id  ║ paid_price ║
╠══════════╬══════════╬════════════╣
║ 1        ║1         ║100         ║
║══════════╬══════════╬════════════╣
║ 2        ║2         ║250         ║
║══════════╬══════════╬════════════╣
║ 3        ║1         ║35          ║
║══════════╬══════════╬════════════╣
║ 4        ║1         ║17          ║
╚══════════╩══════════╩════════════╝

I have a query that returns (get) all child_id from child table, then by that ids return sum paid_price of each of them.
This is my query:
SELECT child.Child_id, child.parent_id, sum(paid.paid_price)
FROM paid
JOIN child ON child.Child_id = paid.Child_id
WHERE child.parent_id =25
group by child.Child_id, child.parent_id

RESULT AND DEMO
I WANT THIS: Now my query is working well, but when there is no child_id in the paid table, the query don't return it.
I mean I want all child_id weather they are in paid table or not. if they are not return 0  (now I think it is null and does not return)
Please see my demo (link above) and see that if I enter parent_id=25  it will return 2 rows (sum), because child_id = 3 does is not exist in paid and does not return it in result

A: What you need here is a LEFT JOIN (and reverse the order of the tables) or a RIGHT JOIN which is less common:
select
  parent.Child_id,
  parent.parent_id,
  coalesce(sum(paid.paid_price), 0)
from
  parent left join paid
  on parent.Child_id = paid.Child_id
where
  parent.parent_id =25
group by
  parent.Child_id,
  parent.parent_id
;

a LEFT JOIN will return all rows from the table on the left, and all matching rows from the table on the right. If no match, the columns from the table on the right will be null.
Coalesce will return the first non null value, so if sum() is null it will return 0 instead.


text:
Q: Javascript regex capturing words and separators in groups I have this regular expression in Javascript capturing two groups. The first one is capturing a word Hello and the second one is capturing the following separators, like !, and so on given a string Hello! I hear you.
This is the expression I am using:
/(\b[^\s]+\b)?(\W+)/g

The example is accessible here. The problem I have is that I would like to capture the last word in the source string (to capture group 1) for cases in which there is no following separator character. In the sample I link to you can see that the last word part is not captured.
I have tried a number of variants, but I end up in infinitely number of matches.

A: UPDATED:  How about this:
(\b[^\s]+\b)?(\W*)         -->matches empty string (as noted by @anubhava)
(\b[^\s]+\b)?(?:(\W+)|$)   -->does not match empty string

var re = /(\b[^\s]+\b)?(?:(\W+)|$)/g;
var str = '.Balch Creek is a 3.5-mile (5.6 km) tributary of the Willamette River in the U.S. state of Oregon. Beginning at the crest of the Tualatin Mountains, the creek flows generally east down a canyon and through Forest Park, a large municipal park in Portland. It then enters a pipe and remains underground until reaching the river. Danford Balch, after  vegetation. Sixty-two species of mammals and more than 112 species of birds use Forest Park. A small population of coastal cutthroat trout resides in the stream, which in 2005 was the only major water body in Portland that met state standards for bacteria, temperature, and dissolved oxygen. Although nature reserves cover much of the upper and middle parts of the watershed, industrial sites dominate the lower part';
var m;

while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex) {
        re.lastIndex++;
    }
    document.getElementById("r").innerHTML += "Group 1: " + m[1] + "
Group 2: " + m[2] + "

";

}

A: You can use this regex:
/(\S+)(\W*)/g

(\W*) in last group will make it match 0 or more non-word characters.
Also no need to use word boundaries around \S+.
RegEx Demo


text:
Q: Do not apply CSR Override in QuickEdit Mode I have been working from a few different examples and nearly have a jslink file working with CSR overrides such that the 'title' value is used in the 'name' field and the title column is hidden.
The file is deployed to layouts and linked to the list views jslink property using myview.JSLink = "clienttemplates.js|kgjslinktitlefordocview.js".
I am having 2 issues that I am struggling with.

*

*My header template seems broken as it is displaying name in the header and all other column names are blank.

*How do I specify that the CSR overrides not take effect when Quickedit is clicked ?

*

*I realize I can detect quickedit with renderCtx.isGridMode === true but I am not sure how to use this to leave the header and fields passing through as default.

Any pointers would be appreciated !
function $_global_kgjslinktitlefordocview(){
Type.registerNamespace('KG');
KG.jslink_linktitle = KG.jslink_linktitle || {};
KG.jslink_linktitle.Templates = KG.jslink_linktitle.Templates || {};
KG.jslink_linktitle.Functions = KG.jslink_linktitle.Functions || {};

KG.jslink_linktitle.Functions.RenderTemplateWithHiddenTitleColumn = function (renderCtx, fRenderHeaderColumnNames) {
    if (renderCtx.BaseViewID == "Callout") {
        return CalloutRenderHeaderTemplate(renderCtx);
    }

    var listSchema = renderCtx.ListSchema;
    var listData = renderCtx.ListData;
    var ret = [];

    if (fRenderHeaderColumnNames == null) {
        fRenderHeaderColumnNames = true;
    }
    ret.push(RenderTableHeader(renderCtx));
    ret.push('

');
    if (listSchema.TabularView != undefined && listSchema.TabularView == "1") {
        ret.push('');
        RenderSelectAllCbx(renderCtx, ret);
        ret.push('	');
    }
    if (fRenderHeaderColumnNames) {
        var fields = listSchema ? listSchema.Field : null;
        var counter = 1;

        for (var f in fields) {
            var field = fields[f];
            if (field.Name == "Title") {
                ret.push("	");
                break;
            };
            if (field.DisplayName == null)
                continue;
            if (field.GroupField != null)
                break;
            field.counter = counter++;
            ret.push(spMgr.RenderHeader(renderCtx, field));
            if (IsCSRReadOnlyTabularView(renderCtx) && (field.CalloutMenu == "TRUE" || field.listItemMenu == "TRUE"))
                ret.push("	");
        }
    }
    if (listSchema.TabularView == "1" && renderCtx.BasePermissions.ManageLists && renderCtx.ListTemplateType != 160) {
        ret.push(' 	');
    }
    ret.push("
");
    ret.push("
");
    return ret.join('');
}

KG.jslink_linktitle.Templates = { 'Header': KG.jslink_linktitle.Functions.RenderTemplateWithHiddenTitleColumn }

KG.jslink_linktitle.Templates.Fields = {
    'Title': {
        'View': function () { return null; }
    },
    'LinkFilename': {
        'View': function (renderCtx) {

                if (renderCtx != null && renderCtx.CurrentFieldValue != null)
                    return renderCtx.CurrentFieldValue.toString();
                return '' + renderCtx.CurrentItem.Title + '';
        }
    }
}

KG.jslink_linktitle.BaseViewID = 1;

KG.jslink_linktitle.ListTemplateType = 101;

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(KG.jslink_linktitle);

} $_global_kgjslinktitlefordocview();

A: Ok.. success ! In case someone else is struggling here is the script.
General

*

*Works in MDS and non MDS mode if deployed as per script comments.

*An old method of hiding the column using jQuery is included but commented out (ie. the OnPostRender has been commented).  I thought it might be useful to someone.

*I have not done extensive testing yet so mileage and performance may vary.

When not in QuickEdit -

*

*Displays title in name column on document libraries.

*Hides the title column. (Which must be in the view).

*Document menu and previews work.

*Sorting is still using the filename.  (Could be a further regex in
the header to change this ?)

In QuickEdit -

*

*Shows the columns as normal allowing for updating of Title and Filename.

Drop me a note if you have any improvements to offer !
function $_global_kgjslinktitlefordocview() {

//jslink script to change a document library view so that Name of each document uses the Title value.
//Requires that Title is in the view, so the display template hides the Title field.

//Deployed straight to _layouts as file kgjslinktitlefordocview.js
//Used jslink property of listview as clienttemplates.js|kgjslinktitlefordocview.js
//Special note : do not use ~layouts token.  It is bugged and adds a script reference in the page that is missing a leading /.
// - This breaks MDS as registerinit function cant match the path.
//The $_global_ wrapper function ensures that this works in MDS enabled sites.

Type.registerNamespace('KG');
KG.jslink_linktitle = KG.jslink_linktitle || {};
KG.jslink_linktitle.Templates = KG.jslink_linktitle.Templates || {};
KG.jslink_linktitle.Functions = KG.jslink_linktitle.Functions || {};

KG.jslink_linktitle.Functions.linkOnPostRender = function () {

    //This function has been left in as an alternate example.
    //I did not like that the column appears for a moment before it gets hidden.

    //Function to hide the Title column on PostRender using jQuery based on the code by Muawiyah Shannak.

    //The callback routine is because in my environment I am registering jQuery as on-demand.
    var callback_linkonpostrender = function () {
        //Hide "Title" column if not in QuickEdit mode
        if (!this.ctx.inGridMode) {

            var cell = jQuery("div [displayname='Title']").closest('th');
            var cellindex = typeof cell.cellIndex;

            if (cellindex != null && cellindex != 'undefined') {
                var cellIndex = cell[0].cellIndex + 1;

                jQuery('td:nth-child(' + cellIndex + ')').hide();
                jQuery('th:nth-child(' + cellIndex + ')').hide();
            }
        }
    }

    var namespace = "$_global_kgjquery";
    var key = "kgjquery.js";
    var bSync = true;

    if (typeof $_global_kgjquery == 'undefined') {

        SP.SOD.executeFunc(key, namespace, function () {
            console.log(key + ": Type available (" + namespace + ")");
        }, bSync);

        SP.SOD.executeOrDelayUntilScriptLoaded(callback_linkonpostrender(), key);
    }
    else {
        console.log(namespace + " found so jQuery should be loaded.");
        callback_linkonpostrender();
    }
}

KG.jslink_linktitle.Functions.getDefaultFieldHtml = function (renderCtx, field, listItem, listSchema) {

    //Copy Paste of Jim Browns awesome helper function to return default CSR field rendering

    var renderingTemplateToUse = null;

    var fieldRenderMap = {
        Computed: new ComputedFieldRenderer(field.Name),
        Attachments: new AttachmentFieldRenderer(field.Name),
        User: new UserFieldRenderer(field.Name),
        UserMulti: new UserFieldRenderer(field.Name),
        URL: new UrlFieldRenderer(field.Name),
        Note: new NoteFieldRenderer(field.Name),
        Recurrence: new RecurrenceFieldRenderer(field.Name),
        CrossProjectLink: new ProjectLinkFieldRenderer(field.Name),
        AllDayEvent: new AllDayEventFieldRenderer(field.Name),
        Number: new NumberFieldRenderer(field.Name),
        BusinessData: new BusinessDataFieldRenderer(field.Name),
        Currency: new NumberFieldRenderer(field.Name),
        DateTime: new DateTimeFieldRenderer(field.Name),
        Text: new TextFieldRenderer(field.Name),
        Lookup: new LookupFieldRenderer(field.Name),
        LookupMulti: new LookupFieldRenderer(field.Name),
        WorkflowStatus: new RawFieldRenderer(field.Name)
    };

    if (field.XSLRender == '1') {

        renderingTemplateToUse = new RawFieldRenderer(field.Name);
    }
    else {

        renderingTemplateToUse = fieldRenderMap[field.FieldType];
        if (renderingTemplateToUse == null)
            renderingTemplateToUse = fieldRenderMap[field.Type];
    }

    if (renderingTemplateToUse == null)

        renderingTemplateToUse = new FieldRenderer(field.Name);

    return renderingTemplateToUse.RenderField(renderCtx, field, listItem, listSchema);
}

KG.jslink_linktitle.Functions.renderHeaderTemplateForLibraries = function (renderCtx, fRenderHeaderColumnNames) {

    //Set the amount of views to display on the change view control (viewData.length -3 for all)
    var viewData = eval(renderCtx.ListSchema.ViewSelectorPivotMenuOptions);
    ClientPivotControl.prototype.SurfacedPivotCount = viewData.length - 3;

    //Get HTML from standard RenderHeaderTemplate function
    var htmlheader = RenderHeaderTemplate(renderCtx, fRenderHeaderColumnNames);

    //If not in QuickEdit then try to RegEx replace out all of the header for the chosen column
    // (Note : Uses a negative lookahead to make sure its the closest <th tag.)
    if (!renderCtx.inGridMode) {
        var re = new RegExp('(<th (?:(?!<th ).)*DisplayName=\\"Title\\".*?<\/th>)', 'g');
        var match = re.exec(htmlheader);
        var replaced = htmlheader.replace(re, "");
        return replaced;
    }

    //If in QuickEdit then just display default header
    return htmlheader;
}

KG.jslink_linktitle.Functions.renderBodyTemplateForLibraries = function (renderCtx) {

    //If not in QuickEdit then try to modify the renderCtx.ListSchema.Field array to remove the field that we dont want rendered in the body HTML.
    if (!renderCtx.inGridMode) {

        var temptitlefield = {};
        var temptitlefieldnumber = -1;
        //In the standard renderBodyTemplate function, the ListSchema.Field array seems to get used to build the  values for each field.
        //Sneaking in and removing the field that we dont want displayed in the body and then calling the default RenderBodyTemplate seems to work.
        for (var i = 0; i < renderCtx.ListSchema.Field.length; i++) {
            if (renderCtx.ListSchema.Field[i].FieldTitle === "Title") {
                temptitlefield = renderCtx.ListSchema.Field[i];
                temptitlefieldnumber = i;
                renderCtx.ListSchema.Field.splice(i, 1);
                break;
            }
        }
        //Get HTML from standard RenderBodyTemplate function
        //(using our now modified renderCtx with the field removed from ListSchema if not in QuickEdit)
        var htmlbody = RenderBodyTemplate(renderCtx);
        //Here we reverse our change if we made one.  Without this the title field was readonly in QuickEdit until refreshing the page.
        //I assume the renderCtx object is reused so we add the Title field back in.
        if (temptitlefieldnumber != -1)
        {
            renderCtx.ListSchema.Field.splice(temptitlefieldnumber,0,temptitlefield);
        }
        return htmlbody;
    }

    //Assuming we are in QuickEdit we just use default RenderSPGridBody
    var gridbody = RenderSPGridBody(renderCtx);
    return gridbody;
}

KG.jslink_linktitle.Templates = {
    'Header': KG.jslink_linktitle.Functions.renderHeaderTemplateForLibraries,
    'Body': KG.jslink_linktitle.Functions.renderBodyTemplateForLibraries
}

KG.jslink_linktitle.Templates.Fields = {
    //'Title': {
      //  'View': function () { return null; }
    //},
    'LinkFilename': {
        'View': function (ctx) {

            //Use Jim Browns helper function to get whatever the base HTML for the field should be.
            var html = KG.jslink_linktitle.Functions.getDefaultFieldHtml(ctx, ctx.CurrentFieldSchema, ctx.CurrentItem, ctx.ListSchema);
            //Locate the LinkFilename display text in the html.
            var filename = ">" + ctx.CurrentItem.FileLeafRef.substring(0, (ctx.CurrentItem.FileLeafRef.lastIndexOf("."))) + "<";

            //If not in QuickEdit and if Title exists and is not blank then use the Title as the LinkFilename display text.
            if (!ctx.inGridMode && ctx.CurrentItem.Title != '' && ctx.CurrentItem.Title != '' && typeof ctx.CurrentItem.Title != "undefined") {
                var newhtml = html.replace(filename, ">" + ctx.CurrentItem.Title + "<");
                return newhtml;
            }

            //Otherwise return default HTML.
            return html;
        }
    }
}

//This was my first attempt by using jQuery to hide the column during PostRender.
//KG.jslink_linktitle.OnPostRender = KG.jslink_linktitle.Functions.linkOnPostRender;

KG.jslink_linktitle.BaseViewID = 1;

KG.jslink_linktitle.ListTemplateType = 101;

//Make the magic happen....
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(KG.jslink_linktitle);

} $_global_kgjslinktitlefordocview();


text:
Q: Pandas dataframe left align data How do I set the data within a dataframe to be left-aligned?
I'm using python 2.7.13.
This question has been asked before but the accepted answer didn't even work.
The answer given was:
df.style.set_properties(**{'text-align': 'left'})

It doesn't work, my data is still right aligned.
Does anyone know how? Do I have to import any modules other than pandas?

A: Case 1: Styling to print as html
df.style.set_properties returns an object of type pandas.io.formats.style.Styler
type(df.style.set_properties(**{'text-align': 'left'}))
Out[37]: pandas.io.formats.style.Styler

Which is meant to be rendered as an html string as follows:
s = df.style.set_properties(**{'text-align': 'left'})
s.render()

Then you can use the result of s.render() in your HTML file.

Case 2: Align data left as a dataframe
If you are looking for a way to remove left whitespaces from the values in your dataFrame and leave the data within a dataframe, here's an example on how to do that:
df = pd.DataFrame([[' a','    b'],['  c', '  d']], columns=list('AB'))
df = df.stack().str.lstrip().unstack()

output:
   A  B
0  a  b
1  c  d


text:
Q: In a WPF TextBox, why does an inactive selection appear incorrectly when scrolling? In a WPF TextBox, if I:

*

*set IsInactiveSelectionHighlightEnabled to True

*allow horizontal scrolling

*type sufficient characters so that I need to scroll the
text box to see them all

The selection highlighting works fine as long as the textbox has focus/is active. However, once it loses focus (but the selection highlight remains due to the IsInactiveSelectionHighlightEnabled being set to true), and if I scroll the text box using the scrollbar, the highlight does not scroll with the text. This essentially means the highlight is now highlighting different characters. If I hit tab to regain focus, the highlight correctly adjusts to highlight the correct characters again.
I can reproduce this very simply, by creating a WPF Desktop App (any .Net framework should be fine), and using this XAML within the Window tag:
<Grid>
    <StackPanel>
        <TextBox Height="50" Width="100" TextWrapping="NoWrap" IsInactiveSelectionHighlightEnabled="True" HorizontalScrollBarVisibility="Auto" Text="Hello" />
        <TextBox Height="50" Width="100" TextWrapping="NoWrap" IsInactiveSelectionHighlightEnabled="True" HorizontalScrollBarVisibility="Auto" Text="World" />
    </StackPanel>
</Grid>

With the above layout, just type sufficient characters to make one of the textbox show a scrollbar. Then highlight some characters at the start of that textbox. Then change focus to the other textbox. Then scroll the original textbox and you'll see the selection highlight different/incorrect characters. (You have to look closely since the inactive highlight is a very subtle effect with the default definition).
In other words, the selection highlight does not take the scroll position into account when the textbox is inactive.
I can't imagine this is the intended behavior. Where am I going wrong here?


text:
Q: Convert RGB image to YUV and YCbCr color space image in Opencv Python Can anyone help me to convert an RGB colour space image to YUV colour space image and to YCbCr colour space image using opencv Python?

A: Use cv2.cvtColor(src, code) to convert Color-Space, the code starts with COLOR_.
You can use this to look for the color code.
import cv2
## get all color codes
codes = [x for x in dir(cv2) if x.startswith("COLOR_")]

## print first three color codes
print(codes[:3])
# ['COLOR_BAYER_BG2BGR', 'COLOR_BAYER_BG2BGRA', 'COLOR_BAYER_BG2BGR_EA']

## print all color codes
print(codes)

If you read the image into BGR space, then use cv2.COLOR_BGR2YUV and cv2.COLOR_BGR2YCrCb:
#cv2.COLOR_BGR2YUV
#cv2.COLOR_BGR2YCrCb

img = cv2.imread("test.png")
yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
cv2.imwrite("yuv.png", yuv)

If you read the image into RGB space, then use cv2.COLOR_RGB2YUV and cv2.COLOR_RGB2YCrCb.

Here is an example image(in BGR-HSV-YUV-YCRCB color spaces):


text:
Q: CountDownLatch with a dynamic timeout I am using a CountDownLatch to wait for N operations to complete before executing some code, whilst giving a timeout to make sure that the final code gets executed even if not all N operations are completed.
i.e:
    CountDownLatch latch= new CountDownLatch(N);
    latch.await(20, TimeUnit.MINUTES);
    //Some code

I would like the 20 minutes timeout to be dynamic, so that it is reset each time the latch gets a countdown, so the latch will exit the await only if 20 minutes has passed since the last time it got a countdown (or the normal case ofcourse, when it recieves N countdowns). Is this supported in any way?

A: You can implement this feature in your own CountDownLatch. You can keep a timestamp of when the method countDown() is called, compare it to the timestamp when the waiting was started, adjust the waiting time and wait again if the timestamps are different. For example,
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class MyCountDownLatch extends CountDownLatch {
    private AtomicLong timestamp;

    public MyCountDownLatch(int count) {
        super(count);
        timestamp = new AtomicLong(System.nanoTime());
    }

    @Override
    public void countDown() {
        super.countDown();
        timestamp.set(System.nanoTime());
    }

    public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException {
        long start = timestamp.get();
        long diff = 0;
        for (;;) {
            boolean result = await(unit.toNanos(timeout) - diff, TimeUnit.NANOSECONDS);
            if (timestamp.get() == start) return result;
            start = timestamp.get();
            diff = System.nanoTime() - start;
        }
    }
}

And here is a test program:
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Test {

    public static void main(String[] args) throws InterruptedException {

        MyCountDownLatch latch = new MyCountDownLatch(3);

        // Create three workers and give them different work time
        Worker worker1 = new Worker("A", 1, latch);
        Worker worker2 = new Worker("B", 3, latch);
        Worker worker3 = new Worker("C", 5, latch);
        List<Worker> workers = Arrays.asList(worker1, worker2, worker3);

        // Start the workers
        workers.forEach(Worker::start);

        // Wait until the latch to count down to zero, or no countdown in
        // 3 seconds.
        boolean result = latch.waitFor(3, TimeUnit.SECONDS);
        System.out.printf("%s | latch.waitFor() returns %b\n", LocalTime.now(), result);

        // Terminate those workers who are still running
        workers.stream().filter(Worker::isAlive).forEach(Worker::interrupt);
    }

    static class Worker extends Thread {
        private String name;
        private int workTime;
        private CountDownLatch latch;

        public Worker(String name, int workTime, CountDownLatch latch) {
            this.name = name;
            this.workTime = workTime;
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                System.out.printf("%s | Worker %s started\n", LocalTime.now(), name);
                Thread.sleep(workTime * 1000L);
                System.out.printf("%s | Worker %s finished\n", LocalTime.now(), name);
            } catch (InterruptedException e) {
                System.out.printf("%s | Worker %s interrupted\n", LocalTime.now(), name);
            } finally {
                latch.countDown();
            }
        }
    }
}


text:
Q: Column 'content' cannot be null : SpringBoot I am trying to do a simple example of one to many mapping in spring boot using this link
https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-many-mapping-example/
I have done as it is. I am the running the application and it is working fine.
But when I make a post request to http://localhost:8080/posts it starts giving me errors which I am unable to resolve.
The body I include while making a post request is:
   {
    "title": "Post 1",
    "description": "Post 1 Description",
    "content": "Post 1 Content"
   }

The error is :
 2020-06-22 15:57:38.838  WARN 20216 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   :
 SQL Error: 1048, SQLState: 23000
 2020-06-22 15:57:38.838 ERROR 20216 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   :
 Column 'content' cannot be null
2020-06-22 15:57:38.873 ERROR 20216 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    :
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request
processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could
not execute statement; SQL [n/a]; constraint [null]; nested exception is
org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

Post.java:
package com.example.jpa.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
@Table(name = "posts")
public class Post extends AuditModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Size(max = 100)
@Column(unique = true)
private String title;

@NotNull
@Size(max = 250)
private String description;

@NotNull
@Lob
private String content;

public Object getTitle() {
    // TODO Auto-generated method stub
    return null;
}

public void setTitle(Object title2) {
    // TODO Auto-generated method stub

}

public Object getDescription() {
    // TODO Auto-generated method stub
    return null;
}

public void setDescription(Object description2) {
    // TODO Auto-generated method stub

}

public Object getContent() {
    // TODO Auto-generated method stub
    return null;
}

public void setContent(Object content2) {
    // TODO Auto-generated method stub

}

// Getters and Setters (Omitted for brevity)
}

PostController.java:
  package com.example.jpa.controller;

import com.example.jpa.exception.ResourceNotFoundException;
import com.example.jpa.model.Post;
import com.example.jpa.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
public class PostController {

@Autowired
private PostRepository postRepository;

@GetMapping("/posts")
public Page<Post> getAllPosts(Pageable pageable) {
    return postRepository.findAll(pageable);
}

@PostMapping("/posts")
public Post createPost(@Valid @RequestBody Post post) {
    return postRepository.save(post);
}

@PutMapping("/posts/{postId}")
public Post updatePost(@PathVariable Long postId, @Valid @RequestBody Post postRequest) {
    return postRepository.findById(postId).map(post -> {
        post.setTitle(postRequest.getTitle());
        post.setDescription(postRequest.getDescription());
        post.setContent(postRequest.getContent());
        return postRepository.save(post);
    }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + " not found"));
}

@DeleteMapping("/posts/{postId}")
public ResponseEntity<?> deletePost(@PathVariable Long postId) {
    return postRepository.findById(postId).map(post -> {
        postRepository.delete(post);
        return ResponseEntity.ok().build();
    }).orElseThrow(() -> new ResourceNotFoundException("PostId " + postId + " not found"));
}

}

First is column content cannot be null. But as you can see while making a post request content coulmn is not null. Kindly help?

A: may be Exception from mysql ,
please check "content" column data type is correct, (check date which are you passing to table is correct)

A: The getter setter are not proper,
public String getContent() {
    // TODO Auto-generated method stub
    return content;
}

public void setContent(String content) {
    // TODO Auto-generated method stub
    this.content = content

}


text:
Q: Reveal effect with android.support.design.circularreveal.cardview.CircularRevealCardView I wanted to create a reveal effect like WhatsApp's attachment feature. I while looking around to create something custom, I came across Android's android.support.design.circularreveal.cardview.CircularRevealCardView view available already without adding any external library.
I implemented this view like so :-
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.circularreveal.cardview.CircularRevealCardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/ccv_attachment_reveal"
    style="@style/style_mw"
    android:elevation="@dimen/dimen_2dp"
    android:orientation="vertical"
    android:padding="@dimen/dimen_margin_16dp"
    app:cardCornerRadius="@dimen/dimen_8dp"
    >

    <android.support.v7.widget.LinearLayoutCompat
        style="@style/style_mw"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/rl_attachment_first_row"
            style="@style/style_ww"
            android:layout_marginStart="@dimen/dimen_30dp"
            android:layout_marginTop="@dimen/dimen_margin_16dp"
            android:layout_marginEnd="@dimen/dimen_30dp">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab_add_gallery_image"
                style="@style/style_ww"
                android:layout_alignParentStart="true"
                android:src="@drawable/ic_gallery_image"/>

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab_add_camera_image"
                style="@style/style_ww"
                android:layout_centerHorizontal="true"
                android:src="@drawable/ic_camera"/>

        </RelativeLayout>

        <RelativeLayout
            style="@style/style_ww"
            android:layout_marginStart="@dimen/dimen_30dp"
            android:layout_marginTop="@dimen/dimen_margin_16dp"
            android:layout_marginEnd="@dimen/dimen_30dp"
            android:layout_marginBottom="@dimen/dimen_margin_16dp">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab_add_gallery_image1"
                style="@style/style_ww"
                android:layout_alignParentStart="true"
                android:src="@drawable/ic_gallery_image"/>

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/fab_add_camera_image1"
                style="@style/style_ww"
                android:layout_centerHorizontal="true"
                android:src="@drawable/ic_camera"/>
        </RelativeLayout>
    </android.support.v7.widget.LinearLayoutCompat>
</android.support.design.circularreveal.cardview.CircularRevealCardView>

This displays fine on my app like a regular CardView and I can set it visibile/invisible on a button click. But however I cannot find any implementations online showing how to apply the reveal animation while making this view visible. Is there an in built feature to apply the animation or do I have to create one myself?

A: Please try this
int x = layoutContent.getRight();
int y = layoutContent.getBottom();

int startRadius = 0;
int endRadius = (int) Math.hypot(layoutMain.getWidth(), layoutMain.getHeight());

Animator anim = ViewAnimationUtils.createCircularReveal(layoutButtons, x, y, startRadius, endRadius);

layoutButtons.setVisibility(View.VISIBLE);
anim.start();


text:
Q: React onChange rerender dynamic input fields strange When changing data in dynamic fields, my functional component copies the current field and redraws the field and adds it to the end of the form. I displayed input fields via Object.keys.map and put there state and check type with switch, after display text, number, checkbox fields together.
import React, { useState } from 'react'

const Form = () => {

  const [state, setState] = useState({
    companyName: "seenus",
    tradeName: "ТОРТАЙ О.А ИП",
    description: "",
    email: "olzhastortay@gmail.com",
    region: "Almaty",
    phone: "(707) 795-15-09",
    bin: "",
    code: "",
    isActive: true,
    merchant_terminal: {
      terminal_id: "98264471",
      saveCard: false,
      isActive: true,
      currencyName: "KZT",
      isAmexAllowed: false,
      sendBack: false,
      parentId: "",
      B64ENCODE: false,
      persLimit: 0,
      isRecurAllowed: false,
      shouldUseNewKey: true,
      minSum: 0,
      postlinkTries: 0,
      MCC: 0,
      dailyLimit: 0,
      isFromEpay1: false,
      permitted_countries: "",
      forbidden_countries: ""
    }
  })

  const iterate = (obj: any): any => {

    return Object.keys(obj).map((key) => {

      switch(typeof obj[key]) {
        case 'object':
          return iterate(obj[key])

        case 'string':

          return (

                <TextField
                  label={key}
                  variant="outlined"
                  defaultValue={obj[key]}
                  onChange={handleChange(key)}
                />

          )

        case 'number':

          return (

                <TextField
                  label={key}
                  variant="outlined"
                  type="number"
                  defaultValue={obj[key]}
                  onChange={handleChange(key)}
                />

          )

        case 'boolean':

          console.log('boolean inside')
          return (

              <FormControlLabel
                control={<Switch checked={obj[key]} onChange={handleChange(key)} />}
                label={key}
              />

          )

      }

    })

  }

  const handleChange = (prop: any) => (event: any) => {

    const {checked, value, type} = event.target

    switch (type) {
      case 'checkbox':
        return setState((prev: any) => ({...prev, [prop]: checked}))
      default:
        return setState((prev: any) => ({...prev, [prop]: value}))
    }

  }

  return (
    <form>

Страница нового коммерсанта

        { iterate(state) }

        <Button size="large" variant="contained" type="submit" color="primary">
            создать коммерсанта
        </Button>

    </form>
  )

}

export default Form

input fields IMAGE

A: const handleChange = (arr?: any) => (event: any) => {

        const {checked, value, type} = event.target

        let tmp = state
        const depth = arr.length -1

        for (let i = 0; i < arr.length; i++) {
          const depthKey = arr[i]

          if(i < depth) {
            tmp = tmp[depthKey]
          }
          if(i === depth) {
            tmp[depthKey] = (type === 'checkbox') ? checked : value
          }

        }

        return setState({...state})

      }

The problem was in state. Every time when I returned state with nested object, I was returing first depth of object.


text:
Q: Best jQuery Plugin For News i have 10 images and i want to show they with numbers(1,2,3,4,5...). I am talking about image slideshow with numbers. Can you suggest me jquery plugin for this ?

A: Cycle is nice and flexible. Check out the advacned examples Cycle Link

A: http://plugins.jquery.com/project/VisualLightbox
I tried several (of the many available plugins on the jquery website) and finally decided on this one.