text:
Q: Orientable manifold $M$ ,then $\partial M$ is orientable Let $M$ a topological manifold of dimension $n$ with boundary $\partial M$.
We define $M$ to be orientable if $M- \partial M$ is orientable. Here when I say orientable, I mean there is a locally coherent choice $\mu_x$ of generators of $H_n(M,M-x) \cong  \mathbb{Z}$,so that every point $x \in M$ has a $U \cong \mathbb{R}^n \ni x$ such that for every $y \in B(0,1) \subset U$, we have $\mu_y$ comes from the isomorphism $$H_n(M,M-x) \cong H_n(M,M-B(0,1) \cong \mathbb{Z})$$
There is an exercise on Hatcher that says that this implies that $\partial M$ is orientable as an $n-1$ manifold without boundary.
I tried to use the fact that $\partial M$ has a collar neighbourhood to "induce " the orientation on $M$ to an orientation on $\partial M$ but I did not really achieve anything.

A: First, it suffices to consider the case when $M$ and $\partial M$ are both connected. (If $M$ is connected and $\partial M$ contains several components $D_i$, consider manifolds $M_i=(M - \partial M) \cup D_i$ for each $i$.) As you noted, $\partial M$ admits a collar $C\cong \partial M\times [0,1)$, where the homeomorphism sends $C\cap \partial M$ to $\partial M\times \{0\}$. Suppose that $\partial M$ is non-orientable. I will prove that it will imply that $C-\partial M\cong \partial M\times (0,1)$ is non-orientable either. But that would contradict orientability of $M$ in the topological sense. For the following, see Example 6.25 (page 289) in Dold's book "Lectures in Algebraic Topology."
Consider a connected $n$-dimensional topological manifold $N$. Then:

*

*$H^n_c(N; {\mathbb Z})\cong {\mathbb Z}$ if and only if $N$ is orientable.

*$H^n_c(N; {\mathbb Z})\cong {\mathbb Z}_2$ if and only if $N$ is non-orientable.
Hence, with rational coefficients (which I will assume from now on), $H^n_c(N)=0$ if and only if $N$ is non-orientable.
Thus, if our $n$-dimensional manifold $M$ has non-orientable boundary, $H^{n-1}_c(\partial M)=0$. By Kunneth formula:
$$
H^n_{c}(\partial M\times (0,1))\cong H^{n-1}_c(\partial M)\otimes H^1_c((0,1))=0\otimes {\mathbb Q}=0.
$$
Thus, if $\partial M$ is non-orientable, then $\partial M\times (0,1)$ is non-orientable, hence, $C-\partial M$ is non-orientable, hence, $M- \partial M$ is non-orientable.

A: If $b\in\partial M$ is a point in the boundary, there exists an open neighbourhood of $b$ homeomorphic to the half-space $\mathbb{R}^{n-1}\times\mathbb{R}_{\ge 0}$. Take any point $x\in\mathbb{R}^{n-1}\times\mathbb{R}_{>0}$ in the interior, we have $x\in M\setminus\partial M$ and thus the local orientation of $M\setminus\partial M$ at $x$ induces a local orientation of $\partial M$ at $b$. The fact that $M\setminus\partial M$ is orientable implies that this is well defined and coherent along $\partial M$.


text:
Q: Function inside of object doesn't want to change by reference Hay I have this code:
let callback2 = () => console.warn('Old one');

let props2 = {
    callback2
}

function test(props) {
    props.callback2 = () => console.warn('siema');

}

test(props2);

callback2();

Here is also fiddle:
https://jsfiddle.net/4g3p9ego/
And the outcome of that code is "Old one" instead of "siema".
But functions are not Primitives and object also, so I expected outcome 'siema'.
Have you idea Why I got "Old one" message?
========== EDITED: EXTENDED EXAMPLE ===========
let callback2 = () => console.warn('Old one');

let moreTest = {
    moreTest: 'moreTest'
}

let props2 = {
    callback2,
    moreTestObject: moreTest
}

function test(props) {
    props.callback2 = () => console.warn('siema');
    props.moreTestObject.moreTest = 'Changed';

}

test(props2);

console.warn(moreTest)
callback2();

Why here I can change object? But can't change function?
I got:

{moreTest: "Changed"}
"Old one"

Expected:

{moreTest: "Changed"}
"siema"

========== SOLUTION ===========
I understand all, my confusion was caused because I didn't know that object {} always knows how to find it's props. So even I have
testObj = {
   inside: 'inside' // 0x123
}

When I call test.Obj object knows that it needs to go to 0x123. And change testObj like :
testObj.inside = 'outside' //0x125

Use it, testObj.inside and object knows to go to 0x125.
Because object has somehow to keep information where it can find it's props.
Thanks a lot.

A:
But functions are not Primitives

That doesn't matter. You never try to modify a function.
Objects are not primitives either.
First, you create an object and assign your original callback2 function to the callback2 property.

let props2 = {
    callback2
}

Then you copy the value of props2 (which is a reference to that object) to the function argument.

test(props2);

Then you overwrite the value of the callback2 property of that object with a new value (a function that calls console.warn).

props.callback2 = () => console.warn('siema');

Then you call:

callback2();

… but that's a variable that still has a value that is a reference to the original function. You never change that.

Why here I can change object? But can't change function?

x = y changes the thing on the left.
Here:

props.moreTestObject.moreTest = 'Changed';

The thing on the left is the moreTest property of the object referenced by props.moreTestObject.
Here:

props.callback2 = () => console.warn('siema');

The thing on the left is the callback2 property of the object referenced by props.
The thing on the left is not a function.
The value its holds before you assign it a new value is a reference to a function, but that doesn't matter because you are overwriting that value with a new one.
The value of the callback2 variable is also a reference to that function (which is referenced by the old value of props.callback2) but that doesn't matter because you aren't changing the value of the callback2 variable.

A: What you do inside a function will not remain outside a function. You need to return props
function test(props) {
  props.callback2 = () => console.warn('siema');
  return props
}

props2 = test(props2);

A: is because you don't replace callback2 variable but attribute of props object.
// you create variable with 1 reference : exemple is our memory addr 0x123
let callback2 = () => console.warn('Old one');

// You copy this reference to another variable : props2 = 0x123 where 0x123 is reference from previous line.
let props2 = {
    callback2
}

function test(props) {
    let {callback2} = props;
    // You replace old reference by new one, this not impact callback2 variable, just remove 1 reference to callback2 and create new one.
    props.callback2 = () => console.warn('siema'); // Replace 0x123 reference by new one, exemple 0x456

}

test(props2);

callback2();

Is all about count reference by the garbage collector in JavaScript. Official documentation
"Complexe type" as Object and Array require possible heavy memory leak if you really clone the data when you do affection (myVar2 = myVar1).
To prevent this, Javascript copy the reference of your data (adresse in memory) instead of copying full data.
Where is can be confusing on your case.
line : props.callback2 = () => console.warn('siema'); doesn't affect other variables who share the same memory reference. You override previous memory reference by new one on correspond to this new anonymous method () => console.warn('siema');
--- UPDATE 1 ---
let callback2 = () => console.warn('Old one');
// This create Ox123 reference in memory.
let moreTest = {
    moreTest: 'moreTest'
}

let props2 = {
    callback2,
    moreTestObject: moreTest // where ou copy Ox123 reference to moreTestObject property
}

function test(props) {
    props.callback2 = () => console.warn('siema');
    // where you edit Ox123 memory reference, is why  you impact both variable who have same reference.
    // props.moreTestObject.moreTest = 'Changed';
    // here you replace Ox123 memory reference by new one : 0x456. This will not impact moreTest original reference because you don't update Ox123 but replace by new entire reference in moreTestObject property
    props.moreTestObject = { moreTest: 'Changed'};

}

test(props2);

console.warn(moreTest)
callback2();

EDIT 2
According to your last update, i see no other choice than do something like this. Or more graceful second sample
//Change this to var as global variable.
var callback2 = () => console.warn('Old one');

let moreTest = {
    moreTest: 'moreTest'
}

let props2 = {
    callback2,
    moreTestObject: moreTest
}

function test(props) {
    // I see no choice than override both here.
    callback2 = props.callback2 = () => console.warn('siema');

}

test(props2);

console.warn(moreTest)
callback2();

More graceful :
let util = {
    foo : () => console.warn('Old one')
};

let second = {
    util
}
let third = {
    util
}

function test(props) {
     props.foo = () => console.warn('siema');
}

test(util);
util.foo(); // Output `siema`
second.util.foo(); // Output `siema`
third.util.foo(); // Output `siema`

A:
Have you idea Why I got "Old one" message?

Accessibility of let {callback2} = props; inside test() is limited to the block in which it got initialized, i.e. test function.
Outside test, it will retain the old bindings of
let callback2 = () => console.warn('Old one');

Remove let from let {callback2} = props; to set new reference that stays outside  as well..
function test(props) {
    callback2 = props.callback2;

    // callback2 = () => console.warn('siema');
    props.callback2 = () => console.warn('siema');
}

A: If you call props2.callback2() it will output siema.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What Linux distro is this? I ran uname -a but I still have no clue what distro this is. The result:
Linux (none) 3.18.0 #4 Sun May 29 03:28:04 CEST 2016 i686 GNU/Linux
All I can get from that is that it has a i686 processor, and runs the Linux 3.18.0 kernel.
Any help is appreciated, and thank you all in advance!

A: Try this:
$ hostnamectl | grep "Operating System"

