text:
Q: Convert datetimeString from file to datetime object i am reading date from file in C++ and the data contains datetime string. i have extracted datetime string from file but unable to convert it into datetime object.
The goal is to calculate time difference between two dates.
I have time in this format:
2021-03-01 09:00:00
in string:
Start: 2021-03-01 09:00:00, Stop: 2021-03-01 14:32:31
See if anybody can help
Here is my code ;
if (!MyReadFile) {
    cout << "file not found";
}

int counter = 0;
map<string, string> times;
while (!MyReadFile.eof()) {
    string line;
    getline(MyReadFile, line);

    string start_time = line.substr(6, 20);
    string end_time = line.substr(33, 51);

    time_t t;

    auto t_start = chrono::high_resolution_clock::now();
    double elapsed_time_ms = chrono::duration<double, std::milli>(end_time - start_time).count();

    times[start_time] = end_time;

    counter++;
}

for (auto& item : times) {
    cout << item.first << ":" << item.second << " " << endl;
}

cout << "Frequency is " << counter << endl;
}

A: [Update]
I've updated the original accepted answer:

*

*Mainly to simplify the Pre C++20 code by using get_time and difftime.

*To work in seconds, since the input values are in seconds.

*

*You don't need a counter if you want to count the file lines that contain different start/stop date pairs. You can just query times map's size at the end of your loop.

*You cannot either subtract strings, let alone expect that subtracting two strings containing text representing a date gives you the elapsed time between the two dates as output. (You can though use operator+ to join two strings together.)
In short, what you can do is:

*

*Read each file line, checking if it contains a start and a stop date. And if it does, parse the date and time fields out of each one.

*Construct a date and time object out of those date and time fields, and use the start and stop objects to compute an elapsed time.

In the code below:

*

*I've assumed you may want to use a std::map<std::pair<start_date_string, stop_date_string>, elapsed_time_ms>, i.e., a map where the key is a pair of start date/stop date strings, and the value is an elapsed time in ms (double). That way, when you print the results, you can output both the date strings and the elapsed time.

*I only use a file line for testing purposes.

*Since input times are in seconds, I calculate time differences in seconds as well. [Updated]

Pre C++20 [Updated]

*

*You can use get_time to directly parse the file line into a couple of tm structs.

*Then turn those tm structs to time_t structs, from which we can compute the elapsed time by using difftime.

https://godbolt.org/z/js3MY7Gnn
#include <ctime>  // tm, difftime
#include <iomanip>  // get_time
#include <iostream>  // cout
#include <map>  // map
#include <utility>  // pair
#include <sstream>  // istringsteam
#include <string>  // string

int main()
{
    // File line
    const std::string line{"Start: 2021-03-01 09:00:00, Stop: 2021-03-01 14:32:31"};

    // Map of elapsed times for each start date/stop date pair of strings
    std::map<std::pair<std::string, std::string>, double> times;

    // Check if file line matches our pattern
    std::istringstream iss{line};
    tm start_tm{};
    tm stop_tm{};
    if (iss >> std::get_time(&start_tm, "Start: %Y-%m-%d %H:%M:%S") and
        iss >> std::get_time(&stop_tm, ", Stop: %Y-%m-%d %H:%M:%S"))
    {
        // Convert tm to time_t
        auto start_tt{mktime(&start_tm)};
        auto stop_tt{mktime(&stop_tm)};

        // Calculate elapsed time in s between the start and stop time_t
        double elapsed_time_s = std::difftime(stop_tt, start_tt);

        // Read start and stop dates into a pair of strings
        auto dt_strs{ std::make_pair(line.substr(7, 19), line.substr(34, 19)) };

        // Add results to the map
        times[dt_strs] = elapsed_time_s;
    }

    // Print the map
    for (const auto& [dt_strs, time] : times)
    {
        std::cout << dt_strs.first << ", " << dt_strs.second << " = " << time << "\n";
    }
}

// Outputs:
//     2021-03-01 09:00:00, 2021-03-01 14:32:31 = 19951

C++20
The std::chrono library simplifies things even more. We can now parse the file line directly into a couple of time points, and compute the elapsed time from those time points. So we save a conversion between time structs.
#include <chrono>  // duration, from_stream, sys_time
#include <iostream>  // cout
#include <map>  // map
#include <utility>  // pair
#include <sstream>  // istringstream
#include <string>  // string

int main()
{
    // File line
    const std::string line{ "Start: 2021-03-01 09:00:00, Stop: 2021-03-01 14:32:31" };

    // Map of elapsed times for each start date/stop date pair of strings
    std::map<std::pair<std::string, std::string>, double> times;

    // Read each date and time field into a couple of time points
    std::istringstream iss{ line };
    std::chrono::sys_time<std::chrono::seconds> start_tp{};
    std::chrono::sys_time<std::chrono::seconds> stop_tp{};
    if (std::chrono::from_stream(iss, "Start: %F %T", start_tp) and
        std::chrono::from_stream(iss, ", Stop: %F %T", stop_tp))
    {
        // Calculate elapse time in s between the start and stop time points
        double elapsed_time_s = std::chrono::duration<double>(stop_tp - start_tp).count();

        // Read start and stop dates into a pair of strings
        auto dt_strs{ std::make_pair(line.substr(7, 19), line.substr(34, 19)) };

        // Add results to the map
        times[dt_strs] = elapsed_time_s;
    }

    // Print the map
    for (const auto& [dt_strs, time] : times)
    {
        std::cout << dt_strs.first << ", " << dt_strs.second << " = " << time << "\n";
    }
}

// Outputs:
//     2021-03-01 09:00:00, 2021-03-01 14:32:31 = 19951

I have only been able to test this with VS2019. Compiler Explorer complained saying from_stream was no part of std::chrono when I tried compiling with x86-64 gcc (trunk) and x86-64 clang (trunk) [ -std=c++20 ]; x64 msvc v.19latest [ /std:c++latest ] compiles but doesn't execute the code.


text:
Q: How to trigger field validation at Ant design form with custom validation func I have password reset form:
  {formItem(
          props.form.getFieldDecorator('currentPassword', {
        rules: [{ min: 6 },
          { validator: maybeMustBeRequared }
        ],
          })(<Input type="password" />),
          {
            label: tUsers.currentPassword,
          },
        )}
        {formItem(
          props.form.getFieldDecorator('newPassword', {
            rules: [{ min: 6 }],
          })(<Input type="password" />),
          {
            label: tUsers.newPassword,
          },
        )}
        {formItem(
          props.form.getFieldDecorator('confirmPassword', {
            rules: [
              { min: 6 },
              {
                validator: compareToFirstPassword,
              },
            ],
          })(<Input type="password" />),
          {
            label: tUsers.confirmPassword,
          },
        )}

my goal revalidates password password field when newPassword or confirmPassword is not empty.
const maybeMustBeRequared = (rule, value, callback) => {
    console.log('rule', rule)
    if (!isEmpty(props.form.getFieldValue('newPassword')) || !isEmpty(props.form.getFieldValue('confirmPassword'))  ) {
      // there I want trigger passwor field validation { min: 6}
    } else {
      callback()
    }
  }

A: Although I think you don't need such validator in your case, both rules min: 6 are enough.
But still you can try this:
  passwordLength = (rule, value, callback) => {
    const { form } = this.props;
    const confirmPassword = form.getFieldValue('confirmPassword');
    if (value || confirmPassword) {
      rule.validate('confirmPassword');
    } else {
      callback('Im Here');
    }
  };

redpajama_set_name: RedPajamaStackExchange


text:
Q: Testing for Nested q-card-section using Vue Test Utils I am using Quasar 2 Vue 3 and I have the following template in a vue component which I would like to test:
<template>
  <q-card>
    <q-card-section class="no-padding">
      <q-btn
        flat
        no-caps
        class="q-ma-sm"
        icon="navigate_before"
        :label="store.name"
        v-close-popup
      />
    </q-card-section>
    <q-separator />
    <q-card-section id="products"
      :style="`height: ${$q.screen.height - 108}px`"
      class="scroll"
    >
      <q-card-section id="productdetails"
        v-for="(product, index) in productList"
        :key="index"
        class="row items-center bg-white text-black"
      >
        <div class="col-5 cursor-pointer" @click="onProductClick(product)">
          <q-item-label class="text-subtitle2">
            {{ product.productName }}
          </q-item-label>
          <q-item-label v-if="product.modifiers.length > 0" caption lines="2">
            {{ getdetails(product) }}
          </q-item-label>
        </div>
<snip>