If that doesn't return an answer, do this:
$ ls -l /etc/*-release

It will output something like this:
-rw-r--r--. 1 root root  38 Nov 30 02:12 /etc/centos-release
-rw-r--r--. 1 root root 393 Nov 30 02:12 /etc/os-release
lrwxrwxrwx. 1 root root  14 Feb 28 18:40 /etc/redhat-release -> centos-release
lrwxrwxrwx. 1 root root  14 Feb 28 18:40 /etc/system-release -> centos-release

A: Common ways to identify a modern UNIX like system include looking in the following:
/etc/system-release
/etc/system-release-cpe
/etc/os-release
/etc/redhat-release
/etc/centos-release
...
Etc ad naseum.

More info can be found here: CPE dictionary
It will vary depending on distribution, version, etc.


text:
Q: "bash: jstack: command not found" error on Amazon Linux AMI On ec2 instance(Amazon Linux AMI) jstack is giving following error
bash: jstack: command not found
Java is installed on the machine
java -version
java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)

Is there any reason to get error for jstack when java is already installed?

A: JDK is required for jstack. The instance only has JRE.


text:
Q: Why the Email Body is giving different out put? I'm trying to trigger an email from Google App script.
const body = HtmlService.createHtmlOutput( "A  new task  have been added to the Task Manager
 www.abc.com")
if (props.val == "Jonh"){
MailApp.sendEmail("abc@abc.com",task,body,{name:"ABC"})
}

The problem is, email body give nothing but just this
screen shot
What is the mistake?

A: In your script, HtmlOutput object is directly used as the text body. I think that this is the reason for your issue. And, the 3rd argument of sendMail is the text body. In your situation, I thought that HTML body might be your expcted result. In this case, how about the following modification?
Modified script:
const body = HtmlService.createHtmlOutput("A  new task  have been added to the Task Manager
 www.abc.com")
if (props.val == "Jonh") {
  MailApp.sendEmail("abc@abc.com", task, null, { name: "ABC",htmlBody: body.getContent() });
}

Or, in your script, I think that you can directly use the HTML as follows.
if (props.val == "Jonh") {
  MailApp.sendEmail("abc@abc.com", task, null, { name: "ABC",htmlBody: "A  new task  have been added to the Task Manager
 www.abc.com" });
}

Or,
const body = HtmlService.createHtmlOutput("A  new task  have been added to the Task Manager
 www.abc.com")
if (props.val == "Jonh") {
  MailApp.sendEmail({
    to: "abc@abc.com",
    subject: task,
    htmlBody: body.getContent(),
    name: "ABC"
  });
}

Or,
if (props.val == "Jonh") {
  MailApp.sendEmail({
    to: "abc@abc.com",
    subject: task,
    htmlBody: "A  new task  have been added to the Task Manager
 www.abc.com",
    name: "ABC"
  });
}

References:

*

*createHtmlOutput(html)

*sendEmail(recipient, subject, body, options)

*sendEmail(message)


text:
Q: Asymptotic bound in induction I actually thought about this after reading the proof for the Immerman–Szelepcsényi theorem (though it is not necessarily related).

Let us define a series: $a_1,...,a_n$  , where:
  $$a_{i+1} = a_i + \log{n}$$
  and: $$a_1=\log{n}$$
  Obviously we get:
  $a_n = n\log{n}$.

However, let us define the following inductive process:

We will try to prove $a_i = O(\log{n})$ for $i=1,...,n$.
The induction basis is pretty straight forward, we get $a_1 = \log{n}
 = O(\log{n})$.
Now, let's assume correctness for $j\le i$ and let's prove for $i+1$.
  Since by induction hypothesis we get $a_i = O(\log{n})$, we get that
  $a_{i+1} = a_i + \log{n} = O(\log{n}) + \log{n} = O(\log{n})$.
So by proving the induction, we conclude that: $$a_n = O(\log{n})$$

This is obviously wrong, but where is the mistake in this induction? I guess it has something to do with the asymptotic bounds, but if the the basis is correct, and the inductive step (based only on the induction hypothesis) is correct, the induction should be too. What am I missing?
Thanks!

A: For every $n\in\mathbb{N^+}$ you can define the sequence $\{a_k\}$
$$
\begin{cases}
a_{k+1}(n)=a_k(n)+\log n \\
a_1(n)=\log n
\end{cases}
\implies a_k(n)=k\log n \quad\forall k\in\mathbb{N^+}
$$
Notice that the expression "$a_k= O(\log n)$" makes no sense because the value of $n$ is fixed. The asymptotic behaviour of $a_k$ is $O(k)$.
Now, for every fixed value of $k$, consider the sequence $\{b_n\}$ defined by
$$b_n(k)\colon=a_k(n)=k\log n \quad\forall n\in\mathbb{N^+}$$
Of course $b_n=k\log n=O(\log n)\quad\forall k\in\mathbb{N^+}$.
The sequence $\{b_n\}$ must not be confused with the different sequence $\{c_n\}$:
$$ c_n\colon= a_n(n)=b_n(n)=n\log n\ne O(\log n) $$
In this case both $k$ and $n$ grow to infinity and their values are not independent.
When you write "$a_n$" it's ambiguous: do you mean $b_n$ or $c_n$?
This is what you need to clarify in your proof.


text:
Q: How to dynamically specify keys of output object based on input I have a react hook that enriches an object with an extra key and a function to set that key. The input could look like this:
fn(data: {...anything }, key: 'checked', initVal: true)

and the output is going to look like this:
{
    ...originalData,
    checked: initVal,
    setChecked: (val) => // sets val
}

I can't figure out how to type this function so that typescript is going to be aware of the checked and getChecked properties on the returned object or if this is even possible. Help would be much appreciated!

A: You can almost get it to work the way you want. I assumed the name 'checked' should be configurable. You can't construct the name setChecked from checked unfortunately. You can use a more generic name (I used set) or you can pass in the setter name as well.
declare function fn<T, TKey extends string, TValue>(data: T, name: TKey, initVal: TValue) : T & Record<TKey, TValue> & {
    set(value: TValue): void
}

var r = fn({ prop:1 }, 'checked', true)
r.checked
r.set(true)


text:
Q: point cloud to low polly mesh I am using the Kinect sensor to generate a point cloud of a person.
I need to generate from the point cloud the corresponding set of collision surfaces in NVidia PhysX.
To achieve it i have to smooth and after triangulate it to concave mesh/set of convex meshes.
I've found only 1 smoothing algorithm:
    The Moving Least Squares.

To triangulate i've found few algorithms:
    Greedy Projection Triangulation or
    Constrained Delaunay triangulation.
    Ear clipping algorithm

And ready solution witch needs an oriented points as input data.
I also want to do it in realtime(at initialization create mesh and after move parts of it corresponding to real person moves) so i need fast methods. Also smoothing algorithm must return < 1000 points to achieve low polly meshes.
Can u advise some useful methods?

A: Maybe you can use The Point Cloud Library (PCL).
You can find functions for downsampling in module Filters.
And for meshing in the module Surface.
So you should be able to create low poly meshes from your point clouds in realtime.


text:
Q: Databricks save Rdata file to AWS S3 Bucket I have developed a model in R using databricks. I want to save the output datafile on AWS S3 bucket but when I save the file as below it does not save to the mounted drive.
doc <- save(data, file=paste0(getwd(), "/datafile.RData"))

What is the best way to mount data to S3 using R?
I have tried the below sample code and it works so I know my connection between AWS and Databricks is working.
%python
display(dbutils.fs.ls("/"))

A: From Databricks File System (DBFS) documentation:

You can use local file APIs to read and write to DBFS paths.
Databricks configures each cluster node with a FUSE mount /dbfs that
allows processes running on cluster nodes to read and write to the
underlying distributed storage layer with local file APIs. When using
local file APIs, you must provide the path under /dbfs.

For example:
save(data, file="/dbfs/datafile.RData")


text:
Q: segment em with known data opencv I use opencv EM algorithm for segment an image into 2 shapes.
One shape is always inside.  I use EM segment.
I want to use some known model of RGB colors: I have input table of 30*3 which is common colors for the background. How to input this to EM? should I calculate means and std and input to the constructor?
Python: cv2.EM.trainE(samples, means0[, covs0[, weights0[, logLikelihoods[, labels[, probs]]]]]) → retval, logLikelihoods, labels, probs
Python: cv2.EM.trainM(samples, probs0[, logLikelihoods[, labels[, probs]]])

thanks !!

A: You may use the cv.EM.trainE interface and provide the algorithm with you initial 30x3 values as means0 input argument.


text:
Q: Why doesn't this function work when I know that the IP Address is "true"? I am trying to append "DEV SRV:" to the page title (i.e. title tag) if the IP Address matches that of the dev server. I have tried this both in the functions.php file of my child theme and as a standalone plugin
add_filter('wp_title', 'dev_srv_title');
function dev_srv_title($title) {
        $host = $_SERVER['SERVER_ADDR'];
        if ($host =='0.0.0.0') {
                return 'DEV SRV: '.$title;
        }
    return $title;
}

A: The issue was not persistent between multiple installations because there were multiple themes in use. The themes were creating the title tag in different ways.
Changed plugin based solution to inserting conditional banner content (and later a contextual feedback form) in wp_footer which is working regardless of theme (so far )


text:
Q: 404 ERROR when I try to GET data from google spreadsheet Hy everyone, I don't know if exit someone who can help me.
I don't know how it is possible, few days ago all ok now it stop to work.
Basically I read data in a html table on a website from a google spreadsheet public on website and public to everyone with the link. Using ajax.
Until now it worked, i saw all the datas and voices presents on my sheet in google drive, now it stop to show the datas and return an anonymous error like if the link to my google spreadsheet is inexistent, but it is here!!
For example on this googlesheet: https://docs.google.com/spreadsheets/d/13KmAf2uc13fWxPvn8dtk9j9kOL3nCVqi8H-wYau6Tww/edit?usp=sharing
I Have a series of data to display on my html website. Until few days ago it worked, now no.
I used jquery google : src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
I public my code below:

and adapt with your own style

A: Another solution without ajax and jQuery, using fetch https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

List ...

https://codepen.io/mikesteelson/pen/YzQKere
For iOS compatibilty, use instead

List ...


text:
Q: IMacros performing action based on EVAL() result? I am new to imacros so i am having a little problem.
I wanted to imacros perform next command based on what result i get from EVAL() in imacros. Like if EVAL() turns to true then visit a link else don't or click a button or not. Is there any way to do it.
For example i am using imacros on firefox.
The code i am running extracts a text from the page and compares it. If it turns to be true, i want it to press submit button else i want to perform all the tasks again
Thanks


text:
Q: Passing callback function to mongoose aggregate function I am forming the query to be executed within aggregate() as follows:
query.$project = {};
query.$project.created_at = '$created_at';
query.$project.month = {};
query.$project.month.$month = currentMonth;
query.$match = {};
query.$match.month = currentMonth.getMonth() + 1;
query.$limit = 5;
query.$sort = {};
query.$sort.created_at = -1;
query.callback = function(err, result){
    // do something
};
console.dir(query);

But when i execute the following:
DataTable.aggregate(query);

I get this:
Error: Arguments must be aggregate pipeline operators
    at Aggregate.append (C:\myproject\node_modules\mongoose\lib\aggregate.js:87:11)
    at new Aggregate (C:\myproject\node_modules\mongoose\lib\aggregate.js:47:17)
    at Function.aggregate (C:\myproject\node_modules\mongoose\lib\model.js:1889:17)
    at C:\myproject\app\routes.js:179:23
    at C:\myproject\node_modules\async\lib\async.js:570:21
    at C:\myproject\node_modules\async\lib\async.js:249:17
    at C:\myproject\node_modules\async\lib\async.js:125:13

I have two question now:

*

*Is there a better way to form this query.

*And how do i specify callback function here.

Edit
I modified the above code as follows:
query.$project = {};
query.$project.created_at = '$created_at';
query.$project.month = {};
query.$project.month.$month = currentMonth;
query.$match = {};
query.$match.month = currentMonth.getMonth() + 1;
query.$limit = 5;
query.$sort = {};
query.$sort.created_at = -1;

But when i execute the following:
DataTable.aggregate(query, function(err, result){
    // do something
});

A: Quoting Mongoose's documentation for aggregate,

Parameters:

*

*[...] <Object, Array> aggregation pipeline operator(s) or operator array

*[callback] <Function>

It is expecting you to pass

*

*an array of aggregation pipeline operators
DataTable.aggregate([{
    $project: {
        created_at: '$created_at',
        month: {
            $month: currentMonth
        }
    }
}, {
    $match: {
        month: currentMonth.getMonth() + 1
    }
}, {
    $limit: 5
}, {
    $sort: {
        created_at: -1
    }
}], function(err, result) {

});

*or multiple aggregation pipeline operators passed as individual arguments
DataTable.aggregate({
    $project: {
        created_at: '$created_at',
        month: {
            $month: currentMonth
        }
    }
}, {
    $match: {
        month: currentMonth.getMonth() + 1
    }
}, {
    $limit: 5
}, {
    $sort: {
        created_at: -1
    }
}, function(err, result) {

});

I would prefer the pipeline builder way,
DataTable.aggregate().project({
    created_at: '$created_at',
    month: {
        $month: currentMonth
    }
}).match({
    month: currentMonth.getMonth() + 1
}).limit(5).sort({
    created_at: -1
}).exec(function(err, result) {

});

Edit: If you prefer preparing individual items separately, then you can use an array object, like this
var query = [];

query.push({
    $project: {
        created_at: '$created_at',
        month: {
            $month: currentMonth
        }
    }
});

query.push({
    $match: {
        month: currentMonth.getMonth() + 1
    }
});

query.push({
    $limit: 5
});

query.push({
    $sort: {
        created_at: -1
    }
});

DataTable.aggregate(query, function(err, result) {

});

Or using the pipeline builder,
var aggregator = DataTable.aggregate();
...
aggregator = aggregator.project({...});
...
aggregator = aggregator.match({...});
...
aggregator = aggregator.limit(...);
...
aggregator = aggregator.sort(...);
...
aggregator.exec(function(err, result) {

});


text:
Q: SyntaxProblem. How to fill double List the same way how I filled the double array at the bottom in comments How to fill double List the same way how I filled the double array at the bottom in comments.
byte b;
short s;
int i;
long l;

private List<List<Product>> products = new ArrayList<>();
private Product[][] productsArray = new products[4][5];

public Automat(){
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 5; j++) {
            products.get(0).get(j) = new Product(b);
        }
    }
}

As you can see in the image below, products.get(0).get(j) is getting flagged as a syntax error:

A: You cannot assign value using = to an index position of an ArrayList. You have to use arrayListObject.set(index, object).
Example:
products.get(0).set(j, new Product(b));

Hope this helps. Good luck.


text:
Q: Why is my api key not accepted by the Google Directions (Android) request? Whenever I include my Google Play Services API key along with my request for Google Directions like in the code below:
    private String makeDirectionsURL(double originLat, double originLong, double destLat, double destLong)
{
    StringBuilder url = new StringBuilder();
    //first part of url//
    url.append("https://maps.googleapis.com/maps/api/directions/json?");
    //start adding parameters//
    //origin coordinates
    url.append("origin="+originLat+","+originLong);
    //destiniation coordinates
    url.append("&destination=");
    url.append(destLat+","+destLong);
    //api key
    url.append("&key=");
    url.append(getResources().getString(R.string.google_api_key));
    //NOTE: for some reason, the request suceeds when leaving out the api key

    return url.toString();

}

When I include the api key as a parameter in the request, the json response shows that my request has been denied. The response reads:
{
   "error_message" : "This IP, site or mobile application is not authorized to use this API key.",
   "routes" : [],
   "status" : "REQUEST_DENIED"
}
Yet the same api key works for my google map view - and my api console registers the accesses for the map view quota limit. Even odder yet, when I leave out the key parameter in the Directions request I get a valid JSON response.
I have a feeling that I have to generate another different api key for just the Google Directions service - but I'm not sure how to. The documentation here:
 https://developers.google.com/maps/documentation/directions/#api_key
Says to visit the console and activate the Directions API service - I did.
Then it says my api key "will be available from the API Access page, in the Simple API Access section. Directions API applications use the Key for server apps." Now is where I'm confused - how can I use the key for server apps if I am accessing from a mobile device - I'm assuming this is for any webpages that wish to use the service - but what do I do for an android app. As I said, I already tried using my Simple API Access key for Android apps, which I know works, yet when I pass the same key to Google Directions - it mysteriously doesn't work...
Any help, vague guidance, or links to read up on would be really appreciated.
PS: If I can't figure this out - am I allowed to keep sending requests w/o a api key?

A: I think the issue is because you are trying to pass a server key which is directly tied to your server's IP address, when you should be passing an android app key.
In your Google APIs console, navigate to API's and Auth. From here you can create a new public API key.

When prompted, select Android Application

You will need to enter your device's SHA1 Certificate Fingerprint
This comes from the keystore used to sign the apk.  When running an app in debug, you will most likely be using your IDE's debugging keystore.  Google has a nice write up on how to get this information.
When releasing the app, you will need to sign it with your own key.  You will either need to edit your API key to the new keystore SHA1 fingerprint or create a new API key.
Additionally, according to Google, you should be using a key.

All Directions API applications should use an API key. Including a key
  in your request:

*

*Allows you to monitor your application's API usage in the APIs

*Console. Enables per-key instead of per-IP-address quota limits.

*Ensures that Google can contact you about your application if necessary.

While I can't comment on how strictly they enforce this, I strongly encourage you to do so to avoid any issues down the road.


text:
Q: Array reference and implicit constructor: bug in gcc or not? The following code compiles fine with clang 3.5.0, but doesn't compile with gcc 4.9.0 (with -Wall -Wextra -pedantic-errors flags and with any of -std=c++03, -std=c++11 and -std=c++14 flags):
struct S
{
    S(const float(&)[12])
    {
    }
};

float v[12];

S f()
{
    return v;
}

int main()
{
}

MS VC 2013 compiles this code fine, too.
Which compiler is right and what is standard-compliant behavior?


text:
Q: swift - chaining animation combined with UIView.transition One more animation question.
What I need - to write a chain animation, for example:

*

*image 1 shows 6 sec

*change to image 2 with fade effect

*image 2 shows 10 sec

*image 2 scaling to 2 times for 1 sec

*image 2 moves left for 1 sec

*image 2 changes to image 3

*image 3 shows for 12 sec

etc for 20+ images
So the result is a long chain of .animate and .transition with completion blocks, and it looks really awful.
And also duration time isn't working when I want only show image for 6 second - in about 1 second calls completion block with changing image lines.
Would be appriciate for any thoughts about my bug and situation in common.
UIView.animate(withDuration: 6.0, animations: {
                self.imageView.alpha = 1
            }) { _ in

                UIView.transition(with: self.imageView, duration: 1.0, options: .transitionCrossDissolve, animations: {
                    if let imageData = NSData(contentsOf: self.images[0]) {
                        self.imageView.image = UIImage(data: imageData as Data)
                    }
                }) { _ in

               }}


text:
Q: Возможно ли задать увеличение ширины элемента пропорционально уменьшению ширины окна браузера? Имеется следующий образец кода:

1

2

3

.wrapper {
  width: 66%;
  background-color: lightblue;
  height: auto;
  margin: 0 auto
}

.flex {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.item {
  font-family: Roboto, sans-serif;
  font-weight: bold;
  height: 40px;
  background: red;
  color: white;
  text-align: center;
  margin: 30px 0;
}

.item-1 {
  width: 110px
}

.item-2 {
  width: 40%
}

.item-3 {
  width: 110px
}

Возможно ли в данном случае задать увеличение ширины .wrapper пропорционально уменьшению ширины окна браузера?
Пен: https://codepen.io/anon/pen/VVJJwr

A: width: 66vw

подробнее ознакомится можете здесь
https://html5book.ru/edinicy-izmereniya-vh-vw-vmin-vmax/


text:
Q: I am trying to convert byte[] to base64 but getting error I want to create QR Code from user data. I have using below library for creating QR Code.
Install-Package QRCoder

Now I have done below code to convert data into base64 string.
private static Byte[] BitmapToBytes(Bitmap img)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                return stream.ToArray();
            }
        }

        public JsonResult SaveVisitorEntry(string FirstName, string LastName)
        {
            //VisitorEntryDA pdm = new VisitorEntryDA();
            object obj = "";//pdm.getCity(country_id, Convert.ToInt64(state_id));
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(FirstName + " " + LastName, QRCodeGenerator.ECCLevel.Q);
            QRCode qrCode = new QRCode(qrCodeData);
            Bitmap qrCodeImage = qrCode.GetGraphic(20);
            ImageConverter converter = new ImageConverter();
            return Json(JsonConvert.SerializeObject(BitmapToBytes(qrCodeImage)));
        }

Below is my AJAX code where i am converting Base64 to image and showing my QR code to image.
jQuery.ajax({
            url: "../VisitorEntry/SaveVisitorEntry",
            type: "POST",
            //data: "{function:'" + value + "'}",
            data: "{FirstName:'" + FirstName + "',LastName:'" + LastName + "'}",
            dataType: "json",
            traditional: true,
            contentType: "application/json; charset=utf-8",
            success: function (data) {

                debugger
                jQuery("#wait").css("display", "none");
                toastr['success']('Line Stoppage closed Successfully');
                //var results = JSON.parse(data);

                //if (results.length == 0) {
                //    jQuery("#wait").css("display", "none");
                //} else {
                //    f_group_data = results.Table;

                //    bindDropDown("function_name", f_group_data, "FUNCTION", "FUNCTION", "Select");
                //    jQuery('#function_name').chosen();
                //    jQuery('#function_name').trigger("chosen:updated");
                //    jQuery("#wait").css("display", "none");
                //}

                QrCodeImage.setAttribute('src', "data:image/jpg;base64," + data);
                //setTimeout(function () {// wait for 5 secs(2)
                //    location.reload(); // then reload the page.(3)
                //}, 3000);

            },
            error: function (data) {
                jQuery("#wait").css("display", "none");
                console.log("error");
            }
        });

I am not getting correct formate of base64 string and getting below error in console.
Failed to load resource: net::ERR_INVALID_URL

Below value I am getting in data variable
""[encoded data, 9998 characters]…"

A: The base64 value you provided in your question is malformed, my recommendation is to not use Json Serialization for this Api response effort.
Try using Convert.ToBase64String

*

*Ensure the method returns string

*and the jQuery request accepts/expects text for dataType
response.

Diff in your Api Endpoint
public IActionResult SaveVisitorEntry(string FirstName, string LastName)
{
  ...

  return Ok(Convert.ToBase64String(BitmapToBytes(qrCodeImage)));
}

Diff in your request
jQuery.ajax({
  dataType: "text",
  success: function (data) {
    QrCodeImage.setAttribute('src', "data:image/jpg;base64," + data);
  }
});

Edit

*

*Correction on contentType, shoul be dataType that is changed to handle response of request.

Additionally,
Though I'm not certain this is related to the issue you're observing here, I do think the data request payload should be an object, not a string.
  ...
  type: "POST",
  data: {
    FirstName: FirstName,
    LastName: LastName
  },
  dataType: "text",
  ...

You should also consider handling scenarios where both Firstname and Lastname parameter are null, whitespace or string.Empty in your Api endpoint.
I would also string.Trim() here as a sanity effort: qrGenerator.CreateQrCode($"{FirstName} {LastName}".Trim(), QRCodeGenerator.ECCLevel.Q);


text:
Q: Last Insert Row ID in sqlite for xamarin android This is my insert in database code. How can i return the last insert rowid of after insertion? I'm using Xamarin.Android, thanks
public void checkDays(int medID, int mon, int tue, int wed, int thu, int fri, int sat, int sun)
        {
            try{
                sqldb_query = "INSERT INTO Days (medicationID, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday) VALUES ('" + medID + "', '" + mon + "', '" + tue + "', '" + wed + "', '" + thu + "', '" + fri + "', '" + sat + "','" + sun + "');";
                sqldb.ExecSQL(sqldb_query);
                //msg = "Record Saved";
            }catch(Android.Database.Sqlite.SQLiteException e){
                //msg = "No " + e.Message;
                throw(e);
            }
        }


text:
Q: Bulk Inserts in Postgres This is with respect to Data Migration activity where the historical data from the client database is migrated to vendor Postgres Database. There will be millions of transactions that need to be migrated as the Big Bang approach.
In oracle database, I used to use the below template of code for migration -
create or replace PROCEDURE PRC_TEST
AS
DECLARE
    CURSOR CUR
    IS
    SELECT ID,NAME  FROM test;
TYPE test_typ IS TABLE OF CUR%ROWTYPE INDEX BY PLS_INTEGER;
test_tbl test_typ;

BEGIN
OPEN CUR;
LOOP
FETCH cur BULK COLLECT INTO test_tbl LIMIT 1000;
DBMS_OUTPUT.PUT_LINE(test_tbl.COUNT);
     FORALL I IN 1..test_tbl.COUNT --SAVE EXCEPTIONS
                INSERT
                INTO test1(ID,NAME)
                VALUES
                (
                test_tbl(I).id,
                test_tbl(I).name
                );

       FORALL I IN 1..test_tbl.COUNT
                  UPDATE test1
                  SET name     = name||test_tbl(I).NAME
                  WHERE id =test_tbl(I).id;

                DBMS_OUTPUT.PUT_LINE('AFTER'|| test_tbl.COUNT);
        EXIT WHEN CUR%NOTFOUND ;
     END LOOP;
     commit;
 close cur;
 EXCEPTION
      WHEN OTHERS THEN
        FOR I IN 1 .. SQL%BULK_EXCEPTIONS.COUNT
        LOOP
        dbms_output.put_line('error'||sqlerrm);
        END LOOP;
END;
End PRC_TEST;

Is there a plpgsql equivalent code available for the same?
What approach to be used in Postgres while handling such migration activity ? please provide some best practices to be followed for better performance and handling/storing the error records in Postgres.
Thanks..!

A: I would convert this into a single INSERT statement using on conflict do deal with the "insert or update" part:
insert into test1(id, name)
select id, name
from test
on conflict (id) do update
  set name = excluded.name;

This assumes that there is a unique index (or constraint) on test1.id


text:
Q: Cannot login to OpenManage Server Administrator After freshly installed OpenManage Server Administrator from the CD that comes with my new server, Dell PowerEdge T110, I still could not figure out how to login successfully to the application. The server is running Windows 2008 SR2 Foundation and serves as a domain controller.
I access its web interface locally using Firefox 3.6. On the login page and choose local system login. OMSA user's guide seems to state that I should be able to login using an Active Directory user. I tried Administrator, my_domain\Administrator, a a few combinations with the correct password. But none of them can logged in.
Does Server Administrator requires any additional treatment to the user accounts, or what are the steps I missed here?

A: This questions is old, but since I had the same problem and couldn't find the solution here, I'd like to share with you my experience and the solution I found:
Under the security tab in Internet Options click the Custom Level button for the zone in which you've added the address of your server and in User Authentication > Logon select the option "Automatic logon with current user name and password".
This solution worked fine for me and I hope it would be helpful for others too.

A: I come across with the same problem.. What worked for me was, to use the username:
.\Administrator
which indicates the local domain.

NOTE: If the server where SupportAssist Enterprise is installed is a
  member of a Windows domain, you must provide the user name in the
  [Domain\Username] format. For example, MyDomain\MyUsername. You can
  also use a period [ . ] to indicate the local domain. For example,
  .\Administrator.
  Souce: Dell Support

A: Well, it actually turned out that the tried-and-true method, restarting, does fix the problem. I'm not quite understand why and the documentation doesn't seem to mention it. But after the server had rebooted, I can logon with the domain admin account just fine.

A: I restarted the dsm services and was able to login with active directory credentials.


text:
Q: How do you convert a large number of files to docx? I had a large number of doc files that I wanted to convert to docx files.
I discovered that there was not a really good way to automatically do this conversion.
I have submitted the method I used to do this but perhaps there are now other ways.

A: I found a few thing that might help:
Microsoft Bulk Converter
Simple Microsoft Word macro
However I was not satisfied with macro provided. I needed something recursive to also convert nested files. So I expanded it to do so.
Sub SaveAllAsDOCX()

    'Search #EXT to change the extensions to save to docx

    Dim strDocName As String
    Dim strPath As String
    Dim oDoc As Document
    Dim fDialog As FileDialog
    Dim intPos As Integer

    'Create a folder dialog
    Set fDialog = Application.FileDialog(msoFileDialogFolderPicker)
    With fDialog
        .Title = "Select root folder and click OK"
        .AllowMultiSelect = False
        .InitialView = msoFileDialogViewList
        If .Show <> -1 Then
            MsgBox "Cancelled By User", , "List Folder Contents"
            Exit Sub
        End If

    'Select root folder
    strPath = fDialog.SelectedItems.Item(1)

    'Ensure the Folder Name ends with a "\"
    If Right(strPath, 1) <> "\" Then strPath = strPath + "\"

End With

'Close any open documents
If Documents.Count > 0 Then
    Documents.Close SaveChanges:=wdPromptToSaveChanges
End If

'remove any quotes from the folder string
If Left(strPath, 1) = Chr(34) Then
    strPath = Mid(strPath, 2, Len(strPath) - 2)
End If

'begin recusion
recurse (strPath)

End Sub

'This method controls the recusion
Function recurse(folder As String)

    'save all the files in the current folder
    SaveFilesInFolder (folder)

    'get all the subfolders of the current folder
    Dim folderArray
    folderArray = GetSubFolders(folder)

    'Loop through all the non-empty elements for folders
    For j = 1 To UBound(folderArray)
        If folderArray(j) <> "" Then
            'begin recusion on subfolder
            recurse (folder & folderArray(j) & "\")
        End If
    Next
End Function

'Saves all files with listed extensions
Function SaveFilesInFolder(folder As String)

    'List of extensions to look for #EXT
    Dim strFilename As String
    extsArray = Array("*.rtf", "*.doc")

    'Loop through extensions
    For i = 0 To (UBound(extsArray))

        'select the 1st file with the current extension
        strFilename = Dir(folder & extsArray(i), vbNormal)

        'double check the current extension (don't to resave docx files)
        Dim ext As String
        ext = ""
        On Error Resume Next
        ext = Right(strFilename, 5)

        If ext = ".docx" Or ext = "" Then
            'Don't need to resave files in docx format
    Else
        'Save the current file in docx format
        While Len(strFilename) <> 0
            Set oDoc = Documents.Open(folder & strFilename)
            strDocName = ActiveDocument.FullName
            intPos = InStrRev(strDocName, ".")
            strDocName = Left(strDocName, intPos - 1)
            strDocName = strDocName & ".docx"
            oDoc.SaveAs FileName:=strDocName, _
                FileFormat:=wdFormatDocumentDefault
            oDoc.Close SaveChanges:=wdDoNotSaveChanges

            strFilename = Dir
        Wend
    End If
    Next

    strFilename = ""
End Function

'List all the subfolders in the current folder
Function GetSubFolders(RootPath As String)
    Dim FS As New FileSystemObject
    Dim FSfolder As folder
    Dim subfolder As Variant

    Set FSfolder = FS.GetFolder(RootPath)

    'subfolders is variable length
    Dim subfolders() As String
    ReDim subfolders(1 To 10)

    Dim i As Integer
    i = LBound(subfolders)
    For Each subfolder In FSfolder.subfolders
        subfolders(i) = subfolder.Name

        'increase the size of subfolders if it's needed
        i = i + 1
        If (i >= UBound(subfolders)) Then
            ReDim subfolders(1 To (i + 10))
        End If

    Next subfolder

    Set FSfolder = Nothing

    GetSubFolders = subfolders

End Function

Yeah I know it's a lot of code. :)


text:
Q: Exception when using @Transient in hibernate i want to have a Extra variable in bean class  so that i used       @Transient  on the extra member variable which is String date. as i red in some other tutorial
To have Extra column as follows
package com.rasvek.cg.entity;
// Generated May 14, 2018 11:39:07 PM by Hibernate Tools 5.1.7.Final

import static javax.persistence.GenerationType.IDENTITY;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import com.fasterxml.jackson.annotation.JsonIgnore;

/**
 * FeeTermDates generated by hbm2java
 */
@Entity
@Table(name = "fee_term_dates", catalog = "campus_guru_01")
public class FeeTermDates implements java.io.Serializable {

    private int tdmId;
    private FeeTerms feeTerms;
    @Transient
    private String date;

    @Temporal(TemporalType.DATE)
    private Date termDate;
    public FeeTermDates() {
    }

    public FeeTermDates(int tdmId, FeeTerms feeTerms) {
        this.tdmId = tdmId;
        this.feeTerms = feeTerms;
    }

    public FeeTermDates(int tdmId, FeeTerms feeTerms, String date) {
        this.tdmId = tdmId;
        this.feeTerms = feeTerms;
        this.date = date;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "tdm_id", unique = true, nullable = false)
    public int getTdmId() {
        return this.tdmId;
    }

    public void setTdmId(int tdmId) {
        this.tdmId = tdmId;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "term_id", nullable = false)
    public FeeTerms getFeeTerms() {
        return this.feeTerms;
    }

    public void setFeeTerms(FeeTerms feeTerms) {
        this.feeTerms = feeTerms;
    }

    @Column(name = "date")
    public Date getTermDate() {
        return termDate;
    }

    public void setTermDate(Date termDate) {
        this.termDate = termDate;
    }
    public String getDate() {
        return this.date;
    }