I am not able to retrieve the #productdetails q-card-section in my test code:
import { qLayoutInjections, installQuasarPlugin } from '@quasar/quasar-app-extension-testing-unit-jest';
import { DOMWrapper, mount } from '@vue/test-utils';
import { QBtn, } from 'quasar';
import Store from "../../../../src/store/index";
import MyComponent from '../../../../src/components/MyComponent';
installQuasarPlugin();
describe('MyComponent', () => {
  let myComponent;
  beforeEach(() => {
    myComponent = mount(MyComponent, {
      global: { plugins: [Store], provide: qLayoutInjections() },
      });
  });
  it('Renders a value from $store.state', () => {
    expect(myComponent).toBeTruthy();

    const qcard = myComponent.find('.q-card');
    expect(qcard.exists()).toBe(true);

    const products = qcard.find("#products");
    expect(products.exists()).toBeTruthy();

    const productdetails = products.find("#productdetails");
    expect(productdetails.exists()).toBeTruthy();
  })

 FAIL  test/jest/__tests__/components/MyComponent.test.js
  ● MyComponent › Renders a value from $store.state

    expect(received).toBeTruthy()

    Received: false

      36 |
      37 |     const productdetails = products.find("#productdetails");
    > 38 |     expect(productdetails.exists()).toBeTruthy();

Any advice and insight is appreciated.


text:
Q: Debug remote pyc/pyo files I try to debug pyc/pyo files, but fail because of  Non-ASCII characters ('\xd1').
Pudb does run against the py files, but due to limitations in the specific environment, i need to run it on pyo/pyc files.
Did anyone face this issue? do you have any idea / solution?
Thanks in advance!
EDIT:
I received an answer on the PuDB mailing list and was told that one can't debug pyc/pyo files using PuDB which is a source-level debugger.
So i wonder if someone here faced a similar situation (debugging pyc/pyo files) and have the right tool for the mission. A colleague of mine uses WingIDE for that, so he runs the debugger on py files in his IDE against remote pyc files. Are there known non-IDE solutions?


text:
Q: usbmount scripting I'm trying to create a script that will automatically format a USB flash drive when inserted, However there is an internal usb flash drive in the device, how would I go about making an exclusion of that device (unit will never turn on again if this drive is formatted).
Thanks!

A: You could check for the USB ID (obtain it via lsusb).


text:
Q: CSS - Add border color on clip path polygon I'm working with clip path for the first time and i need to add a border in this shape. Anyone can explain me how to do that?

.image-center {
  width: 300px;
  height: 300px;
  margin: 0 auto;
}
.shape {
  width: 300px;
  height: 300px;
  -webkit-clip-path: polygon(15% 0, 70% 0, 100% 50%, 70% 100%, 15% 100%, 0 70%, 20% 50%, 0% 30%);
  clip-path: polygon(15% 0, 70% 0, 100% 50%, 70% 100%, 15% 100%, 0 70%, 20% 50%, 0% 30%);
}
img {
  width: 300px;
  height: 300px;
}

A: You can fake it with several drop shadow filters. There isn't much support, but cli path doesn't have much either ...

.image-center {
  width: 300px;
  height: 300px;
  margin: 0 auto;
  -webkit-filter: drop-shadow(2px 2px 0px red)
    drop-shadow(2px -2px 0px red)
    drop-shadow(-2px 2px 0px red)
    drop-shadow(-2px -2px 0px red);
  filter: drop-shadow(2px 2px 0px red)
    drop-shadow(2px -2px 0px red)
    drop-shadow(-2px 2px 0px red)
    drop-shadow(-2px -2px 0px red);
}
.shape {
  width: 300px;
  height: 300px;
  -webkit-clip-path: polygon(15% 0, 70% 0, 100% 50%, 70% 100%, 15% 100%, 0 70%, 20% 50%, 0% 30%);
  clip-path: polygon(15% 0, 70% 0, 100% 50%, 70% 100%, 15% 100%, 0 70%, 20% 50%, 0% 30%);
}
img {
  width: 300px;
  height: 300px;
}


text:
Q: Oracle: Get column names of Top n values over multiple columns My question is similar to
https://community.oracle.com/message/4418327

in my query i need the MAX value of 3 different columns.
example: column 1 = 10, column 2 = 20, column 3 = 30 > output should
  be 30. i need this MAX value to sort the list by it.

However instead of the actually value I need the column name and ideally not just the max one but top 3 as example.
The desired output would then be
ID    first    second    third
-------------------------------
1    column 3  column 2  column1

A: Not sure if there is a better way of doing this, but here's a possible solution using the CASE statement. Here's the table structure I've tested it on:
CREATE TABLE MAX_COL(
  "ID" INT,
  COLUMN_1 INT,
  COLUMN_2 INT,
  COLUMN_3 INT
);

And here's the SQL I used:
SELECT
  "ID",
  CASE
    WHEN COLUMN_1 > COLUMN_2 AND COLUMN_1 > COLUMN_3 THEN 'COLUMN_1'
    WHEN COLUMN_2 > COLUMN_1 AND COLUMN_2 > COLUMN_3 THEN 'COLUMN_2'
    WHEN COLUMN_3 > COLUMN_2 AND COLUMN_3 > COLUMN_1 THEN 'COLUMN_3'
    ELSE 'NONE'
  END AS "FIRST",
  CASE
    WHEN COLUMN_1 > COLUMN_2 AND COLUMN_1 < COLUMN_3 THEN 'COLUMN_1'
    WHEN COLUMN_2 > COLUMN_1 AND COLUMN_2 < COLUMN_3 THEN 'COLUMN_2'
    WHEN COLUMN_3 > COLUMN_2 AND COLUMN_3 < COLUMN_1 THEN 'COLUMN_3'
    ELSE 'NONE'
  END AS "SECOND",
  CASE
    WHEN COLUMN_1 < COLUMN_2 AND COLUMN_1 < COLUMN_3 THEN 'COLUMN_1'
    WHEN COLUMN_2 < COLUMN_1 AND COLUMN_2 < COLUMN_3 THEN 'COLUMN_2'
    WHEN COLUMN_3 < COLUMN_2 AND COLUMN_3 < COLUMN_1 THEN 'COLUMN_3'
    ELSE 'NONE'
  END AS "THIRD"
FROM
  MAX_COL;

Please note that you will need to deal with situations where one or more columns have the same value. In this case I am just returning 'NONE' if this occurs, but you may want to do something else.
UPDATE
You could also use PLSQL functions to achieve this, which may be easier to use for many columns. Here's an example:
CREATE OR REPLACE
FUNCTION COLUMN_POSITION (IDVAL INT, POSITION INT) RETURN VARCHAR2 AS
  TYPE COLUMN_VALUE_TYPE IS TABLE OF NUMBER INDEX BY VARCHAR2(64);
  COLS COLUMN_VALUE_TYPE;
  COL_KEY VARCHAR2(64);
  QUERY_STR VARCHAR2(1000 CHAR) := 'SELECT COL FROM(SELECT T.*, DENSE_RANK() OVER (ORDER BY VAL DESC) AS RANK FROM (';
  COL_NAME VARCHAR2(64);
BEGIN
  COLS('COLUMN_1') := NULL;
  COLS('COLUMN_2') := NULL;
  COLS('COLUMN_3') := NULL;
  --ADD MORE COLUMN NAMES HERE...

  COL_KEY := COLS.FIRST;

  LOOP
    EXIT WHEN COL_KEY IS NULL;
    QUERY_STR := QUERY_STR || 'SELECT ' || COL_KEY || ' AS VAL, '''|| COL_KEY ||''' AS COL FROM MAX_COL WHERE ID = '|| IDVAL ||' UNION ALL ';
    COL_KEY := COLS.NEXT(COL_KEY);
  END LOOP;

  QUERY_STR := SUBSTR(QUERY_STR, 0, LENGTH(QUERY_STR) - 11);
  QUERY_STR := QUERY_STR || ') T ) WHERE RANK = ' || POSITION;

  EXECUTE IMMEDIATE QUERY_STR INTO COL_NAME;

  RETURN COL_NAME;
END;

This example has only 3 columns but you could easily add more. You can then use this in a query like this:
SELECT
  MAX_COL.*,
  COLUMN_POSITION(ID, 1) AS "FIRST",
  COLUMN_POSITION(ID, 2) AS "SECOND",
  COLUMN_POSITION(ID, 3) AS "THIRD"
FROM MAX_COL

A: There is no built-in function for what you are asking. So user1578653's answer is good, straight-forward and fast. Another way would be to write a function with PL/SQL.
In case you want to use pure SQL, but want it easier to add columns to the comparision, then if you are satisfied with just two columns (id and column names string), you can do this:
select id, listagg(colname, ', ') within group (order by value desc) as columns
from
(
  select id, 'column1' as colname, col1 as value from mytable
  union all
  select id, 'column2' as colname, col2 as value from mytable
  union all
  select id, 'column3' as colname, col3 as value from mytable
  -- add more columns here, if you wish
)
group by id;

Be aware this is slower than user1578653's SQL statement, as the table is being read three times. (I also treat equal values differently here, same values lead to random order.)

A: You can use PIVOT/UNPIVOT for this.
Fisrt UNPIVOT your table and assign rank with values ordered in descending order.
create table sample(
  id number,
  col1 number,
  col2 number,
  col3 number
  );

insert into sample values(1,10,20,30);
insert into sample values(2,10,20,15);

select id, col_name, val,
       row_number() over (partition by id order by val desc) r
from sample
unpivot(val for col_name in (
        col1 AS 'col1', col2 AS 'col2', col3 AS 'col3')
       );

Output:
| ID | COL_NAME | VAL | R |
|----|----------|-----|---|
|  1 |     col3 |  30 | 1 |
|  1 |     col2 |  20 | 2 |
|  1 |     col1 |  10 | 3 |
|  2 |     col2 |  20 | 1 |
|  2 |     col3 |  15 | 2 |
|  2 |     col1 |  10 | 3 |

sqlfiddle.
Next PIVOT the col_name based on the rank column.
with x(id, col_name, val,r) as (
  select id, col_name, val,
         row_number() over (partition by id order by val desc)
  from sample
  unpivot(val for col_name in (
          col1 AS 'col1', col2 AS 'col2', col3 AS 'col3')
         )
  )
select * from (
  select id, col_name, r
  from x
  )
pivot(max(col_name) for r in (
  1 as first, 2 as second, 3 as third)
      );

Output:
| ID | FIRST | SECOND | THIRD |
|----|-------|--------|-------|
|  1 |  col3 |   col2 |  col1 |
|  2 |  col2 |   col3 |  col1 |

sqlfiddle.

A: SELECT
  (CASE
    WHEN A > B AND A > C THEN 'A'
    WHEN B > A AND B > C THEN 'B'
    WHEN C > B AND C > A THEN 'C'
  END) AS "MaxValue_Column_Name",
greatest(A,B,C) AS Max_Value FROM  max_search   ;
--table name =max_search and column_name are A,B and C


text:
Q: Find the minimum of $\sum_{i=0}^n(i^n-P(i))^2$ with $P$ in $\mathbb{R}_{n-1}[X]$ This is an exercise I liked to solve and I wanted to share it.

Find the minimum of $\displaystyle\sum_{i=0}^n(i^n-P(i))^2$ with $P$ in $\mathbb{R}_{n-1}[X]$

Where $\mathbb{R}_{p}[X]$ denotes the ring of real polynomials whose degree is at most $p$
Do not hesitate to comment and share your thoughts. Feel free to correct me (especially my English).

A: First of all, I thought of using the inner product on $\mathbb{R}_{n}[X]$ defined by:
$$\langle  P|Q\rangle = \sum_{i=0}^nP(i)Q(i)$$

Proof it is an inner product:
$\bullet$ $\mathbb{R}_{n}[X]$ is a real vector space and $\langle \cdot | \cdot \rangle$ is well defined.
$\bullet$ $\forall  (P,Q) \in(\mathbb{R}_{n}[X])^2, \, \displaystyle \langle  P|Q\rangle = \sum_{i=0}^nP(i)Q(i) = \sum_{i=0}^nQ(i)P(i) = \langle  Q|P\rangle $ so  $\langle \cdot | \cdot \rangle$ is symmetric.
$\bullet \, \forall  (P,Q,R) \in(\mathbb{R}_{n}[X])^3, \forall\lambda \in \mathbb{R},$
$$ \langle P+\lambda Q |R\rangle = \displaystyle \sum_{i=0}^n (P+\lambda Q)(i) R(i)=\sum_{i=0}^nP(i)R(i)+\lambda\sum_{i=0}^nQ(i)R(i) = \langle  P|R\rangle+\lambda \langle  Q|R\rangle$$
Hence $\langle \cdot | \cdot \rangle$ is linear on the left, but as it is symmetric, it is also linear on the right. Therefore $\langle \cdot | \cdot \rangle$ is bilinear.
$\bullet$ For all $P \in \mathbb{R}_{n}[X]$, we have,
$$\langle P | P \rangle = \sum_{i=0}^n P(i)^2\geq0$$
Moreover,
if $\langle P | P \rangle =0$ then for all $i \in \{0,\dots,n\}, P(i) = 0$, therefore $P$ has at least $n+1$ roots and its degree is at most $n$, hence $P=0$. This proves the positive definiteness.

Consequently, as $\langle  \cdot|\cdot\rangle$ is an inner product let $\lVert \cdot \rVert$ denote its related norm. We have by the theorem of the orthogonal projection,
$$\min_{P \in \mathbb{R}_{n-1}[X]} \left( \displaystyle\sum_{i=0}^n(i^n-P(i))^2 \right) = \min_{P \in \mathbb{R}_{n-1}[X]} \lVert X^n -P \rVert^2 = \left(\min_{P \in \mathbb{R}_{n-1}[X]} \lVert X^n -P \rVert\right)^2 = \lVert X^n -p(X^n)\rVert^2$$
Where $p(X^n)$ is the orthogonal projection of $X^n$ on  $\mathbb{R}_{n-1}[X]$.

Let $Q = X^n-p(X^n)$. As $p(X^n) \in \mathbb{R}_{n-1}[X]$ one can see that $Q$ is a monic polynomial and $n$ is its degree.
For all $1\leq\ell\leq n$, let $Q_{\ell} = \displaystyle \prod_{\substack{i=1\\i \neq \ell}}^n(X-i) \in \mathbb{R}_{n-1}[X]$. Because $Q$ is orthogonal to every polynomial in $\mathbb{R}_{n-1}[X]$ we have,
$$\forall 1\leq\ell\leq n, \langle Q |Q_{\ell} \rangle =0$$
thus for  $1\leq\ell\leq n$,
$$\sum_{i=0}^{n} Q(i)Q_{\ell}(i) =0$$
So,
$$Q(\ell)Q_{\ell}(\ell)+Q(0)Q_{\ell}(0)=0$$
Thus,
$$\forall 1 \leq \ell \leq n, \quad Q(\ell) = -\frac{Q_{\ell}(0)}{Q_{\ell}(\ell)} Q(0) = -\frac{(-1)^{n-1}n!/\ell}{(\ell-1)!(-1)^{n-\ell}(n-\ell)!}Q(0) = (-1)^{\ell} \binom{n}{\ell}Q(0)$$
And this result is also true when $\ell=0$.
We can deduce that,
$$\lVert Q \rVert^2 = \sum_{i=0}^n Q(i)^2 = \sum_{i=0}^n \binom{n}{i}^2 Q(0)^2 =Q(0)^2 \sum_{i=0}^n \binom{n}{i}^2 $$
Moreover using Lagrange polynomials,
$$Q = \sum_{\ell=0}^{n}Q(\ell) \prod_{\substack{i=0\\i \neq \ell}}^n\dfrac{X-i}{\ell-i}$$
We can see that the coefficient before $X^n$ in $Q$ is $1$ ($Q$ is monic) but also:
$$ \sum_{\ell=0}^{n}Q(\ell) \prod_{\substack{i=0\\i \neq \ell}}^n\dfrac{1}{\ell-i} = 1 $$
Therefore,
$$ \sum_{\ell=0}^n (-1)^{\ell} \binom{n}{\ell}Q(0) \dfrac{(-1)^{n-\ell}}{\ell! (n-\ell)!}=1 $$
Hence,
$$(-1)^n \dfrac{Q(0)}{n!} \sum_{\ell=0}^{n} \binom{n}{\ell}^2 = 1$$
So,
$$Q(0) = (-1)^n n! \left(\sum_{\ell=0}^{n} \binom{n}{\ell}^2\right)^{-1}$$
By expanding $(1+X)^{2n} = (1+X)^n(1+X)^n$ with binomial expansion and identifying the term before $X^n$, we end up with:
$$\sum_{\ell=0}^{n} \binom{n}{\ell}^2 = \binom{2n}{n} = \dfrac{(2n)!}{(n!)^2} $$
Therefore,
$$\lVert Q \rVert^2 = \left((-1)^n n! \left(\sum_{\ell=0}^{n} \binom{n}{\ell}^2\right)^{-1} \right)^2 \sum_{\ell=0}^{n} \binom{n}{\ell}^2 = (n!)^2 \dfrac{(n!)^2}{(2n)!}=\dfrac{(n!)^4}{(2n)!}$$

To conclude,
$$\boxed{\min_{P \in \mathbb{R}_{n-1}[X]} \left( \displaystyle\sum_{i=0}^n(i^n-P(i))^2 \right)
= \dfrac{(n!)^4}{(2n)!}}$$


text:
Q: Chat bug: tags has got too small line-height That's a terrible bug!
An upper tag is eating lower tag!
Obviously, I mean that a tag in the next line eats the border of the tag on the previous line.
Not that it's a problem, though, but I had to report it.


text:
Q: Drawing QR code with Qt in native C/C++ I am successfully drawing and displaying the QrCode on a QLabel, but it's not recognised when I scan it. Here is the code I used - I made a small class with a static function:
void QrCodeDrawer::paintQR(QPainter &painter, const QSize sz, const QString &data, QColor fg)
{
    char *str=data.toUtf8().data();
    // NOTE: At this point you will use the API to get the encoding and format you want, instead of my hardcoded stuff:
    QrCode qr = QrCode::encodeText(str, QrCode::Ecc::HIGH);
    const int s=qr.size>0?qr.size:1;
    const double w=sz.width();
    const double h=sz.height();
    const double aspect=w/h;
    const double size=((aspect>1.0)?h:w);
    const double scale=size/(s+2);
    // NOTE: For performance reasons my implementation only draws the foreground parts in supplied color.
    // It expects background to be prepared already (in white or whatever is preferred).
    painter.setPen(Qt::NoPen);
    painter.setBrush(fg);
    for(int y=0; y<s; y++) {
        for(int x=0; x<s; x++) {
            const int color=qr.getModule(x, y);  // 0 for white, 1 for black
            if(0x0!=color) {
                const double rx1=(x+1)*scale, ry1=(y+1)*scale;
                QRectF r(rx1, ry1, scale, scale);
                painter.drawRects(&r,1);
            }
        }
    }
}

And called it here:
QPixmap map(400,400);
QPainter painter(&map);
QrCodeDrawer::paintQR(painter,QSize(400,400),"Hello World", QColor("white"));
ui.qrCode->setPixmap(map);

I gave "Hello World" as input string and here is the code I get:

I got the source code from here.

A: I used the same sample but had problems with garbage QR codes until I realised str can be a dangling pointer. I changed my code to this and it worked fine:
void QrCodeDrawer::paintQR(QPainter &painter, const QSize sz, const QString &data, QColor fg)
{
    // NOTE: At this point you will use the API to get the encoding and format you want, instead of my hardcoded stuff:
    QrCode qr = QrCode::encodeText(data.toUtf8().constData(), QrCode::Ecc::HIGH);

A: I finally solved it, by drawing the background first(white or any) and then draw the qr code on top of it with a different enough color...
void paintQR(QPainter &painter, const QSize sz, const QString &data, QColor fg, QColor bg)
{
    char *str=data.toUtf8().data();
    // NOTE: At this point you will use the API to get the encoding and format you want, instead of my hardcoded stuff:
    QrCode qr = QrCode::encodeText(str, QrCode::Ecc::HIGH);
    const int s=qr.size>0?qr.size:1;
    const double w=sz.width();
    const double h=sz.height();
    const double aspect=w/h;
    const double size=((aspect>1.0)?h:w);
    const double scale=size/(s+2);

    painter.setPen(Qt::NoPen);
    // Setting the background color....
    painter.setBrush(bg);
    for(int y=0; y<400; y++) {
        for(int x=0; x<400; x++) {
            const double rx1=(x+1)*scale, ry1=(y+1)*scale;
            QRectF r(x, y, 1, 1);
            painter.drawRects(&r,1);
        }
    }
    //Drawing the Code....
    painter.setBrush(fg);
    for(int y=0; y<s; y++) {
        for(int x=0; x<s; x++) {
            const int color = qr.getModule(x, y);  // 0 for white, 1 for black
            if(0x0!=color) {
                const double rx1=(x+1)*scale, ry1=(y+1)*scale;
                QRectF r(rx1, ry1, scale, scale);
                painter.drawRects(&r,1);
            }
        }
    }
}

A: Just curious, if it is possible to ask for all of the code to make it work?
I am starting from complete nothing with my son, and he wants to make a QRcode generator, I thought if we could get one working we can study from there.
Best,
Mike


text:
Q: Pass ATTR{idVendor} as argument in udev script I have a script which is run whenever a usb device by vendor 1004 is connected. The udev rule I am using works and looks like this.
SUBSYSTEM=="usb", ATTR{idVendor}=="1004", RUN+="/var/www/beta/trigger.php"

Now I would like to have this script run whenever ANY usb device is connected, and pass the Vendor ID as parameter. (So the script can decide whether it has to be run or not.)
Adding a parameter which can be accessed in the script has worked so far:
SUBSYSTEM=="usb", RUN+="/var/www/beta/trigger.php myparam"

Can someone please tell me how to replace "myparam" with the value of ATTR{idVendor}? I have tried all kinds of combinations, but I never got the expected result...
Thanks a lot!

A: Just to add on to this answer, udev also lets you pass arguments to RUN and PROGRAM.
From the udev man page:
   The NAME, SYMLINK, PROGRAM, OWNER, GROUP, MODE and RUN fields support simple
   printf-like string substitutions. The RUN format chars gets applied after
   all rules have been processed, right before the program is executed. It
   allows the use of device properties set by earlier matching rules. For all
   other fields, substitutions are applied while the individual rule is being
   processed.

For example, you could have a rule like this:
# Passes major, minor and serial number as parameters to script.
ACTION=="add", SUBSYSTEM=="usb", RUN+="/tmp/test.sh %M %m $attr{serial}"

The available substitutions are:
    $kernel, %k
       The kernel name for this device.

   $number, %n
       The kernel number for this device. For example, ´sda3´ has kernel number
       of ´3´

   $devpath, %p
       The devpath of the device.

   $id, %b
       The name of the device matched while searching the devpath upwards for
       SUBSYSTEMS, KERNELS, DRIVERS and ATTRS.

   $driver
       The driver name of the device matched while searching the devpath
       upwards for SUBSYSTEMS, KERNELS, DRIVERS and ATTRS.

   $attr{file}, %s{file}
       The value of a sysfs attribute found at the device, where all keys of
       the rule have matched. If the matching device does not have such an
       attribute, follow the chain of parent devices and use the value of the
       first attribute that matches. If the attribute is a symlink, the last
       element of the symlink target is returned as the value.

   $env{key}, %E{key}
       A device property value.

   $major, %M
       The kernel major number for the device.

   $minor, %m
       The kernel minor number for the device.

   $result, %c
       The string returned by the external program requested with PROGRAM. A
       single part of the string, separated by a space character may be
       selected by specifying the part number as an attribute: %c{N}. If
       the number is followed by the ´+´ char this part plus all remaining
       parts of the result string are substituted: %c{N+}

   $parent, %P
       The node name of the parent device.

   $name
       The current name of the device node. If not changed by a rule, it
       is the name of the kernel device.

   $links
       The current list of symlinks, separated by a space character. The
       value is only set if an earlier rule assigned a value, or during a
       remove events.

   $root, %r
       The udev_root value.

   $sys, %S
       The sysfs mount point.

   $tempnode, %N
       The name of a created temporary device node to provide access to the
       device from a external program before the real node is created.

   %%
       The ´%´ character itself.

   $$
       The ´$´ character itself.

A: udev sets for you several environmental variables that you can use, among others ID_VENDOR. Try that little script:
#!/bin/bash

echo "Called by udev" >> /tmp/testenv
env >> /tmp/testenv
echo "Vendor id is $ID_VENDOR" >> /tmp/testenv

Put it in a rule, and you will see how much things are set up for you.


text:
Q: "document.write" sobreescreve a página ao chamar função Ao puxar a função JS, os elementos da página somem e a table aparece. Como posso resolver o que está causando esse sumiço?

function Gerar() {
  document.write("
");
  document.write("
");
  document.write("celula	");
  document.write("
");
  document.write("
");
}

Caça-Palavras

    <form>
      Conteudo da pagina

      <button onClick="Gerar()">Gerar</button>
    </form>

A: Normalmente document.write é usado em JS para compor partes de uma página durante sua carga (por sinal, seu uso é desencorajado por uma série de razões e efeitos colaterais).
Ocorre que sua função está sendo chamada depois do HTML original já ter sido servido e o DOM já montado. Isso faz com que implicitamente, na primeira ocorrência, seja chamado um document.open, efetivamente sobreescrevendo o documento original.
Da própria documentação da MDN:

Note: Because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document.

que traduzido é:

Nota: à medida que document.write grava no fluxo de documentos, chamando document.write em um documento fechado (carregado) invoca automaticamente document.open, que limpará o documento.

Mesmo resolvendo esta parte, ainda tem o problema do botão enviar o form (é o comportamento do button), o que pode não ser desejável nesse caso.
Isso se resolve com <button type="button"> (dá para suprimir o evento de submit, mas melhor é nem disparar).
Solução substituindo o document.write por innerHTML:
Uma possível solução para criar conteúdo em um documento já existente é substituindo o conteúdo HTML de um elemento.
Para fins de exemplo usaremos

, mas pode adaptar para qualquer elemento:

function Gerar() {
  var output = document.getElementById('output');
  output .innerHTML = '
';          // Primeiro usamos =
  output .innerHTML += '
';            // depois += para acrescentar
  output .innerHTML += 'CONTEUDO GERADO	';
  output .innerHTML += '
';
  output .innerHTML += '
';
}

  <form>
    Conteudo preexistente da pagina

    <button type="button" onClick="Gerar()">Gerar</button>

  </form>

Se fosse um conteúdo puramente textual, poderiamos usar innerText.
Alternativamente, criando conteúdo diretamente no DOM:
Com document.createElement podemos criar qualquer elemento do HTML, e para inserir um elemento dentro de outro usamos document.appendChild (tem outras maneiras, mas vamos focar nessas bem corriqueiras):

function Gerar() {
  var output = document.getElementById('output');
  var table  = document.createElement('table');
  var tr     = document.createElement('tr');
  var td     = document.createElement('td');
  td.innerText = 'CONTEUDO GERADO';
  tr.appendChild(td);
  table.appendChild(tr);
  output.appendChild(table);
}

  <form>
    Conteudo preexistente da pagina

    <button type="button" onClick="Gerar()">Gerar</button>

  </form>


text:
Q: Contar municipios de una sola entidad en Microsoft Access Tengo un examen de Access 2010 para oposición este fin de semana y éste es el único ejercicio que no he conseguido hacer por mi cuenta de los que nos entregó la academia, así que agradecería que me ayudaran para ir un poco más tranquilo al examen.
Tengo una primera tabla con dos claves primarias, una de municipios y otra de entidades.
Hay municipios con una sola entidad y municipios con varias, como puede verse en el screenshot de la tabla:

Tengo una segunda tabla relacionada por la clave de municipio que tiene el siguiente aspecto:

La pregunta del ejercicio es cuántos municipios tienen una sola entidad.
Imagino que habrá de solucionarse a través de una consulta a la primera tabla, pero no alcanzo a ver cómo.

A: Solo se me ocurre mediante una subconsulta
Por un lado tenemos la lista de municipios con una sola entidad:
select Id_Municipio, count(Id_Entidad)
from Entidades
Group by Id_Municipio
Having count(Id_Entidad) = 1

Para contar el número de municipios, contamos el resultado de la consulta anterior
select count(Id_Municipio)
from (
    select Id_Municipio, count(Id_Entidad) as Entidades
    from Entidades
    Group by Id_Municipio
    Having count(Id_Entidad) = 1
) a


text:
Q: rails will_paginate with different partials I have some new actions for the notification model and things started getting messy so I refactored from <% = render @other_notifications %> with notifcations/_notification.html.erb to the following structure.
My problem is the following. The page renders everything well, but the pagination doesn't work properly. So IF I have the structure below and doesn't delete _notification.html.erb then the page will be loaded with the new action partials and the pagination objects will be loaded with _notification.html.erb. IF I delete _notification.html.erb then the page still loads with the new partials, but pagination doesnt't work. How should I change the pagination to make this work?
notifications_controller.rb
def other_notifications
  @other_notifications = current_user.notifications.not_chat.order(created_at: :desc).includes(:sender_profile).
                         paginate(page: params[:page], per_page: Notification.pagination_per_page)
  current_user.reset_new_other_notifications
  respond_to do |format|
    format.html
    format.js
  end
end

other_notifications.html.erb

  <% @other_notifications.each do |notification| %>
    <% if lookup_context.template_exists?(notification.action, "notifications/actions", true) %>
      <%= render partial: "notifications/actions/#{notification.action}", locals: { notification: notification } %>
    <% end %>
  <% end %>

  <%= will_paginate @other_notifications %>

other_notifications.js.erb
$('.other-notifications-index').append('<%= j render @other_notifications %>');
<% if @other_notifications.next_page %>
  $('.pagination').replaceWith('<%= j will_paginate @other_notifications %>');
<% else %>
  $(window).off('scroll');
  $('.pagination').remove();
  $('.no-more').delay(1000).fadeIn(1500);
<% end %>

A: I solved it like this. So will paginate will look for _notification partial, which will always be found with the following code, and the _notification partial will call the rest of the partials.
other_notifications.html.erb
<%= render @other_notifications %>
<%= will_paginate @other_notifications %>

_notification.html.erb
<% if lookup_context.template_exists?(notification.action, "notifications/actions", true) %>
  <%= render partial: "notifications/actions/#{notification.action}", locals: { notification: notification } %>
<% end %>


text:
Q: How to pass a value retrieved from HttpContext to BackgroundJob.Enqueue I have this code in my controller:
var user = HttpContext == null ? null
                               : HttpContext.Items["ApplicationUser"] as ApplicationUser;
int organisationid = user == null ? 0
                                  : user.OrganisationID;
BackgroundJob.Enqueue(() => Merge(organisationid));

So the background job calls the Merge method in my controller:
public void Merge(int organisationid)
{
    _Uow.MergeSHQSCostsTable(organisationid);
}

But I would like the call in the merge method to use the organisationid retrieved from the request and available at the time the call to Enqueue is made. How do I do that? Currently my code always passes the value zero because the HttpContext is null when the background job is run.

A: The trick is to encapsulate the call to BackgroundJob.Enqueue in a separate method so that Hangfire can serialise the parameter:
public SHQSController(IUnitOfWork uow) : base(uow)
{
   //CurrentOrganisationID is retrieved from HttpContext
   EnqueueMerge(CurrentOrganisationID);
}

private void EnqueueMerge(int organisationid)
{
    BackgroundJob.Enqueue(() => Merge(organisationid));
}


text:
Q: PS/2 to USB adapter doesn't work with Model M keyboard I bought a server about 3 months ago from a friend, and I have only had time to tinker with it in the last week. I noticed that this server doesn't have any PS/2 ports, which meant configuring it was near impossible. I don't have any USB keyboards in the house, I only have an IBM Model M keyboard (built 1994) and another IBM keyboard that was built circa 2001. Both of them have PS/2 connections.
I bought an adapter off eBay, and when I used it with the Model M keyboard the three lights on the keyboard flashed for a split second, but then the keyboard is then unresponsive. I can bash away at the keys for ages and nothing will happen. The same applies to the later built IBM keyboard.
What could I do to make the adapter work? I am getting the loan of a USB keyboard in two weeks time, but I'd like a more permanent solution without having to rely on getting the loan of a keyboard every time I have to perform maintenance on the server. And as I already have two keyboards which work fine and I like using, I don't really want to have to buy another keyboard just for use on the server.

A: The PS/2 and USB connectors are not equivalent. Many devices can be used in both using a passive adapter (but then almost always USB->PS/2, not the other way around), but not all [1].
There are "active adapters" available that connect to USB and simply gives you two PS/2 connectors. If this is what you have, then something is weird, but you probably have a pure rewiring adapter.

A: IBM Model M keyboards require more power than that is provided by most USB<->PS/2 adapters. If you search the Net, you'll find one with ease.


text:
Q: Prolog transpose of a Matrix using decompose First of all, I know there are other codes to make the transpose of a matrix in other questions, but my problem is specific one:
In a homework I was asked to build a decompose/3 code which separates the first element of each list from the rest of the elements.
After this I was asked to create a code to transpose/3 a matrix. (If the input is not a matrix, it can fail, the purpose is not to check whether it is a matrix or not).
I have the following codes decompose/3, transpose/3, and transpose1/3 so far: (transpose and transpose1 are the same but with a different base case)
%4. transpose(M, R)
%Input transpose([[1,2],[3,4],[5,6]], R).

decompose([], [], []).
decompose([[H|T]|T0], [H|L1], [T|L2]) :-
    decompose(T0, L1, L2).

transpose(M,[L1|Z]):-                       #This code works for 3 rows
    decompose(M,L1,L2),
    transpose(L2,Z).

transpose1([[X],[Y],[Z],[B]],[[X,Y,Z,B]]).  #This code works for up to 4 rows
transpose1([H|T],[L1|R]):-
    decompose([H|T],L1,L2),
    transpose1(L2,R).

So the input matrix is a [3 x 2] in this example, and it works fine, for both, but if my matrix has more than 4 rows, transpose does not work anymore, and because of the base case transpose1([[X],[Y],[Z],[B]],[[X,Y,Z,B]]). it can manipulate up to 4 rows, but if the matrix is bigger, then the outcome is false.
Any idea how to manipulate my code? How to make the base case apply for any number of rows on my matrix? Why is this not working?
Thank you!


text:
Q: Can I download apps inside android emulator from Google play I am trying to download an app from virtual emulator using google play. Google play list all my real devices that I have used my email on and asks to download this app to one of them. I want to install it in the mobile emulator instead, is this even possible ?
Google play emulator download

A: Yes this is possible,

*

*Open the AVD manager in android studio

*create a virtual device

*choose a device definition with the play store icon
Using this AVD you'll be able to login and access the play store. You can then install apps on this device via the browser too

A: If your emulator having the "PlayStore" then you can sign with your Gmail account, and can download the app likewise the real device,


text:
Q: How can I rewrite Git tags in an "interactive-rebase-like" manner? I'm converting an old, multi-project Subversion repo into a series of single-project Git repos and trying to retain as much of the original data as possible.  I've got most of the conversion sorted, but am having trouble with the tags.
Due to the way the tags were checked into the Subversion repo, each tag is currently attached to an empty commit which is a child of the commit to which the tag should be attached.  In other words, I have a repo with the following commit structure:
A -> B -> C -> D
 \         \-> (empty) -> 1.1
  \-> (empty) -> 1.0

Ideally, what I'd like to do is something like an interactive rebase, but instead of reordering commits, I want to move those tags up onto the correct commits.
Is anything like this possible?  The new repos haven't been pushed anywhere yet, so I have total freedom to rewrite history.

A: You can do this with a filter-branch command.
Filter each tag, and find the relevant child commit. Then put the tag there.
You can also remove the empty commit as part of the filter if you so choose.

A: A tag (whether annotated or lightweight) simply points to a commit.1  Hence, as ryanve noted, you can simply force the tag to point to a different commit (since it's still a new private repo there's no one else to mess up; you don't have to worry about remote repos' copies of the tags).
While git filter-branch can do the whole thing, it tends to be quite a heavy-weight operation.  You might want, instead, to snip out the part of filter-branch that copies annotated tags, and use that to make your own replacements.
To do this, start by opening up the filter branch script in an editor, e.g.:
$ vim $(git --exec-path)/git-filter-branch

Search for git mktag and you'll find this chunk of code:
            if [ "$type" = "tag" ]; then
                    new_sha1=$( ( printf 'object %s\ntype commit\ntag %s\n' \
                                            "$new_sha1" "$new_ref"
                            git cat-file tag "$ref" |
                            sed -n \
                                -e '1,/^$/{
                                      /^object /d
                                      /^type /d
                                      /^tag /d
                                    }' \
                                -e '/^-----BEGIN PGP SIGNATURE-----/q' \
                                -e 'p' ) |
                            git mktag) ||
                            die "Could not create new tag object for $ref"
                    if git cat-file tag "$ref" | \
                       sane_grep '^-----BEGIN PGP SIGNATURE-----' >/dev/null 2>&1
                    then
                            warn "gpg signature stripped from tag object $sha1t"
                    fi
            fi

            git update-ref "refs/tags/$new_ref" "$new_sha1" ||
                    die "Could not write tag $new_ref"

Note that $type is $tag only when the tag is an actual annotated tag object.  Note also the gpg signature stripping—probably not a problem in your case, and if you wanted to sign your new tags you could do that.
The one key input for this code fragment is the existing annotated tag name ($ref).
The two key things you'd need to compute before using this block of code are:

*

*The SHA-1 of the commit you want tagged ($new_sha1): that's the parent commit of the commit to which the existing tag points, so it's simply the output of git rev-parse ${ref}^{commit}^: find the commit to which the tag (indirectly) points, and traverse the commit graph to that commit's first (and only) parent.

*The new name of the tag.  if you want to systematically modify the tag names, set new_ref appropriately.  If not, just use $ref (note that git update-ref will then update the existing reference in-place, rather than creating a new ref, so the error message for failure becomes a bit wrong).

Once you've done that, all you need to do is apply this block of code2 to each annotated tag.  Since you'll have already verified that they are all annotated tags, you won't need the if [ "$type" = "tag" ] test at all: just write the appropriate subset of code to a new shell script, wrap it up as a function, and call the function on all your known annotated tags (which you can get by using git for-each-ref refs/tags).
Once you've moved all the tags to point away from the empty side commits, the side commits will become invisible due to nothing pointing to them, and will eventually be garbage collected.

1A lightweight tag points directly to a commit—this is what makes it lightweight—while an annotated tag starts with the same thing as a lightweight tag, i.e., a reference in the refs/tags/ name space, but that reference points to a repository object of type "tag", which contains the text described in the git mktag documentation.  The object to which it points is normally a commit, so that the type string is also commit, and the tag name in the annotated tag object is the same as the lightweight tag's name (minus the refs/tags/ part).
It's possible for a tag (lightweight or annotated) to point to something other than a commit, e.g., you can point one tag to another tag.  Of course if you point a lightweight tag to an annotated tag object, you have an annotated tag, although if the annotated tag's internal name doesn't match the lightweight tag's name, you can at least detect this odd situation ... not that there is anything to do about it, other than point out that it's odd.
2Most of the block is regular shell built-ins or commands.  The one unusual part is sane_grep, which is really just running grep but working around brokenness in some specific cases.  You can find that in the git-sh-setup script in the same exec-path directory, or just use this, which I copied out of git-sh-setup:
sane_grep () {
        GREP_OPTIONS= LC_ALL=C grep "$@"
}

The warn and die function-ettes are in git-filter-branch (there's a die in the setup script as well), and do the obvious thing.

A: To rename tags you can delete the old tags and then tag the correct commits with the new names.


text:
Q: To compute the cell array of voronoi I'm converting a Matlab code to python.I came across a function 'voronoin' in Matlab which gives vertices and cell array as an output. From my program I am only getting vertices. The cell array I am getting from my program is not matching with the one I got in Matlab.
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi

def voronoi_volumes(points):
    v = Voronoi(points)
    print(v.vertices)
    for i, reg_num in enumerate(v.point_region):
        print(reg_num)
        indices = v.regions[reg_num]
        print(indices)

points = np.array([[ 0.4074,  0.4567],
                   [ 0.4529,  0.3162],
                   [ 0.0635,  0.0488],
                   [ 5, -45],
                   [ 5,  55],
                   [-45,  5],
                   [ 55,  5]])
k = voronoi_volumes(points)

In Matlab the output I have is:
[9,5,3,4,7]
[9,7,6,8]
[7,4,2,6]
[8,1,2,6]
[5,1,3]
[4,2,1,3]
[9,5,1,8]

In python the output I am getting is:
[7, 3, 1, 2, 5]
[7, 5, 4, 6]
[5, 2, 0, 4]
[6, -1, 0, 4]
[-1, 1, 3]
[-1, 0, 2, 1]
[7, 3, -1, 6]

A: The answer iam getting in python is correct.Matlab and python have different indices. when i try to access vertices from the indices,iam getting same answers from both.


text:
Q: Eventmachine HTTP - How to get notified if connection is lost? I have this EM http code:
require 'eventmachine'
require 'em-http'
require 'json'

http = EM::HttpRequest.new("api_url", :keepalive => true, :connect_timeout => 0, :inactivity_timeout => 0)

EventMachine.run do

  s = http.get({'accept' => 'application/json'})
  s.stream do |data|
    puts data
  end

  s.errback do
    puts "FATAL EM STOPPED: #{response.error}"
    EM.stop
  end

end

I want to get notified if the connection is lost. I just tried to disable my WIFI and nothing is triggered. After I enable my WIFI the connection is established again and the messages are printed again. I want this behavior I just want to catch that the connection is lost, so that I can raise a error message.


text:
Q: TIMESTAMP on HIVE table I'm trying to load data from Oracle to Hive as parquet. Every time i load a table with date/timestamp column to hive, it automatically converts these columns to BIGINT. Is is possible to load timestamp/date formats to hive using sqoop and as a parquet file?
Already tried creating the table first in hive then using impala to LOAD DATA INPATH the parquet file.
Still failed with errors

"file XX has an incompatible Parquet schema for column XX column:
  TIMESTAMP"

BTW, I'm using cloudera quickstart vm. Thanks

A: From the Cloudera documentation:
If you use Sqoop to convert RDBMS data to Parquet, be careful with interpreting any resulting values from DATE, DATETIME, or TIMESTAMP columns. The underlying values are represented as the Parquet INT64 type, which is represented as BIGINT in the Impala table. The Parquet values represent the time in milliseconds, while Impala interprets BIGINT as the time in seconds. Therefore, if you have a BIGINT column in a Parquet table that was imported this way from Sqoop, divide the values by 1000 when interpreting as the TIMESTAMP type.
Or you can also use your Hive query like this to get the result in your desired TIMESTAMP format.
FROM_UNIXTIME(CAST(SUBSTR(timestamp_column, 1,10) AS INT)) AS timestamp_column;

A: Try using configuration of sqoop
--map-column-hive
<cols_name>=TIMESTAMP


text:
Q: Input.GetAxis for android I'm creating a maze game and curently i am having delays with my android  controls. I have lade the computer controls to move front and to turn left and right and to jump using input.getaxis. Now on android i created buttons that work but not how i want. It can jump and turn how i want but it doesnt move properly. There are 2 problems one is that when i click it moves a bit and then i need to click again but i want to hold and it will move continuously and second problem is that when i turn the character doesnt move the corect way it goes always on x axis with input.getaxis everything works perfectly but i need something that will work for androdid like that, here is my code:
using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {
    public float speed;
    public float speedj;
    Rigidbody rb;
    static Animator anim;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        anim = GetComponent<Animator>();
    }
    public void Walk ()
    {
        anim.SetTrigger ("Walk");
        rb.velocity = new Vector3 (0,0,7f);
    }
    public void Left ()
    {
        transform.Rotate(0,-90f,0);
    }
    public void Right ()
    {
        transform.Rotate(0,90f,0);
    }
    public void Jump ()
    {
        anim.SetTrigger ("Jump");
        rb.velocity = new Vector3 (0,4f,0);

    }
    public void StopVelocity ()
    {
        rb.velocity = Vector3.zero;
        transform.Translate(0,0,0);
    }
    void FixedUpdate ()
    {
        float x = Input.GetAxis ("Horizontal") * Time.deltaTime * speed;
        float z = Input.GetAxis ("Vertical") * Time.deltaTime * speed;
        transform.Translate (0,0,z);
        transform.Rotate (0,x,0);
        if(Input.GetKey(KeyCode.Space))
        {
            anim.SetTrigger ("Jump");
            rb.velocity = new Vector3 (0,speedj,0);
        }
    }
}

So this is it the fixedUpdate functionis for the computer the others are for buttons for android i am using event trigger for pointer up and down events pleasehelp me to change the code so that it will work for android like it works with Input.getAxis for computer thanks!

A:
"when i click it moves a bit and then i need to click again but i want to hold and it will move continuously."

Using the EventTrigger here should be the optimal way. Check out OnPointerDown(); the function should be called for every frame. You should attach the EventTrigger to the button for it to work on mobiles.

"when i turn the character doesnt move the corect way."

Try moving using your Local Transforms Forward. Namely Transform.Forward(). It will allow you to move forward into the direction you set before, the Forward is always a Normalized Vector3. Moving in the way you are will use the world axis, your rotation wont matter at all.


text:
Q: Possible to attach a Blu-Ray writer to VirtualBox on Linux Mint 18 host? What I don't have:

*

*Windows on a machine

What I do have:

*

*Laptop with USB 3.0

*Linux Mint 18.1 64-bit OS (on this laptop)

*VirtualBox version 5.1.22 + Extension Pack (on this OS)

*Windows 8.1 guest machine (in this VirtualBox)

What I need:
I would like to know if to this setup, it will be possible to plug through a Blu-Ray writer and copy some of my original Blu-Ray disks?

Rationale:
On Linux it is highly complicated and often impossible to read original Blu-ray movie disks.

A: What you are trying to do is entirely possible with both the Linux Mint OS and the Virtual windows machine.
really all you need to do is make an ISO of your Blu-ray disk and save them anywhere you please.
You could also copy the actual media files depending on their format. And one last possibility is to use a screen capture program to record the videos. This however is not the best option as it could result in a choppy recording depending on your computers hardware and the software configurations. Still worth mentioning.
Edit:
There are some post out there about using blu-ray on Linux.
Take a look at this post. Can linux play blu-rays?


text:
Q: getting Exception in thread "main" java.lang.UnsupportedClassVersionError: com/ram/hadoop/driver/DriverCode : Unsupported major.minor version 51.0 This question is asked several times by people. I gone through all the Q&A but still I didn't resolve my issue with those answers.
I compiled the code using Eclipse with Java 1.6.0.15 in the Windows 10. I took the code in the format of jar file and ran with Java 1.6.0.25 in Ubantu 10 OS.
By that I got the follwing error :

Exception in thread "main" java.lang.UnsupportedClassVersionError:
  com/ram/hadoop/driver/DriverCode : Unsupported major.minor version
  51.0

I verified in hadoop-config.sh it is pointing to Java 1.6.
Why this error is coming while running the code.
I verified in hadoop classpath as well.
Thanks.


text:
Q: Implementing Movable 's in jquery I am trying to build a dynamic drag&drop module for my App.
It includes a table that holds all the droppable divs and few shapes.
As i can't know from advance the type of shape someone will put in a div and i have to save the div or divs which the user chose to drop the shape in i need to allow the app to be very dynamic...
I managed to do it for all the celld except from the top row for the big square and the long line and the right column for the big square and for a wide line....
The code:

    <title>Untitled Page</title>

    <form id="form1" runat="server">

	 ***not getting responce for draggable_big***

	 ***not getting responce for draggable_big***

	 ***not getting responce for draggable_big***

	 ***not getting responce for draggable_big***

	 ***not getting responce for draggable_big***

	 ***not getting responce for draggable_big***

	 ***not getting responce for draggable_big***

    </form>

Any one have any idea what is the problem?
Thanks

A: solved the problem by adding:
$( ".draggable_big" ).draggable( "option", "cursor", 'move' );
$( ".draggable_big" ).draggable( "option", "cursorAt", {right:15,top:15} );

to every draggable object..
10x


text:
Q: does leaving php code without any function/classes has disadvantages? Initially I had the habbit of directly writing the php code in the
<?php

?>

region. Those were for simpler sites and lesser traffic.
Now I am in process of developing a bigger site involving a lot of social networking. So would it be apt to leave the code just like that or should I encapsulate it.
Are there any disadvantages or chances of the site crashing if the code is not in any function/class?

A: Create classes and functions for the sake of creating classes and functions? No.
Create functions to support code reuse? Yes. Create objects to adopt one of several possible code patterns? Yes.
I suggest a good deal of reading to gain an understanding of the fundamental difference between procedural and OOP programming.
Start with this question, which isn't technically a duplicate, but pretty close: simple explanation PHP OOP vs Procedural?
Read the answers, especially the detailed one and the one with all the links -- visit the links.
Check out tutorials like this one or this one. You must understand not only the difference between the programming styles, but also when and why to use them. Simply dashing functions and classes into your code so you can "do OOP" is not actually using OOP at all, it's just making your code into spaghetti.

A: The disadvantages a huge regarding:

*

*code readability: now as well as for the future, for you as well as for any future developers that might work on the project;

*maintenance: changing the same code in 10 different files might mean you forgot to change it in the 11th file;

*verbosity: writing the same stuff tens of times just because the code isn't centralised / organised into reusable pieces (one can argue that reusable pieces can be achieved by structuring the files and including them);


text:
Q: json and jquery using this I have an issue here:
I am trying to convert a jquery string that is obtained by $this.text into a json argument then output the results in an alert:
this is the json: var test = { "hi" : { "Name":"moe", "Genre":"ez"} };
$this.text() will have the text of "hi"
alert(test.$this.text().Name)
keep in mind replacing this.text with "hi" works great
I've tried so many this if anyone cant help in any way it would be appreciated very much

A: To return value from json using key name inside variable/function you should use square brackets. Like this :
var test = { "hi" : { "Name":"moe", "Genre":"ez"} };

// $this.text() - returns hi
alert(test[$this.text()].Name)

A: Using like this:
test[$this.text()].Name

A:
$this.text() will have the text of "hi"

Above statement states that :

var test = { "hi" : { "Name":"moe", "Genre":"ez"} };

function text() {
  return "hi";
}

console.log(test[text()]);

Hence, if you want to access Name property of hi object then try this :

var test = { "hi" : { "Name":"moe", "Genre":"ez"} };

function text() {
  return "hi";
}

console.log(test[text()].Name);

A: fixed the json had to be placed in brackets and $this needed to be $(this)


text:
Q: POSTGRESQL - calling function with different times as input parameter I was trying to call the function I created to fetch some data for particular time slot. Given below is a  script of my function:
CREATE OR REPLACE FUNCTION my_function(
    starttime timestamp with time zone,
    endtime timestamp with time zone)
RETURNS TABLE("Deviceid" integer, "AlertTime" timestamp with time zone)
    LANGUAGE 'plpgsql'
    COST 100.0

AS $function$

 DECLARE

r record;

BEGIN

SELECT "DeviceID" ,  "AlertTime" FROM my_table
WHERE "AlertTime" BETWEEN starttime AND endtime;

END;

$function$;

ALTER FUNCTION public.my_function(timestamp with time zone, timestamp with time zone)
    OWNER TO postgres;

When I am calling function with time '2016-12-15 00:00:01' to '2016-12-15 18:00:00' I am not getting any record. Even many records available for the time slot, I checked it by passing same time values for the query inside the function, its fetching data properly.
select * from my_function('2016-12-14 00:00:01','2016-12-15 18:00:00')

But when I am calling function with 2016-12-15 00:00:00' to '2016-12-15 18:00:00' I am able to get all records.
select *  from my_function('2016-12-14 00:00:00','2016-12-15 18:00:00')

Even I tried to change the input parameters to "character varying" and convert the input internally to time stamp even then it is not working.

A: The explanation is obvious, isn't it?
All the matching rows from mytable have "AlertTime" greater or equal than 2016-12-14 00:00:00 and less than 2016-12-14 00:00:01.


text:
Q: What's blocking Windows Update from using all resources available? When watching Windows Update doing its work with Task Manager's performance tab and Resource Monitor open, the update process usually - i.e. ~99% of the time - doesn't max out any of the available resources. By far.
Some general figures observed:

*

*Windows 10 Fall Creators Update 1709 took about 1.5 hours in total - a clean install is less than 5 minutes, but that's another question

*cpu cores almost idle most of the time with a single core maxing out once in a while (even when it does, it usually won't run at maximum clock rate)

*ram usage is at about 5% all the time, didn't expect that to max out

*disk activity averages at about 10% with 100% almost never reached, used disk bandwidth far away from specs at about 10 MB/s

*network connection maxes out if used (small amount of time)

As I understand it, there should always be a bottleneck limiting other resources; one of those resources should always be at 100% blocking further progress. But in case of Windows Update, a standard scenario snapshot looks like this:

*

*busiest cpu core at 30%

*ram at 5%

*disk at 10% activity with combined read/write bandwidth of 10 MB/s

*network at 0%
There simply is no bottleneck in Windows Update (maybe by design for marketing purposes) most of the time. Or at least it's not visible to me.
This leaves me asking what the computer is doing instead. Is this intended to not put too much load onto the system to prevent overheating or to allow for parallel usage/responsiveness at any time? Is it a bug or shortcoming regarding Task Manager or Resource Monitor? Is there any way to force Windows Update to use every resource possible?
Interprocess Locking/Concurrency issues as a reason?
Frank Thomas' "drains and water pipes" analogy made me think of a possible reason: interprocess locking. Since there are usually multiple cores in action, maybe they are waiting for each other. Or they are blocking resources any other thread or process needs. Likely or not? Will observe cores' orchestration next time. Better yet: apply an update inside a single core (virtual) machine and see if the theory holds true.


text:
Q: jQuery getJSON data order varies across browsers JSON data:
  {"2":"Alpha","1":"Beta"}

The data format is fixed, i.e. I can't change it, I can only amend the javascript/jQuery code.
    $.getJSON("www.myurl.com", function(data) {
        var items = [];
        $.each(data, function(key, val) {
            items.push(key + ', ' + val);
        });
        alert(items);
    });

Chrome, IE9, and Opera display:
  1, Beta,2, Alpha
Firefox and Safari display:
  2, Alpha,1, Beta
Question 1: Which is correct?
Question 2: I want the data ordered as in Firefox and Safari. What's the easiest way for me to ensure Chrome, IE9, and Opera produce the same output as Firefox and Safari?

A: $.each operates on javascript arrays (indexes are 0 based integers). The JSON you have shown is not an array. It's an associative array which is what javascript objects are. So:
$.getJSON("www.myurl.com", function(data) {
    var items = [];
    for (var prop in data) {
        if (data.hasOwnProperty(prop)) {
            items.push(prop + ', ' + data[prop]);
        }
    }
    alert(items);
});

Or if you want to use $.each then use arrays, like this:
["Alpha", "Beta"]

and then:
$.getJSON("www.myurl.com", function(data) {
    var items = [];
    $.each(data, function(index, element))
        items.push(index + ', ' + element);
    }
    alert(items);
});

A: no idea... but you can sort the array after the fact.
given the following output (simulated for testing)
var items = ["1, Beta", "2, Alpha"]

you can
items.sort(function(a,b){ return b.split(",")[0] - a.split(",")[0] })

A: i would rearrange your response to something more like this:
[
  {
    "key":"2",
    "value":"Alpha"
  },
  {
    "key":"1",
    "value":"Beta"
  }
]

using an array will ensure that the order is preserved.


text:
Q: Place to put a Jquery UI dialog, in a spring mvc project (with JSP) I have a Spring mvc project in eclipse. In most cases, for the web pages, i have a composition of various jsp, from a main layout jsp to others jsp files.
I try to put a dialog of jquery UI, but i have various problems.
First, i don't know where is the best place to put the div of the dialog UI. I expect that, the dialog is displayed in upper part of the page, centered, but with so many jsp and div, i get confused.
Second, when show  the dialog, this no have correct style or take style of others div. I know that with Theme roller, is possible to customize the styles, but i don't know where is the best place to put the css file, and how and where include it.
¿How is possible to get darker the page, when is shown the jquery ui dialog? And How to block the other elements on the page? (I try with modal:true, but not works, and i some page the dialog is shown behind others elements)
Sorry for the long question, but i really get confused.

A: *

*You can just make the div a direct child of the body element.

*Once you use the Themeroller to configure your styles, you will be able to download a bundle of files including the CSS file that the Themeroller generated based on your choices. You should put that CSS file in the head of your jsp page, something like:
<link href="/yoursite/css/custom-theme/jquery-ui-1.9.2.custom.css" type="text/css" rel="stylesheet"/>

*The modal option is the correct way to achive that as described here: http://api.jqueryui.com/dialog/#option-modal


text:
Q: $\operatorname{char}R=0 \implies\mathbb{Q} \hookrightarrow R$ Let $R$ be any field, then:
$$\operatorname{char}R=0 \implies \mathbb{Q}  \hookrightarrow R$$
Proof:
We know that $\mathbb{Q} = Q(\mathbb{Z})=\{[(x,y)]\subseteq\mathbb{Z}\times \mathbb{Z^*}:(x,y) \in \mathbb{Z}\times \mathbb{Z^*}\}$
We consider $φ:Q(\mathbb{Z})\longrightarrow R, \ [(r,s)]\longmapsto rs^{-1}$ and it's easy to prove that $φ$ is homomorphism, well ordered, and $\operatorname{ker}φ=\{[(x,y)]: φ[(x,y)]=0_R\}=\{0_{Q(\mathbb{Z})}\}$. So $φ$ is monomorphism.
Is it right? And if it is, why must $\operatorname{char}R=0$ necessary?

A: Suppose char$\,R=p>0\;,\;\;(p\;$ a prime), then
$$\phi(p)=p\cdot\phi(1)=0\implies \phi\;\;\text{isn't injective}$$
even assuming you don't divide by zero because of some miracle.

A: The map $\chi\colon\mathbb{Z}\to R$ that maps $n$ to $n1$ (the multiple of the identity element $1\in R$ by the integer $n$) is a ring homomorphism. It is injective if and only if $\operatorname{char}R=0$. In this case this map $\chi$ can be extended to $\varphi\colon \mathbb{Q}\to R$ by
$$
\varphi\left(\frac{m}{n}\right)=\chi(m)\chi(n)^{-1}
$$
(here we use injectivity, so $n\ne0$ ensures $\chi(n)\ne0$). The map $\varphi$ is a ring homomorphism and it is injective, since it maps $1\in\mathbb{Q}$ to $1\in R$ and $\mathbb{Q}$ is a field, so its only ideals are $\{0\}$ and $\mathbb{Q}$.
If $R$ has characteristic $p>0$, then there is no ring homomorphism $f\colon \mathbb{Q}\to R$ such that $f(1)=1$. The reason is very simple:
$$
f(p)=pf(1)=0
$$
so $p\in\ker f$, but since $\ker f\ne\mathbb{Q}$, it follows $\ker f=\{0\}$: contradiction.


text:
Q: How to add custom error message notification in login page I have started integrating the react-admin page, In the login page, I'm trying to manage the error message in the auth provider. I'm not able to get the error message to display in the notification .any one please help.
login: ({ username, password }) => {
        const request = { 'email': username, 'password': password}
        return axios.post(process.env.REACT_APP_URL+`/login`, request).then(response => {
            let result = response.data;

            if(result.success){

            } else {
                console.log(response.data);
                throw new HttpError(result.message);

            }
           // localStorage.setItem('username', username);
            return Promise.resolve();
        }).catch(error => {
            return error;
        });```

A: You can use the useNotify function from react-admin to render custom notifications.
//Import the notification
`import {useNotify} from 'react-admin';`
...
...
//Place this line in your component.
`const notify = useNotify();`
...
...
//Place this wherever you want to show notification
`notify('Message of Notification');`
//For error notifications
`notify('Error Notification','error);`

More on https://marmelab.com/react-admin/Actions.html
Edit: on reading the comment realised that this requires custom error messages.
https://marmelab.com/react-admin/doc/2.8/Translation.html
You would need to replace the messages from 'ra-language-english' with your own.
import React from 'react';
import { Admin, Resource } from 'react-admin';
import englishMessages from 'ra-language-english';

const englishCustomMessages = englishMessages;
englishCustomMessages.ra.auth.sign_in_error = 'Your Custom Message goes here';

const messages = {
    en: englishCustomMessages,
}
const i18nProvider = locale => messages[locale];

const App = () => (
    <Admin locale="en" i18nProvider={i18nProvider}>
        ...
    </Admin>
);

export default App;

If you want to customize more notifications look at this file:
https://raw.githubusercontent.com/marmelab/react-admin/89ac783fd9f961401d1c2e8d4ca4965053ed1d21/packages/ra-language-english/index.js
Don't import directly as you may not stay updated with the changes in react-admin. Always override only the required changes.


text:
Q: Modelling data from a single timestamp to a record with valid_from/valid_to timestamps when there is a change Here is table1 with some example data:

id
date_column
col1
col2

1
06/03/2021
NULL
1

1
07/03/2021
NULL
1

1
08/03/2021
1
1

1
09/03/2021
1
2

2
05/03/2021
1
1

2
09/03/2021
1
1

I want to transform it into the following format:

id
valid_from
valid_to
col1
col2

1
06/03/2021
08/03/2021
NULL
1

1
08/03/2021
09/03/2021
1
1

1
09/03/2021
01/01/2100
1
2

2
05/03/2021
01/01/2100
1
1

So a new row in the desired format is created every time there is a new value in col1 or col2.
The valid_from is the the earliest value in date_column for this unique values in col1 and col2, while the the valid_to is the earliest value in date_column when any of these values have changed.
I was able to to achieve this transformation with the following SQL (Presto specific):
WITH base AS (
SELECT
*
FROM (
  VALUES
    (1, date('2021-03-06'), NULL, 1),
    (1, date('2021-03-07'), NULL, 1),
    (1, date('2021-03-08'), 1, 1),
    (1, date('2021-03-09'), 1, 2),
    (2, date('2021-03-05'), 1, 1),
    (2, date('2021-03-09'), 1, 1)
) AS t (id, date_column, col1, col2)
)

, base2 AS (
SELECT
  id
, date_column
, col1
, col2
, array_join(array[cast(col1 AS VARCHAR),
                   cast(col2 AS VARCHAR)], '','null') AS col_dedup
FROM
  base
)

, base3 AS (
SELECT
  id
, date_column
, col1
, col2

, coalesce(
    lag(col_dedup) OVER (PARTITION BY id  ORDER BY date_column) = col_dedup,
    false
) AS same_as_previous

from base2
)

SELECT
  id
, date_column                                                                          AS valid_from
, lead(date_column, 1, date('2100-01-01')) OVER (PARTITION BY id ORDER BY date_column) AS valid_to
, col1
, col2
FROM
  base3
WHERE
  same_as_previous = false
ORDER BY
  id
, date_column ASC

The difficulty is when you have 100 columns, all of these 100 columns must appear in the array_join.
Now the actual question - is there a better way of doing the above transformation?

A: This is a type of gaps-and-islands problem . . . but actually a simple version.  You want the first row of each grouping.  Then lead() to get the end date:
select id, col1, col2, datecol as valid_from,
       lead(datecol, 1, '2100-01-01') over (partition by id order by datecol) as valid_to
from (select t1.*,
             lag(datecol) over (partition by id order by datecol) as prev_datecol,
             lag(datecol) over (partition by id, col1, col2 order by datecol1) as prev_datecol_12
      from table1 t1
     ) t1
where prev_datecol_12 is null or
      (prev_datecol <> prev_datecol_12);

Note that this method does not require aggregation, which is typically faster.
More importantly, this handles groups where the values return to a previous set of values.  Your method does not do that.  I am guessing that this is what you really want for this type of problem.


text:
Q: How to cange a the cursor type by clicking on a button in JavaFX? Maybe this questionis silly but i didn't get any idea about how to change the Cursor type in JavaFX Application but when i run the application and clicking on the button it does anything it should be set the Cursor_WAIT and then loading a page in the WebViewand then return the Cursor_DEFAULT so this is the code i've traied:
  @FXML
private void tabfirst (ActionEvent ee) throws IOException { // for tha Chooser frame text.

            String hh = text11.getText();
            Socket socket = new Socket();

    try {

        //do work
        URL url = new URL (hh);
        url.getContent();
        WebEngine myWebEngine = web1.getEngine();
        myWebEngine.load(url.toExternalForm());
        //close the window chooser
        Stage stage = new Stage();
          Parent root = FXMLLoader.load(getClass().getResource("Choose.fxml"));
          Scene scene = new Scene(root);
         stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
              @Override public void handle(WindowEvent t) { } });
        //close cursor
        ancpa.setCursor(Cursor.DEFAULT);
        web1.setCursor(Cursor.DEFAULT);
        web2.setCursor(Cursor.DEFAULT);
        web3.setCursor(Cursor.DEFAULT);
        web4.setCursor(Cursor.DEFAULT);
        web5.setCursor(Cursor.DEFAULT);
        web6.setCursor(Cursor.DEFAULT);
        web7.setCursor(Cursor.DEFAULT);
        web8.setCursor(Cursor.DEFAULT);
        web9.setCursor(Cursor.DEFAULT);
    }
   catch (IOException e){
       final  Stage stg = new Stage();
        stg.initModality(Modality.APPLICATION_MODAL);
        stg.initOwner(stg);
        stg.setTitle("Cannot connect to the internet /n Please Verify your connection internet");
        labelno.setText("Cannot connect to the internet...");
        //close chooser
        Stage stage = new Stage();
         Parent root = FXMLLoader.load(getClass().getResource("Choose.fxml"));
         stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
              @Override public void handle(WindowEvent t) { } });

       //set cursor
         ancpa.setCursor(Cursor.DEFAULT);
        web1.setCursor(Cursor.DEFAULT);
        web2.setCursor(Cursor.DEFAULT);
        web3.setCursor(Cursor.DEFAULT);
        web4.setCursor(Cursor.DEFAULT);
        web5.setCursor(Cursor.DEFAULT);
        web6.setCursor(Cursor.DEFAULT);
        web7.setCursor(Cursor.DEFAULT);
        web8.setCursor(Cursor.DEFAULT);
        web9.setCursor(Cursor.DEFAULT);
   } finally{
       try{ socket.close(); } catch (Exception e){ }
       }

}

So Please can anybody help me Thanks in advance :)

A: Your code is incomplete. Here's how you could do it:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class WaitCursorDemo extends Application {

    Stage primaryStage;

    @Override
    public void start(Stage primaryStage) {

        this.primaryStage = primaryStage;

        HBox root = new HBox();

        Button button = new Button( "Wait 10 Seconds on Scene");
        button.setOnAction(e -> waitAction());
        root.getChildren().add( button);

        Button button2 = new Button( "Wait 10 Seconds On Button 2");
        button2.setOnAction(e -> waitAction( button2));
        root.getChildren().add( button2);

        Button button3 = new Button( "Wait 10 Seconds On Button 3");
        button3.setOnAction(e -> waitAction( button3));
        root.getChildren().add( button3);

        Scene scene = new Scene( root, 1600, 900);

        primaryStage.setScene( scene);
        primaryStage.show();

    }

    private void waitAction() {

        primaryStage.getScene().setCursor(Cursor.WAIT);

        Thread thread = new Thread( new Runnable() {

            @Override
            public void run() {

                try {

                    sleep(3000);

                } catch( Throwable th) {

                    th.printStackTrace();

                } finally {

                    Platform.runLater( () -> { primaryStage.getScene().setCursor(Cursor.DEFAULT); });

                }

            }
        });
        thread.start();

    }

    private void waitAction( Button button) {

        button.setCursor(Cursor.WAIT);

        Thread thread = new Thread( new Runnable() {

            @Override
            public void run() {

                try {

                    sleep(3000);

                } catch( Throwable th) {

                    th.printStackTrace();

                } finally {

                    // null means that the cursor from the scene will be used, see documentation of setCursor
                    Platform.runLater( () -> { button.setCursor( null); });

                }

            }
        });
        thread.start();

    }

    private void sleep( long ms) throws InterruptedException {

       Thread.sleep( ms);

    }

    public static void main(String[] args) {
        launch(args);
    }

}


text:
Q: Any alternate of REGEXP_LIKE as it causing performance issue We have one sql which is performing bad.I have fixed the execution plan but REGEXP_LIKE causing high buffer gets and also contribute in runtime.Any alternate which i can use in my sql.The problematc is
AND REGEXP_LIKE (xx3la.assembly_type, '^I..*')
/* Formatted on 1/6/2023 2:07:28 PM (QP5 v5.318) */
SELECT 1
  FROM apps.oe_order_lines_all  ola
       JOIN APPS.OE_order_headers_all oh
           ON oh.Header_Id = ola.header_id AND oh.org_id = ola.org_id
       JOIN inv.mtl_parameters org
           ON ola.ship_from_org_id = org.ORGANIZATION_ID
       INNER JOIN ont.oe_transaction_types_tl tt
           ON     tt.transaction_type_id = oh.order_type_id
              AND tt.language = 'US'
              AND LPAD (UPPER (tt.name), 4) NOT IN ('TRIA',
                                                    'WARR',
                                                    'REPA',
                                                    'DUMM',
                                                    'DEMO',
                                                    'GOOD',
                                                    'INTE',
                                                    'CRED',
                                                    'EVAL',
                                                    'INVO')      --- ('STAND')
       JOIN apps.mtl_system_items_b msib
           ON     ola.Ordered_item_Id = msib.inventory_item_id
              AND msib.ORGANIZATION_ID = org.ORGANIZATION_ID
       INNER JOIN xxom.xxom_3lp_sym_ora_order_hdr xx3ha
           ON xx3ha.header_id = oh.header_id
       INNER JOIN xxom.xxom_3lp_sym_ora_order_lines xx3la
           ON xx3la.header_id = ola.header_id AND xx3la.line_id = ola.line_id
       LEFT JOIN
       (SELECT msib.Inventory_item_id,
               mcb.segment1 ProductionLine,
               msib.ORGANIZATION_ID,
               msib.item_type,
               msib.Fixed_LEAD_Time
          FROM apps.mtl_system_items_b  msib
               JOIN inv.mtl_parameters org
                   ON msib.ORGANIZATION_ID = org.ORGANIZATION_ID
               JOIN apps.MTL_ITEM_CATEGORIES ic
                   ON     ic.INVENTORY_ITEM_ID = msib.INVENTORY_ITEM_ID
                      AND msib.organization_id = ic.ORGANIZATION_ID
               JOIN apps.mtl_categories_b mcb
                   ON mcb.CATEGORY_ID = ic.CATEGORY_ID
         WHERE mcb.ENABLED_FLAG = 'Y' AND ic.CATEGORY_SET_ID = 1100009407) im
           ON     ola.Ordered_item_Id = im.inventory_item_id
              AND org.organization_id = im.organization_id
       LEFT JOIN (  SELECT Header_Id,
                           Line_Id,
                           WIP_ORDER_NUMBER,
                           MAX (PRODUCT_LINE) PRODUCT_LINE
                      FROM XXRMT.XXURD_SO_UNIT
                  GROUP BY Header_Id, Line_Id, WIP_ORDER_NUMBER) u
           ON u.Header_Id = oh.Header_Id AND u.Line_Id = ola.Line_Id
       LEFT JOIN wip.wip_discrete_jobs wdj
           ON     wdj.source_line_id = ola.line_id
              AND wdj.status_type IN (1,
                                      2,
                                      3,
                                      4,
                                      5,
                                      12)
       LEFT JOIN wip.wip_entities we ON we.wip_entity_id = wdj.wip_entity_id
       LEFT JOIN xxrmt.xxont_som_scheduler adm
           ON adm.subscriber_id = xx3la.order_admin
       LEFT JOIN apps.oe_order_lines_all ol2
           ON     ol2.ato_line_id = ola.line_id
              AND ol2.item_type_code IN ('CONFIG')
       LEFT JOIN
       (SELECT mso.source_organization_code,
               mso.vendor_name,
               mso.vendor_site,
               msa.sourcing_rule_name,
               DECODE (mso.source_type,
                       1, 'TRANSFER',
                       2, 'MAKE',
                       3, 'BUY')
                   SourceType,
               msa.inventory_item_id,
               msa.organization_id
          FROM apps.mrp_sr_assignments_v  msa
               --join inv.mtl_parameters    org  on msa.organization_id = org.organization_id
               INNER JOIN apps.mrp_sourcing_rules msr
                   ON msr.sourcing_rule_id = msa.sourcing_rule_id
               INNER JOIN apps.mrp_sr_receipt_org_v msro
                   ON msr.sourcing_rule_id = msro.sourcing_rule_id
               INNER JOIN apps.mrp_sr_source_org_v mso
                   ON mso.sr_receipt_id = msro.sr_receipt_id AND mso.RANK = 1
         WHERE     msa.assignment_set_id = 561
               AND (msro.disable_date IS NULL OR disable_date >= SYSDATE))
       srd
           ON     srd.inventory_item_id = ol2.inventory_item_id
              AND srd.organization_id = ola.ship_from_org_id
 WHERE     org.organization_code IN ('DRM')
       AND ola.Flow_Status_Code <> 'CANCELLED'
       AND NVL (oh.Cancelled_flag, 'N') = 'N'
       AND oh.Flow_Status_Code <> 'CANCELLED'
       AND ola.booked_flag = 'Y'
       AND oh.booked_date IS NOT NULL
       AND TRUNC (oh.booked_date) >= TO_DATE ('2022-12-01', 'YYYY-MM-DD')
       AND msib.item_type NOT IN ('P',
                                  'B/R',
                                  'OP',
                                  'SVC',
                                  'OP',
                                  'EMR_PURCH')
       AND (   ola.item_type_code IN ('CONFIG', 'MODEL')
            OR (    ola.item_type_code IN ('CLASS')
                AND REGEXP_LIKE (xx3la.assembly_type, '^I..*'))
            OR (    ola.item_type_code IN ('CLASS')
                AND u.PRODUCT_LINE IS NOT NULL
                AND xx3la.model_string IS NOT NULL
                AND msib.segment1 NOT IN ('R-CAP1199', 'R-38-315'))
            OR (    ola.item_type_code = 'STANDARD'
                AND xx3la.assembly_type IS NULL))

Somehow fixed the BG issue but still REGEXP_LIKE an issue

A: Your current regex assertion:
REGEXP_LIKE(xx3la.assembly_type, '^I..*')

can be written using an ordinary LIKE:
xx3la.assembly_type LIKE 'I_%'

Note that the above LIKE version should be able to use an index on assembly_type.  That being said, I doubt that the REGEXP_LIKE call be the only major performance bottleneck existing in a query of this size and complexity.  You should run EXPLAIN on your query to view the execution plan.


text:
Q: D3 v5: how do I animate multiple lines to be "drawn" in a multiline chart? Big thank you in advance, I am new to D3. I am trying to make a multiline chart that is animated, basically that acts as if the line is being "drawn" from left to right. I would like all the lines to be drawn at once.
Here is a link to the codepen project: https://codepen.io/amandaraen/project/editor/ZLLWBe
Basically, this is what I thought I should do based on Scott Murray's D3 book that I'm reading:
    d3.transition().selectAll(".line")
    .delay(function(d, i) { return i * 500; })
    .attr("d", function(d) { return line(d.values); })
    .style("stroke", function(d, i){
        return colorScale(i);
  });

But all this does is add the lines in their entirety one by one, instead, I would like for them to be unrolled. I have looked at lots of posts here and tried a lot of things but this is the closest I've come. Additionally, (and annoyingly) I had labels for this lines on the right hand side, but after I added the transition code the labels disappeared.
Edit, okay, I made a few changes and now, at least the labels have reappeared. So now it is only matter of how to make the lines appear like they are being drawn. Update:
 var country = g.selectAll(".country")
    .data(countries)
    .enter().append("g")
    .attr("class", "country");

// draw the lines
country.append("path")
    .transition()
    .duration(2000)
    .delay(function(d, i) { return i * 500; } )
    .attr("class", "line")
    .attr("d", function(d) { return line(d.values); })
    .style("stroke", function(d, i){
        return colorScale(i);
  });

A: EDIT:
Actually I would ignore my solution and try the stroke-dashed property described in this article
http://duspviz.mit.edu/d3-workshop/transitions-animation/
that I linked to through this question.
Animate line chart in d3

To make the line appear like it is drawn, use the attrTween along with the built in interpolator d3.interpolateNumber to set the x2, y2 values.
<!doctype html>
<html lang='en'>
<head>
<!-- Required meta tags -->
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>
<!-- Bootstrap CSS -->
<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css' integrity='sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh' crossorigin='anonymous'>

<title>Hello, world!</title>
</head>
<body>

<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src='https://code.jquery.com/jquery-3.4.1.min.js' integrity='sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=' crossorigin='anonymous'></script>
<script src='https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js' integrity='sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo' crossorigin='anonymous'></script>
<script src='https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js' integrity='sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6' crossorigin='anonymous'></script>
<!-- d3 v5 -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/d3/5.15.0/d3.js'></script>
<script>

let width = 500
let height = 300
//make up some lines
let lines = [
    {
        "x1": 0,
        "y1": 0,
        "x2": 400,
        "y2": 250
    },
    {
        "x1": 0,
        "y1": 250,
        "x2": 400,
        "y2": 0
    }
]

//add lines
let svg = d3.select( "body" ).style( "padding", "30px" ).append( "svg" ).attr( "height", height).attr( "width", width )

// Here you set the x1, y1, x2, y2 values of line to all be equal to x1, y1,
// Then in your transition, use interpolate the number between x1 and x2 and y1
// and y2 respectively.
svg.selectAll( ".line").data( lines )
    .enter().append( "line" )
        .attr( "class", "line" )
        .attr( "stroke-width", 2 )
        .attr( "stroke", "black" )
        .attr( "x1", d => d.x1 )
        .attr( "y1", d => d.y1 )
        .attr( "x2", d => d.x1 )
        .attr( "y2", d => d.y1 )
        .transition().duration( 750 )
            .attrTween( "x2", d => {
                return d3.interpolateNumber( d.x1, d.x2 )
            })
            .attrTween( "y2", d => {
                return d3.interpolateNumber( d.y1, d.y2 )
            })

</script>
</body>
</html>

Since this is a line it was easy to use the build in interpolator, but if it was a path or something you can define your own. I found this to be a great reference.
https://www.andyshora.com/tweening-shapes-paths-d3-js.html
EDIT: I realized you were making paths. I'm sure there is a more elegant solution, but you can break the path up at each node to create list of segments. For example, if the path was ABCD you would get
A
AB
ABC
ABCD
Then you can each line with a delay so A is drawn, then AB, then ABC, etc.
let width = 500
let height = 300

//get some paths
let paths = [
    getPath( .5, 0 ),
    getPath( .25, 0 )
]

// for each path, take a length from 0-i
// So for path [(0,0), (1, 1), (2,2)] =>
// [ [(0,0)], [(0,0),(1,1)], [(0,0), (1,1), (2,2)] ]
let pathSegments = paths.map( p => segmentPath( p ))

//make the line generator
var lineGenerator = d3.line()
.x(function(d, i) {
    return d.x;
})
.y(function(d) {
    return d.y;
});

//add the svg
let svg = d3.select("body").style("padding", "30px").append( "svg" ).attr( "height", height).attr( "width", width)

//add the group elements which will contain the segments for each line - merge with update selection -
let lines = svg.selectAll( ".line" ).data( pathSegments )
lines = lines.enter().append( "g" )
    .attr( "class", "line" )
    .merge( lines )

//To add line to g,  selectAll to add the segments - data bound to lines will be passed
// down to children if data is called - in this case .data( d => d ) - d is the segmented
// path [ [(0,0)], [(0,0),(1,1)], [(0,0), (1,1), (2,2)] ] for a single line
// add a delay on stroke-width to give the appearance of being drawn
lines.selectAll( ".segment" ).data( d => d )
    .enter().append( "path" )
        .attr( "class", "segment" )
        .attr( "stroke", "black" )
        .attr( "stroke-width", 0 )
        .attr( "fill", "none" )
        .attr( "d", lineGenerator )
        .transition().duration(750)
        .delay( (d,i) => i * 100 )
            .attr( "stroke-width", 2 )

//helper functions
function getPath( m, b ) {
    let line = [...Array(5).keys()].map( d => {
        return {
            "x": d * 100,
            "y": m * d * 100 + b,
        }
    })
    return line
}
function segmentPath( path ) {
    let segments = []
    for( let i=1; i < path.length; i++ ) {
        segments.push( path.slice(0, i ))
    }
    return segments

}

Of course, you might want to remove the extra segments after adding. Also, it only works if the path segments are small enough to make a smooth transition. If not, segment the line further, or break the path into a set of lines and use the x1,y1,x2,y2 interpolation from above.


text:
Q: node-red requireHttps does not work, accessing http does not redirect to https I am trying to expose a node-red instance into the internet by using HTTPS, following this tutorial.
In short, I added (uncommented) the following lines inside node-red's setting.js :
var fs = require("fs");

requireHttps: true,

https: {
       key: fs.readFileSync('privatekey.pem'),
       cert: fs.readFileSync('certificate.pem')
},

The https worked as expected. However, the http does not redirect to https and instead gives ERR_EMPTY_RESPONSE
Can anybody help?
Thanks.

A: This is working as designed, Node-RED only listens on one port at a time so when configured to use HTTPS it will not respond to HTTP traffic.
This means you cannot redirect from one to the other with just Node-RED. A better solution is to use something like nginx to reverse proxy for Node-RED and have it handle the redirect.
From the article you linked to:

Note:I didn't get this to work with SSL so you may need to skip this

You can see that the author also was mistaken and couldn't get this to work.
.

A: This does the job without any other web server.
Based on Node-RED documentation: Embedding into an existing app, node-RED runs with managed http and https servers provided by node.js.
According to the tuto you've given, you don't have to overide settings.js.
To make this work, you have to create your own project :
$ mkdir myNodeREDProject
$ cd myNodeRedProject
$ touch index.js
$ npm init
$ npm install node-red

Copy your ssl private key and certificate into the myNodeREDProject folder.
Edit index.js and copy the following :
const https = require('https');
const express = require("express");
const RED = require("node-red");
const fs = require('fs');

const HTTP_PORT = 8080;
const HTTPS_PORT = 8443;

// Create an Express app
const app = express();

// at the top of routing: this is the http redirection to https part ;-)
app.all('*', (req, res, next) => {
  if (req.protocol === 'https') return next();
  res.redirect(`https://${req.hostname}:${HTTPS_PORT}${req.url}`);
});

// Add a simple route for static content served from 'public'
app.use("/",express.static("public"));

// Create a https server
const options = {
  key: fs.readFileSync('./privatekey.pem'),
  cert: fs.readFileSync('./certificate.pem')
};
const httpsServer = https.createServer(options, app);
// create a http server
const httpServer = http.createServer(app);

// Create the settings object - see default settings.js file for other options
const settings = {
  httpAdminRoot:"/red",
  httpNodeRoot: "/api",
  userDir:"./nodered/",
  functionGlobalContext: { }    // enables global context
};

// Initialise the runtime with a server and settings
RED.init(httpsServer,settings);

// Serve the editor UI from /red
app.use(settings.httpAdminRoot,RED.httpAdmin);

// Serve the http nodes UI from /api
app.use(settings.httpNodeRoot,RED.httpNode);

httpsServer.listen(HTTPS_PORT);
httpServer.listen(HTTP_PORT);

// Start the runtime
RED.start();

Finally, to run the node-RED application :
$ node index.js   # MAGIC !!!

Please, don't hesitate to correct me if I'm wrong, I've tested it on my Linux server.
Sorry for my english.


text:
Q: How can I parse through a UITextView's .attributedText in order to differentiate between a pasted image and regular text? I have a function for handling pasted images and I'm trying to handle them with my server like iMessage does: having separate messages for text before and after pasted images.
This is my code for adding the image to the textView.
override func didPasteMediaContent(userInfo: [NSObject : AnyObject]) {
    if let pickedImage = UIPasteboard.generalPasteboard().image {
        // Image Caching
        if let data = UIImageJPEGRepresentation(pickedImage, 0.50) {
            hanekeCount += 1
            haneke.set(value: data, key: "pastedImage\(hanekeCount)")
        }

        // Image resizing
        let textViewWidth: CGFloat = self.textView.frame.size.width - 20
        let percentResize = textViewWidth / pickedImage.size.width
        let toBeExportedHeight = pickedImage.size.height * percentResize
        let resizedImage = ImageManipulationManager.sharedInstance.resizeImage(exportedWidth: Int(textViewWidth),exportedHeight: Int(toBeExportedHeight), originalImage: pickedImage)

        // Storage into TextView
        let attributedString = NSAttributedString(string: textView.text)
        let attachment = NSTextAttachment()
        attachment.image = resizedImage
        let attString = NSAttributedString(attachment: attachment)
        print(textView.selectedRange.location)
        textView.textStorage.insertAttributedString(attString, atIndex: textView.selectedRange.location)
        textView.selectedRange.location = textView.selectedRange.location + 1
        textView.textStorage.insertAttributedString(NSAttributedString(string: "\n"), atIndex: textView.selectedRange.location)
        textView.selectedRange.location = textView.selectedRange.location + 1
        textView.font = UIFont.systemFontOfSize(16.0)
    }
}


text:
Q: WPF trying to use pixelshader to disable certain channels I'm trying to use a pixel shader to disable specific channels on an image. Unfortunately, I can't seem to get my shader to work, nor do I know how to do step-through debugging on this. I've tried PIX for windows, but haven't gotten any success with that tool.
Here's my shader file: ChannelEffect .fx
sampler2D implicitInputSampler : register(S0);

float4 main(float2 uv : TEXCOORD) : COLOR
{
// Get the source color
float4 color = tex2D(implicitInputSampler, uv);

color.g = 0.0f;
color.b = 0.0f;
// Return new color
return color;
}

Right now I'm hard-coding the channels I'm disabling, just to test it. This sample should make only the red channel appear.
            ChannelEffect channelEffect = GetChannelEffect(displayChannel);
            image.Effect = channelEffect;

            dc.DrawImage(image.Source, destRect);

The end result I get is that the image renders as normal. Its as if I'm not even applying a shader at all. Any ideas?

A: I was doing something similar- and found Shazzam which is a fantastic program that not only will allow you to tweak and twiddle with shaders but will even generate code for you.  I didn't use that code myself, but it gives a great example on how to use shaders with C# and XAML.
You can even import your own images to test with until you get your shader code exactly right.