    public void setDate(String date) {
        this.date = date;
    }
}

but i am geeing below Exception
org.hibernate.MappingException: Repeated column in mapping for entity: com.rasvek.cg.entity.FeeTermDates column: date (should be mapped with insert="false" update="false")
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:835)
    at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:853)
    at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:875)
    at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:607)
    at org.hibernate.mapping.RootClass.validate(RootClass.java:265)
    at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:459)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
    at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:511)
    at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:495)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1688)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1626)
    ... 77 more

is there any mistake in my bean class to have extra member variable ?
or
is there any other way to do so ?
can any one help me?

A: From JSR 338: JavaTM Persistence API, Version 2.1:

2.3.1 Default Access Type
When annotations are used to define a default access type, the
  placement of the mapping annotations on either the persistent fields
  or persistent properties of the entity class specifies the access type
  as being either field- or property-based access respectively.

*

*When property-based access is used, the object/relational mapping
  annotations for the entity class annotate the getter property
  accessors[7], and the persistence provider runtime accesses persistent
  state via the property accessor methods. All properties not annotated
  with the Transient annotation are persistent.

So, you need to put @Transient on the getter.


text:
Q: ReactJs, Express and Axios, send request to server then respond to client I have a question how to send "params" value to express server. The respond from server to client will not be a big problem because I done the respond. I have problem with sending data to server.
this is my server.js file

const express = require('express');
const axios = require('axios');
const app = express();
const port = process.env.PORT || 5000;
const cors = require('cors');
var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.get('/category', (req, res) => {
   axios.get(`https://newsapi.org/v2/${params}&language=pl&sortBy=publishedAt&apiKey=API`)
  .then(response =>{
      let articles = [];
      response.data.articles.map((article) =>{
          articles.push(article);
      })
  res.send({ articles});
});
})
app.listen(port, () => console.log(`Listening on port ${port}`));

and here is my app.js

  //make api request
  setApiKey = params => {

   this.setState(
    {
      apiKey: api,
   },
   this.makeApiRequest,
  );
   return api;
  }

  //set state after request
  makeApiRequest = () =>{
      axios.get('/category')
      .then(response => {
        this.setState({articles: response.data.articles});
      })
  }

  //set new  api on input chnage
  switchOnInputChange=(event)=>{
     if(event.target.value.length >3) {
        let params = `everything?q=${event.target.value}`
        this.setApiKey(params);
        this.setState({headerText: "Popularne"},
        this.makeApiRequest,
      )
       }
     if (event.target.value.length < 3){
       this.setState({
        apiKey: apiTop,
        headerText: "Popularne"
      },
      this.makeApiRequest,);
    }
  }

scrollOnBtnClick = () =>{
  this.smoothScrollTo(0, window.outerHeight, 1500);
  this.toggleNav();
}
  //change api on click
  switchCatOnClick = (event) =>{
    let text  = event.target.innerText;
    let params = `top-headlines?country=us&category=${event.target.getAttribute("switch")}`
    this.setApiKey(params);
    this.smoothScrollTo(0, window.outerHeight, 1500);
    this.setText(text);
  }

as You can see I want to pass params which are created on click or input change.

A: Working solution:
server.js

app.get('/category',  (req, res) => {

   axios.get(`https://newsapi.org/v2/${req.query.path}?country=${req.query.country}&category=${req.query.category}&apiKey=API_KEY`)

  .then(response =>{
      let articles = [];
      response.data.articles.map((article) =>{
          articles.push(article);
      })
  res.send({ articles});
});
})

app.js

 switchCatOnClick = (event) =>{
    let text  = event.target.innerText;
    let params = `path=top-headlines&country=pl&category=${event.target.getAttribute("switch")}`
    this.callApi(`/category?${params}`)
    .then(response => {
      this.setState({
        articles: response.articles
      });
    });
    this.smoothScrollTo(0, window.outerHeight, 1500);
    this.setText(text);
    this.scrollOnBtnClick();
    this.toggleNav
  }


text:
Q: Update Score based on interactive feedback for Elasticsearch I am working on a project, which requires me to build a UI for a search engine. Elasticsearch is my choice. After indexing data and doing search queries, I also implement a function so that, if the user ticks on a result that is not relevant, I will reduce the score of that specific data in elasticsearch. However, when doing the second search with the same query, the order of search results remained the same. The reason is that even though the score is updated, the order of the data in elasticsearch index remained unchanged.
How do I reflect the score changes without having to reindex the whole thing again?

A: You could add a bool / should query. There you perform a term query with a boosting.
This is how you change the order depending on the search.


text:
Q: error when read xml from a stream by boost i'm trying get a xml response from ip-api.com to get some information. But i don't know why i can't read xml from stringstream.
Here is my code:
boost::asio::ip::tcp::iostream stream;
stream.expires_from_now(boost::posix_time::seconds(60));
stream.connect("ip-api.com", "http");
stream << "GET /xml HTTP/1.0\r\n";
stream << "Host: ip-api.com\r\n";
stream << "Accept: */*\r\n";
stream << "Connection: close\r\n\r\n";
stream.flush();
//std::cout << stream.rdbuf() << std::endl;
char res[255];
std::stringstream ss;
while (!stream.eof()) {
    stream.getline(res, 255);
    ss << res << "\n";
}
std::cout << ss.str();
boost::property_tree::ptree ntree;
boost::property_tree::read_xml(ss, ntree); <~ exeption in here
boost::property_tree::ptree vals = ntree.get_child("query");
BOOST_FOREACH(auto f, vals) {
    if (f.first == "country") std::cout << f.second.data() << std::endl;
    if (f.first == "city") std::cout << f.second.data() << std::endl;
    if (f.first == "query") std::cout << f.second.data();
}

A: So the exception reads
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::property_tree::xml_parser::xml_parser_error> >'
  what():  <unspecified file>(1): expected <

What you could have seen from dumping the response is that it starts with HTTP response headers. Here's a simplified piece of code with those checks:
#include <boost/asio.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>

boost::property_tree::ptree ipApiCheck() {
    boost::asio::ip::tcp::iostream stream;
    stream.expires_from_now(boost::posix_time::seconds(2));
    stream.connect("ip-api.com", "80");
    stream << "GET /xml HTTP/1.0\r\n";
    stream << "Host: ip-api.com\r\n";
    stream << "Accept: */*\r\n";
    stream << "Connection: close\r\n\r\n";
    stream.flush();

    std::string const response(std::istreambuf_iterator<char>(stream), {});
    auto headersEnd = response.find("\r\n\r\n");
    if (std::string::npos == headersEnd)
        throw std::runtime_error("Malformed response");

    std::istringstream iss(response.substr(headersEnd+4));
    boost::property_tree::ptree ntree;
    read_xml(iss, ntree);
    return ntree;
}

int main() {
    auto xml = ipApiCheck();

    std::cout
        << "country: " << xml.get("query.country", "?") << "\n"
        << "city   : " << xml.get("query.city", "?") << "\n"
        << "query  : " << xml.get("query.query", "?") << "\n";
}

Prints, e.g.
country: Zimbabwe
city   : Harare
query  : 56.155.44.177


text:
Q: PowerBI consuming Data Bricks consuming Azure Data Lake GEN1 I am trying to consume Azure Data Bricks from Power BI.
Bricks has been set up to connect to Azure DataLake GEN1.
I have no issue in getting data out of GEN1 from Bricks.
And I have no issue in consuming a Bricks instance from Power BI.
However, when trying the whole chain, Power BI consuming Bricks and Bricks calling into GEN1, I get a security related error saying that is not possible to find ADLS Gen1 Token in com.databricks.backend.daemon.data.client.adl.AdlCredentialContextTokenProvider.
Do you have any idea of what the problem that I am facing could be?
Cheers,
G.


text:
Q: Syntax highlighting: rich text box control for .NET I'm looking for a free control/component/library something like a rich text box for editing codes of python (or other languages.)
I like to have some features:

*

*Highlight codes

*Auto Indent

*Line numbering

*Defining new styles or rules of highlighting (for OpenType keywords)

Is there such a control? or I have to write my own?

A: Have a look at ScintillaNET.

ScintillaNET is a powerful text editing control for Windows Forms applications and a managed wrapper around the versatile Scintilla Windows control. Created with the developer in mind, the ScintllaNET API makes it simple to add advanced text editing and syntax highlighting to your application or IDE (Integrated Developer Environment) .

A: A commercial option is ActiPro Software's SyntaxEditor. The link is for a WPF version of the control. They also offer a WinForms version which I've used for XML editing - works very well.
From what I've read on the site, the WPF version supports ANTLR-generated lexer-parsers.


text:
Q: Nodejs client for SOLR- how to build facets in the query I am trying for some time now to get facets in the nodejs client query that I am using. Below is the snippet for the same.
var client = sails.solr;
var query = client.createQuery().q({
  'city_id': options.city_id,
  'content_auto': options.term,
})
.fl('sku+score')
.start(0)
.rows(200)
.facet(true)
.facet.field('brand')
var defer = sails.Q.defer();
client.search(query, function(err, obj){
    if(err) {
        console.log('Error getting data from solr. Error: ' + err);
        return defer.reject(err);
    }
    return defer.resolve(obj.response.docs);
});
return defer.promise;

But its not working and there's almost no documentation for the same. Would someone know how to get it working or even a reference would help!
Thanks!

A: This finally worked!
.facet('brand')

A: This worked for me.
.facet(
    {'field':'brand'}
 );


text:
Q: Is there a python way to groupby the dataframe in the below way I have a data frame that has the details of person1 and person2 which is obtained when they breach social distance. I have details such as timestamp. I want to groupby the data frame for each person for a date and for a particular hour. I have completed these steps. but the problem I am facing is, is there a way to extract the people with whom he contacted with the groupby method. I have written the below code:
df2_sd = df_2.groupby(['Date', 'Hour', 'username']).agg({'breach_count' : ['sum']})

Is there a better way to extract this information? i have attached sample data frame for reference (left: sample, right: result required)

A: u can pass ','.join()  to aggregate function
>>>df2_sd=df_2.groupby(['Date', 'Hour', 'username']).agg({'breach_count' : sum,'contact_name':','.join}).reset_index()
>>>print(df2_sd)
         Date  Hour username  breach_count contact_name
0  01-06-2020     1        A             3        X,X,Y
1  01-06-2020     2        A             1            X
2  01-06-2020     2        B             1            Y
3  01-06-2020     2        C             1            Z
4  01-06-2020     3        A             1            A
5  01-06-2020     3        B             1            A
6  01-06-2020     3        C             1            B


text:
Q: $10$ distinct color balls and we want to divide them into $3$ identical boxes with hard restrictions and probability
We have $10$ distinct color balls and we want to divide them into $3$ identical boxes .We decide that two of the groups can contain at most $3$ balls and the rest one contain at most $4$ balls. Moreover, there are two balls called $A$ and $B$ in $10$ balls.
$1-)$ How many ways are there to distribute these $10$ balls to $3$ groups obeying size restriction of groups and $A$ and $B$ are in the same box?
$2-)$ What is the probability that $A$ and $B$ are in the same boxes obeying size restriction of boxes?
$3-)$  How many ways are there to distribute these $10$ balls to $3$ groups obeying size restriction of groups and $A$ and $B$ are not in the same box?
$4-)$ What is the probability that $A$ and $B$ are not in the same boxes obeying size restriction of boxes?
$5-)$ Solve the foregoing $4$ questions if the number of balls is $7$ instead of $10$.

Solution
$1-)$ $$\bigg (\frac{\binom{8}{1}\binom{7}{3}\binom{4}{4}}{2!}=140 \bigg)+ \bigg (\frac{\binom{8}{3}\binom{5}{3}\binom{2}{2}}{2!} =280\bigg )=420$$
$2-)$ $$\bigg (\frac{\binom{8}{1}\binom{7}{3}\binom{4}{4}}{2!}+ \frac{\binom{8}{3}\binom{5}{3}\binom{2}{2}}{2!} \bigg )/\frac{\binom{10}{3}\binom{7}{3}\binom{4}{4}}{2!}=42/168$$
$3-)$ $$\frac{\binom{10}{3}\binom{7}{3}\binom{4}{4}}{2!}-420 =2100-420=1680$$
$4-)$ By using $3$ and $4$ , $$1-42/168=126/168$$
$5-)$ I could not solve this part because of low number of balls, and I do not know how to distribute.
Are my solutions correct? If not, can you correct me and help for $5$?

A: First question:
The first term is incorrect. It should be,
$ \displaystyle \binom{8}{1}\binom{7}{3}\binom{4}{4}=280$
Unlike second term, it should not be divided by $2!$ as the boxes having $3$ balls each are different groups - one of them has $A$ and $B$ and the other is without them.
So the answer should be $560$
Second question:
The denominator, as you mentioned, $ \displaystyle \binom{10}{3}\binom{7}{3}\binom{4}{4} / 2! = 2100$
So the probability is $\displaystyle \frac{560}{2100} = \frac{4}{15}$
Now you can use above results to solve $(3)$ and $(4)$.
Coming to the question if there are $7$ balls instead of $10$, you can break it into cases: $i$) three groups with $1, 2, 4$ balls $ii$) three groups with $2, 2, 3$ balls $iii$) $1, 3, 3$ balls


text:
Q: Heroku Deployment Failure from Travis CI My app deployment to Heroku stopped working two days ago, (January 14th). I received the error:

API request failed. Message: Invalid credentials provided.

This app has been online for nearly a year and I've never had issues with a deployment before. I use GitHub for version control. Testing and deployment to Heroku are automatically performed by Travis CI when any updates are pushed to the Master branch.
Here's a link to the latest broken build: https://travis-ci.org/drichards211/revuer/builds/637772527
221 The command "npm test" exited with 0.
222 store build cache
223 nothing changed
224
225 rvm $(travis_internal_ruby) --fuzzy do ruby -S gem install dpl
226 Successfully installed dpl-1.10.14
227 1 gem installed
228
229 Installing deploy dependencies
230 Successfully installed multipart-post-2.1.1
231 Successfully installed faraday-1.0.0
232 Successfully installed rendezvous-0.1.3
233 Successfully installed netrc-0.11.0
234 Successfully installed dpl-heroku-1.10.14
235 5 gems installed
236
237 API request failed.
238 Message: Invalid credentials provided.
239 Reference:
240 Preparing deploy
241
242 failed to deploy

Nothing has changed on my end. I've since updated all Node dependencies as a broad-spectrum inoculant, but the problem appears after the tests successfully complete and deployment is attempted by Travis. This appears to be a credentials handshake issue between Travis CI and Heroku.
I attempted opening a ticket with Heroku, but they won't accept tickets on free applications. I wrote a similar message on the Travis Community Forums; one of their developers got back to me right away, but they haven't been able to find anything wrong, yet.
I've also updated my Heroku API token and encrypted and updated that value with Travis CI. No change.
Any ideas?

A: 24 hours later I re-encrypted the Heroku API token again and updated the value with Travis CI. This time it worked; a successful deployment. There's no indication as to the cause of the initial problem or as to why it's working now. A delicious mystery.


text:
Q: Troubles with Advertising Studio Facebook In Advertising Studio I'm building a audience in facebook to test the functionality and I'm receiving the error message bellow. I've search for some miss configuration that i've done, but I cant reach the answer

Does anyone has any idea how to fix this before I'll contact Salesforce support?

A: The error seems to be self explanatory. Do you own the facebook page that you are trying to integrate with AB


text:
Q: Сортировка Map в обратном порядке по значению Помогите, нужно отсортировать Map в обратном порядке по значению (Value).
Map<String, Integer> map = new HashMap<>();
map.put("Text1", 0);
map.put("Text2", 1);
map.put("Text3", 2);
map.put("Text4", 0);

Надо чтобы оно отсортировало так:
Key - Value:

Text3 - 2
Text2 - 1
Text1 - 0
Text4 - 0

или
Text3 - 2
Text2 - 1
Text4 - 0
Text1 - 0

A: Может кому будет полезным, вот как я сделал:
private static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    return map.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    (e1, e2) -> e1,
                    LinkedHashMap::new
            ));
}


text:
Q: How would I include a non-existent module as a dependency in Angular tests? I have inherited two angular apps. The one app(AppB) that I'm writing tests for and for lack of better phrasing it sets atop another app(AppB) that I've created. I want each of these to be their own separate repos with tests that cover that repo.
So I have a module with a controller that I want to test that looks something like this
angular.module('moduleName', ['moduleDependency1','moduleDependency2','moduleDependency3'])

Where moduleDependency2 is not included in the config because this particular code doesn't need to be tested in this module.
I have tried setting the following up to test this module
beforeEach(function() {

    module('moduleName');

    inject(function (_$rootScope_, _$controller_, _$q_) {
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
        $controller = _$controller_;
        $q = _$q_;
    });

});

however this returns:
Error: [$injector:modulerr] http://errors.angularjs.org/1.5.7/$injector/modulerr?p0=moduleName
I tried declaring each module dependency but the moduleDependency2 then threw an error about not being defined.
What am I missing here?


text:
Q: How to refer from one container to another using localhost I'm working on building docker containers for a Ruby-on-Rails project I'm currently working on, so that I can develop this project using the remote feature of Visual Studio Code. This project should still continue to work without using docker containers, so I cannot make breaking changes to the existing code that would compromise this.
The application server (Rails) needs to connect to a MySQL database that's running in a separate container. The database container is named db, and I can connect from the application container to this container by using the db hostname.
The database.yml config file for rails defines how to connect to the database, but this is where my problem is situated. I don't want to change the host to db instead of localhost as this would mean that regular users (that do not use Docker containers) will no longer be able to connect to the database without changing this file. How can I somehow start or change my docker config so that db is accessible as localhost instead of db inside of the application container?
database.yml:
default: &default
  adapter: mysql2
  username: ****
  password: ****
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: ****
  # setup local port forwarding for this to work
  host: db
  port: 3306

docker-compose.yml:
version: '3.7'

services:
  db:
    build: ./unipept-db
    environment:
      MYSQL_ROOT_PASSWORD: ****
      MYSQL_DATABASE: ****
      MYSQL_USER: ****
      MYSQL_PASSWORD: ****
    restart: always
    ports:
      - "3306:3306"
    hostname: mysql
  phpmyadmin:
    depends_on:
      - db
    image: phpmyadmin/phpmyadmin
    ports:
      - '8080:80'
    environment:
      PMA_HOST: db
      MYSQL_ROOT_PASSWORD: ****
    restart: always
  app:
    depends_on:
      - db
    build: ./unipept-application
    command: sleep infinity
    ports:
      - '5000:5000'
    volumes:
      - ~/.gitconfig:/root/.gitconfig
      - ..:/workspace

A: user network_mode: "host"in your APP config then you can call the DBfrom your APP using localhost:PORT
phpmyadmin:
    depends_on:
      - db
    image: phpmyadmin/phpmyadmin
    ports:
      - '8080:80'
    environment:
      PMA_HOST: db
      MYSQL_ROOT_PASSWORD: ****
    restart: always
    network_mode: "host"
  app:
    depends_on:
      - db
    build: ./unipept-application
    command: sleep infinity
    ports:
      - '5000:5000'
    network_mode: "host"
    volumes:
      - ~/.gitconfig:/root/.gitconfig
      - ..:/workspace

PS: Published ports are discarded when using host network mode

A: If you make it an environment variable in your database.yml.erb file, it will be configurable.  You even already have an example of this.  You can set:
host: <%= ENV.fetch('DB_HOST', 'localhost') %>

In development, just don't set the environment variable, and it will use localhost.  In a Docker environment, do set it, and it will use that hostname.
version: '3'
services:
  db:
    image: mysql
  app:
    build: .
    environment:
      DB_HOST: db
    ports:
      - '5000:5000'

You should also pass things like database credentials the same way.


text:
Q: Changing Multiple Image Trouble on Mouse over I have trouble changing multiple images on mouseover. I tried the function below to change the image on mouseover but it didnt work perfectly.  With the Onmouseover event the first image fades out slowly then the second image fades in smoothly.  After a few seconds the second image fades out slowly and the third image fades in smoothly.
function changeimage(img_id)
{
setTimeout(function(){ $("#"+img_id).attr("src","http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/prdt_03.jpg").show(); }, 5000);
    $("#"+img_id).attr("src","http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/prdt_05.jpg").fadeIn(5000);
    setTimeout(function(){ $("#"+img_id).attr("src","http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/prdt_05.jpg").show(); }, 5000);
    $("#"+img_id).attr("src","http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/prdt_05.jpg").fadeOut(5500);
}

Jsfiddle link:
http://jsfiddle.net/XVz95/3/

A: I made your jsfiddle link just works:
function changeimage(img_id)
{
setTimeout(function(){ $("#"+img_id).attr("src","http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/prdt_03.jpg").show(); }, 5000);
    $("#"+img_id).attr("src","http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/prdt_05.jpg").fadeIn(5000);
    setTimeout(function(){ $("#"+img_id).attr("src","http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/prdt_05.jpg").show(); }, 5000);
    $("#"+img_id).attr("src","http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/prdt_05.jpg").fadeOut(5500);
}

http://jsfiddle.net/XVz95/4/

A: You can do it in jQuery as follows
The Markup:

The javascript:
$( document ).ready(function() {
    $('#pdtimg_1').mouseover(function(){
        $(this).find('img:first').hide();
        $(this).find('img:last').show();
    });

    $('#pdtimg_1').mouseout(function(){
        $(this).find('img:first').show();
        $(this).find('img:last').hide();
    });
});

http://jsfiddle.net/CabK3/
-----------------------------------UPDATE-------------------
$( document ).ready(function() {
$('#pdtimg_1').mouseover(function(){
    var elem  = $(this);
    elem.find('img:first').fadeOut(5000, function() {
        elem.find('img:nth-child(2)').fadeIn(5000, function() {
             elem.find('img:nth-child(2)').fadeOut(5000);
            elem.find('img:last').fadeIn(5000);
        });
    });

});

});
and

A: Is this like what you want? It allows for an array of image sources, in case you need to add more pictures:
function changeImage(img) {
    var imgSrcArr = [];
    imgSrcArr.push("http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/men-wedding-rings.jpg");
    imgSrcArr.push("http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/prdt_03.jpg");
    imgSrcArr.push("http://247nywebdesign.com/Testing/nurses-jewel/php/pdt_images/prdt_05.jpg");

    $img = $(img);
    if ($img.is(":visible")) {
        $img.fadeOut(5500, function() {
            var i = imgSrcArr.indexOf($(this).attr("src"));
            i = i+1 >= imgSrcArr.length ? 0 : i+1;
            $(this).attr("src", imgSrcArr[i]).on('load', function() {$(this).fadeIn(5000)})
        });
    } else {
        $img.fadeIn(5000);
    }
}

$("#pdtimg_1").mouseenter(function() {changeImage(this)});

jsFiddle example


text:
Q: Pivot_longer 6 columns to 3 columns I know my question is simple but I've trying all morning and I can't get my head around it.
I have this data frame:
  GeneID Gene.Symbol01    Ratio.2h   Ratio.6h  Ratio.10h  Ratio.24h  Pvalue_2h
 1    174           FUT -0.23618761 -0.3276162 -0.1366940 -4.4899131 0.49045105
  Pvalue_6h Pvalue_10h   Pvalue_24h
 1 0.06128851 0.59995612 0.0001798584

And I need to pivot_longer all columns except GeneID and GeneSymbol. The resulting data frame should have 3 new columns. One with time: 2h, 6h, 10h, and 24h. Then two more columns with the ratio values and another one with the pvalues.
I know this should be done with a combinametion of names_to and names_pattern.
I have tried many things but I can't get it.
Last thing I have tried was this:
pivot_longer(cols = -c(GeneID, Gene.Symbol01),
             names_to = c("Time", ".value"),
             names_pattern = "_")

Dput:
structure(list(GeneID = 174, Gene.Symbol01 = "FUT", Ratio.2h = -0.23618761,
    Ratio.6h = -0.3276162, Ratio.10h = -0.136694, Ratio.24h = -4.4899131,
    Pvalue_2h = 0.49045105, Pvalue_6h = 0.06128851, Pvalue_10h = 0.59995612,
    Pvalue_24h = 0.0001798584), row.names = c(NA, -1L), class = c("tbl_df",
"tbl", "data.frame"))

A: Using tidyverse you might want to pivot_longer all variable from Ratio.2h to Pvalue_24h, then separate it into 2 columns.
library(tidyverse)

DF %>%
  pivot_longer(Ratio.2h:Pvalue_24h, names_to = "var") %>%
  separate(var, into = c("type", "time"), sep = "_|\\.")

# # A tibble: 8 x 5
#   GeneID Gene.Symbol01 type   time      value
#    <dbl> <chr>         <chr>  <chr>     <dbl>
# 1    174 FUT           Ratio  2h    -0.236
# 2    174 FUT           Ratio  6h    -0.328
# 3    174 FUT           Ratio  10h   -0.137
# 4    174 FUT           Ratio  24h   -4.49
# 5    174 FUT           Pvalue 2h     0.490
# 6    174 FUT           Pvalue 6h     0.0613
# 7    174 FUT           Pvalue 10h    0.600
# 8    174 FUT           Pvalue 24h    0.000180

then, change back it to wider format using pivot_wider
DF %>%
  pivot_longer(Ratio.2h:Pvalue_24h, names_to = "var") %>%
  separate(var, into = c("type", "time"), sep = "_|\\.") %>%
  pivot_wider(names_from = "type", values_from = "value")

# # A tibble: 4 x 5
#   GeneID Gene.Symbol01 time   Ratio   Pvalue
#    <dbl> <chr>         <chr>  <dbl>    <dbl>
# 1    174 FUT           2h    -0.236 0.490
# 2    174 FUT           6h    -0.328 0.0613
# 3    174 FUT           10h   -0.137 0.600
# 4    174 FUT           24h   -4.49  0.000180

Data
DF <- tribble(~GeneID, ~Gene.Symbol01,  ~Ratio.2h,   ~Ratio.6h, ~Ratio.10h, ~Ratio.24h, ~Pvalue_2h,~Pvalue_6h, ~Pvalue_10h,   ~Pvalue_24h,
              174, "FUT", -0.23618761, -0.3276162, -0.1366940, -4.4899131, 0.49045105,0.06128851, 0.59995612, 0.0001798584)

A: using melt:
library(data.table)

melt(df,id.vars=1:2) %>% separate(variable,c("type","time"))) %>%
 pivot_wider(names_from =type,values_from= value)

Result:

#
# GeneID Gene.Symbol01 time   Ratio   Pvalue
#   <dbl> <fct>         <chr>  <dbl>    <dbl>
#1    174 FUT           2h    -0.236 0.490
#2    174 FUT           6h    -0.328 0.0613
#3    174 FUT           10h   -0.137 0.600
#4    174 FUT           24h   -4.49  0.000180


text:
Q: How to get results of the weekend laravel I'm trying to get results of the weekend in laravel. I would like to show all the events of the weekend during all the week. So I would like to show all results from monday to sunday, but just weekend events.
I have:
$friday = Carbon::parse('this friday')->toDateTimeString();
$sunday = Carbon::parse('this sunday')->toDateTimeString();
if (Carbon::now()->gt(Carbon::parse('this friday'))) {
        $friday = Carbon::parse('last friday')->toDateTimeString();
}
$events = Event::where([
        ['date', '>=', $friday],
        ['date', '<=', $sunday]
    ])
        ->orderBy('date', 'asc')
        ->get();

But when it's satuday this doesn't work. I don't know how to do it. Any idea?
Thanks!

A: Firstly, you can use code:$dt = Carbon::now(); $dt->isWeekend(); to check is weekend or not, then calculate the $friday date and $sunday date.

A: I also need to show events filtered by week and weekend:
$now = Carbon::now();

//This weekend's datarange
$starOftWeekend = $now->endOfWeek()->subDays(2)->format('Y-m-d H:i');
$endOfWeekend   = $now->endOfWeek()->format('Y-m-d H:i');

//Weekly date range
$startOfWeek = $now->startOfWeek()->format('Y-m-d H:i');
$endOfWeek = $now->endOfWeek()->format('Y-m-d H:i');


text:
Q: How is new version of an ASPX file compiled and loaded into the application? Upon serving a request for an ASPX page, if ASP.NET notices any change to that page, it will automatically recompile the page into an assembly and use that new page definition to handle to the request.
As far as I know, .NET doesn't allow us to unload an assembly from an application domain.  However, it does allow us to unload the whole application domain (with its assemblies).  Therefore, it seems to me that the only way ASP.NET can replace the old assembly with the new assembly (of the updated ASPX file) is unloading the whole application domain and create a new one to host the web application (which is effectively a application restart, which happens when the web.config is changed, assemblies bin folder are updated etc.)  However, I notice that it seems not to be the case as the application responds much more quickly after I modify an ASPX file than when I modify the web.config file.
Therefore, my question is: is it possible for ASP.NET to load new version of the assembly of an ASPX page without having to unload the whole application and create a new one?

A: ASP.NET can't unload the old assembly without the restarting the application, but it can ignore the old assembly and start using the newly compiled version of your page. A new assembly is compiled and loaded (actually containing the whole folder rather than just the one changed page) and subsequent requests use that new assembly.
You can see the change of assembly by writing out the assembly name in your page:
<%= System.Reflection.Assembly.GetExecutingAssembly().FullName %>

With two pages in different folders you'll see that the changed page moves to a new assembly, while the other page is unaffected.
To avoid gradually filling up memory with old assemblies, the application will occasionally be restarted in response to a change. By default this is every 15 changes, though you can adjust that in web.config with
<compilation debug="false" numRecompilesBeforeAppRestart="50" ...

A: Steve's answer is largely accurate, though the behaviour described (assembly generation on file changes) is predicated on the default CompilationMode=Always; you can avoid assembly generation all together with CompilationMode=Never. As an aside, note that there is also a new attribute available in 3.5, though it relates specifically to top-level changes that would have previously re-started the application (like web.config):

By default, when any change is made to
  a top-level file in a Web site, the
  whole site is recompiled. Top-level
  files include the global.asax file and
  all files in the bin and App_Code
  folders. It is safest to recompile
  everything when one of these files
  changes because other files in the
  site, such as .aspx and .ascx files,
  may reference the objects created by
  code in top-level files.
While recompiling everything works
  fine for most applications, it could
  cause a very large application to be
  unavailable for long periods of time
  even when minor changes have been made
  to it. If the application is large
  enough, it could be unavailable for
  five to ten minutes or more after a
  change is made.
If you want to be able to change
  top-level files without causing the
  whole site to be recompiled, you can
  set the optimizeCompilations attribute
  of the compilation element in the
  Web.config file to true.

A: ASP.NET compute hashes of your files and when they changes it recompile them
and since .net can't unload assemblies without unloading entire appdomain asp.net cannot do it too


text:
Q: How to change json of default settings in vscode? I tried to add wordpress at intelephense.stubs in defaultSettings.json. But, I couldn't edit it. It showed:

I am not expert at it. I have added it at settings.json like this way:

Did I do it correctly? Will the entire intelephense.stubs be replaced with just that single value? or it will work like this way (which I tried to achieve)?:
"intelephense.stubs": [
    "apache",
    "bcmath",
    ..........
    "zlib",
    "wordpress"
]

A: Yes. You've done right.
Just put it in your settings and it will overwrite default settings.
To be completely sure, copy the default settings and paste them in settings, adding the ones you want to.


text:
Q: PostgreSQL and nodejs/pg, return nested JSON I'm using PostgreSQL with nodejs and pg.
Everything works fine, but I want to output a result from PostgreSQL as a nested json - as if I was working with MongoDB or similar.
My 2 tables from PostgreSQL are:
portfolio (id int, name text)

cars (portfolio_id int, name text);

Is there a "correct" way of returning a JSON object with the following structure:
{
    { name: 'Portfolio #1', cars: { name: 'Car #1', name: 'Car #2' },
    { name: 'Portfolio #2', cars: { name: 'Car #3' }
}

My general way of querying the database in nodejs/pg is:
client.query('SELECT ...', [params], function(err, result) {
    done();
    if (err) {
        res.status(500).json({ error: err });
    } else {
        res.json({ portfolios: result.rows });
    }
});

A: In PostgreSQL, you can build the following JSON object:
[
    { "name": "Portfolio #1", "cars": [ "Car #1", "Car #2" ] },
    { "name": "Portfolio #2", "cars": [ "Car #3" ] }
]

You could construct the object from your tables with the following query:
select array_to_json(array(
  select row_to_json(n)
  from portfolio p
  left join lateral (select p.name, array(select name from cars where portfolio_id = p.id) as cars) n on true
  ))

And with cars.votes fields included:
select array_to_json(array(
  select row_to_json(n)
  from portfolio p
  left join lateral (select p.id, p.name, array_to_json(array(
     select row_to_json((select a from (select c.name, c.votes) a))
     from cars c
     where portfolio_id = p.id)) as cars) n on true
  ))


text:
Q: Kotlin LocalDateTime as Long I am trying to get my LocalDateTime field saved as a long so I can store it in my SQLite database. How am I able to do this?
var datetime = LocalDateTime.now()
var longdt: Long = getString(datetime).toLong()

A: You can use toEpochSecond() and ofEpochSecond() to convert to/from a long value with precision to the second.
Example (in Java)
LocalDateTime now = LocalDateTime.now();
long nowInSeconds = now.toEpochSecond(ZoneOffset.UTC);
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(nowInSeconds, 0, ZoneOffset.UTC);

System.out.println("now = " + now);
System.out.println("nowInSeconds = " + nowInSeconds);
System.out.println("dateTime = " + dateTime);

Output
now = 2020-05-12T12:12:36.984263200
nowInSeconds = 1589285556
dateTime = 2020-05-12T12:12:36

If you needed the long value with precision to the millisecond, do this:
LocalDateTime now = LocalDateTime.now();
long nowInMillis = now.toEpochSecond(ZoneOffset.UTC) * 1000
                 + now.get(ChronoField.MILLI_OF_SECOND);
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(nowInMillis / 1000,
                  (int) (nowInMillis % 1000 * 1000000), ZoneOffset.UTC);

System.out.println("now = " + now);
System.out.println("nowInMillis = " + nowInMillis);
System.out.println("dateTime = " + dateTime);

Output
now = 2020-05-12T12:16:38.881510700
nowInMillis = 1589285798881
dateTime = 2020-05-12T12:16:38.881

If needed, specify a zone offset other than UTC, but in that case you should really be using ZonedDateTime or OffsetDateTime instead of LocalDateTime.

A: If by long you mean number of second or millisecond use this way.
LocalDateTime in Epoch seconds
val seconds = datetime.atZone(ZoneOffset.UTC).toEpochSecond())

LocalDateTime to epoch milliseconds
val milliseconds = datetime.atZone(ZoneOffset.UTC)?.toInstant()?.toEpochMilli()


text:
Q: Domain and range in two coordinates let $f(x,y) = \sqrt{(x-1)(y-1)}$; what is the domain and the range?
I wanted to know if I was doing the domain part right and needed help with the range.
For the domain I got $(x-1)(y-1)$ are good as long as they are any real number. is that right?

A: We need for $f(x, y) = \sqrt{(x - 1)(y - 1)}$ to be defined. So we must have $(x - 1)(y - 1) \geq 0$. Why?
Then recall: The domain of a function are those values on which the function is defined. So we know that $f(x, y)$ is defined for all $(x, y)$ in the plane for which $(x - 1)(y - 1)\geq 0.\;$ We can pick, say, any $\,x\,$ we want. This will then determine the values of $\,y\,$ on which the function $\;f(x, y)\,$ is defined. We can determine $\,y\,$ as follows: $$(x-1) \lt 0 \implies (y - 1) \leq 0, \;\; (x-1) = 0 \implies y\in \mathbb R,\;\;\; (x -1) \gt 0 \implies (y - 1) \geq 0$$
All points $(x, y)$ satisfying the above inequalities are points in the domain of $f(x, y)$, which will points in $\mathbb R^2$, the real plane. And it will follow that the range will necessarily be points in $\mathbb R$ (the real line) such greater than or equal to zero: the set of all non-negative reals.

A: HINT: Assuming that you are working in the real numbers, the domain of $f$ is the set of $\langle x,y\rangle\in\Bbb R^2$ such that $(x-1)(y-1)\ge 0$: those are precisely the pairs for which the square root exists in $\Bbb R$. This means, for instance, that $\langle 2,0\rangle$ is not in the domain of $f$, since $(2-1)(0-1)=-1$ is negative. Thus, to describe the domain of $f$ in a nice way you will have to solve the inequality
$$(x-1)(y-1)\ge 0\;.$$
A product of two real numbers is non-negative precisely when one of the following holds:

*

*both factors are positive;

*both factors are negative;

*at least one of the factors is zero.

Can you describe the regions in the plane where:

*

*$x-1>0$ and $y-1>0$;

*$x-1<0$ and $y-1<0$; and

*$x-1=0$ or $y-1=0$?

The range is the set of possible values of $f(x,y)$. Clearly all of these are non-negative. Suppose that $z$ is any non-negative real number; can you find values of $x$ and $y$ (in terms of $z$) such that $f(x,y)=z$? If can do so for all $z\ge 0$, you'll have shown that the range of $f$ is the set of all non-negative real numbers.

A: The square root is not defined (in the reals) if the thing under it is negative, so you need $x-1$ and $y-1$ to be of the same sign.  For any $x$ there are some $y$ that are acceptable, but the domain is a region of the plane.


text:
Q: OpenCV Error : Assertion failed while calling detectMultiScale Getting OpenCV Error : Assertion failed while calling detectMultiScale for human body detection using webcam.
Error details

Unhandled exception at 0x000007FEFD9F9E5D in BodyDetection.exe:
  Microsoft C++ exception: cv::Exception at memory location
  0x00000000001AF470.
OpenCV Error : Assertion failed (0 <= roi.x && 0<= roi.width && roi.x
  + roi.width <= m.cols && 0<= roi.y && 0<= roi.height && roi.y + roi.height <= m.roys) in cv:: Mat :: Mat, file
  C:\builds\master_PackSlave-win64-vc12-shared\opencv\modules\core\src\matrix.cpp,
  line 508

I'm using visual studio 2013 with x64

A: This was mainly because of opencv files that i have installed.
32 bit and 64 bit is a tricky one!


text:
Q: Install custom theme on google devtools I am trying to install a custom theme on google devtools.
I am following this guide
http://www.hongkiat.com/blog/chrome-devtools-theme/
I am copying and pasting the theme on custom.css but it doesn't change the devtools at all.

A: That method of styling DevTools was an accident. Never actually intended to work. The bug that allowed it was patched.
There is a theme API for extensions if you want to build one of those. It is hidden under a DevTools Experiments flag.
However, a default Dark theme is making its way down the road (already in Dev channel.) I would wager custom themes API could get removed once that has been out for a bit, but nothing is solid (or even talked about to this extent.)
tl;dr
Theming DevTools with a custom theme is a painful process and not recommended.


text:
Q: How to eliminate render-blocking JavaScript I was testing the web page loading with Google PageSpeed tool. The result says "Eliminate render-blocking JavaScript and CSS in above-the-fold content" for
<script type='text/javascript' src='http://example.com/wp-includes/js/jquery/jquery.js?ver=1.11.2'></script>
<script type='text/javascript' src='http://example.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1'></script>

The source code is:
<head>
...
...

<script>(function(){document.documentElement.className='js'})();</script>
...
...
</head>

I'm keen to add a async or defer tag. How can I achieve this?

A: From MDN about the async attribute:

It has no effect on inline scripts (i.e., scripts that don't have the src attribute).

The same is true about the defer attribute.
Basically, if you really want to get rid of the error, just move that to just before the </body> tag.


text:
Q: inconsistent string to int error and response I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1
def addition():
    x = 0
    y = 1
    total = 0

    while x < y:
        total += int(input())

        if input() == "exit":
            x += 1

    print(total)

addition()

I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors

A: Maybe this is what you are looking for:
def addition():
    total = 0

    while True:
        value = input()

        if value == "exit":
            break
        else:
            try:
                total += int(value)
            except:
                print('Please enter in a valid integer')

    print(total)

EDIT

There are two reasons why the code isn't working properly:
First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.
Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.

A: You can break the while loop, without using x and y.
def addition():
    total = 0
    while True:
        total += int(input())
        if input() == "exit":
            break

    print(total)

addition()

A: These are a few ways you can improve your code:

*

*Run the loop forever and break out of it only if the user enters "exit"

*To know when the user entered "exit" check if the input has alphabets with isalpha()
Making the above changes:
def addition():
    total = 0
    while True:
        user_input = input()
        if user_input.strip().isalpha() and user_input.strip() == 'exit':
            break
        total += int(user_input)

    print(total)

addition()

A: def safe_float(val):
    ''' always return a float '''
    try:
       return float(val)
    except ValueError:
       return 0.0

def getIntOrQuit():
    resp = input("Enter a number or (q)uit:")
    if resp == "Q":
       return None
    return safe_float(resp)

print( sum(iter(getIntOrQuit,None)) )

is another way to do what you want :P


text:
Q: Asp.net core website intermittently refusing connections I have an asp.net core 3.0 website. It has a controller that implements an HttpGet function that does some database stuff then returns a Json object (https://localhost:44356/api/runner/match).
I have a console application that uses an HttpClient to hit that url. I launch the site locally and then I launch my console app. About 50% of the time it works. The other 50% of the time I get:
HttpRequestException: No connection could be made because the target machine actively refused it.
SocketException: No connection could be made because the target machine actively refused it.

I'm trying to figure out why my console app's connection is being blocked. I don't know how to start debugging this. I tried to implement a retry on the request, but once I get the exception, I keep getting it. So I think it's something non-deterministic happening in my website, potentially related to SSL?
I'm able to hit the url in Chrome locally just fine.
How do I figure out what is blocking the connection from being made?
Is there any chance this is something IIS Express is doing?
Calling code in console app:
static async Task<List<Deck>> GetMatchData()
        {

            string baseUrl = "https://localhost:44356/api/runner/match";

            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage res = null;
                res = await client.GetAsync(baseUrl);

Controller function:
    [HttpGet("match")]
    public async Task<ActionResult> GetMatchup()
    {
        int count = db.Decks.Count();

        Random r = new Random();

        int d1 = r.Next(count) + 1; // database ids start at 1 for some reason
        int d2 = r.Next(count - 1) + 1;

        if (d1 == d2)
            d2++;

        List<Deck> result = new List<Deck>();

        result.Add(await db.Decks.FindAsync(d1));
        result.Add(await db.Decks.FindAsync(d2));

        if (result[0] == null || result[1] == null)
        {
            return BadRequest();
        }

        return Ok(result);
    }

A: try
HttpClient httpClient = new HttpClient();

//specify to use TLS 1.2 as default connection
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

string baseUrl = "https://localhost:44356/api/runner/match";

httpClient.BaseAddress = new Uri(baseUrl );
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var getResult = await httpClient.GetAsync(baseUrl);


text:
Q: Hybris with Angular frontend In hybris projects that use angular in the frontend, we are create angular components and add a proxy like this one to do the mapping and call the service:
{
"/hybris/*": {
   "target": "<sap-nw-gateway-host>:<sap-nw-gateway-port>",
   "secure": false,
   "logLevel" : "info"
}
}

My question is:
How do we manage these components on the hybris side? On the cms cockpit, for instance.
Thanks in advance,
Jookje

A: We use the 'Spartacus' Framework in our project to communicate with Hybris BE. (I add this as a comment). Without going to deep in detail, it is about creating FlexComponents in Hybris CMS BE. Here is an example:
INSERT_UPDATE CMSFlexComponent; $contentCV[unique = true]; uid[unique = true]; name                ; flexType            ; &componentRef
                          ;                          ; SiteLogoComponent ; Site LogoComponent ; xxxLogoComponent ; SiteLogoComponent