text:
Q: clients.openWindow() "Not allowed to open a window." on a serviceWorker Google Chrome I'm testing under Chrome Version 42.0.2311.152m and I want to implement to open a window on a notificationclick like in this example: (source: https://developer.mozilla.org/en-US/docs/Web/API/WindowClient
)
self.addEventListener('notificationclick', function(event) {
  console.log('On notification click: ', event.notification.tag);
  event.notification.close();

  // This looks to see if the current is already open and
  // focuses if it is
  event.waitUntil(clients.matchAll({
    type: "window"
  }).then(function(clientList) {
    for (var i = 0; i < clientList.length; i++) {
      var client = clientList[i];
      if (client.url == '/' && 'focus' in client)
        return client.focus();
    }
    if (clients.openWindow)
      return clients.openWindow('/');
  }));
});

My filestructure is like:
https://myurl.no-ip.org/app/index.html
https://myurl.no-ip.org/app/manifest.json
https://myurl.no-ip.org/app/service-worker.js
I have the issue that I always get an

InvalidAccessError

when calling clients.openWindow('/') or clients.openWindow('https://myurl.no-ip.org/app/index.html') in the service-worker.js, I receive the error:
{code: 15,
message: "Not allowed to open a window.",
name: "InvalidAccessError"}

The "return client.focus()" line is never reached because the client.url is never just '/'.
Looking at
clients.matchAll({type: "window"})
.then(function (clientList) {
console.log(clientList[0])});

I see my current WindowClient:
{focused: false,
frameType: "top-level",
url: "https://myurl.no-ip.org/app/index.html",
visibilityState: "hidden" }

The properties 'focused' and 'visibilityState' are correct and change correctly.
By doing a manual focus call
clients.matchAll({type: "window"})
    .then(function (clientList) {
    clientList[0].focus()});

I receive the error:
{code: 15,
message: "Not allowed to focus a window.",
name: "InvalidAccessError"}

I think the problem is that url is not just '/'. Do you have any ideas for that?
Thank you very much!
Best regards
Andi

A: Your code works fine for me, so I'll explain the requirements for using openWindow / focus, and how you can avoid the "Not allowed to [open|focus] a window" error message.
clients.openWindow() and windowClient.focus() are only allowed after clicking the notification (in Chrome 47 at least), and at most one of these methods can be called, for the duration of the click handler. This behavior was specified in https://github.com/slightlyoff/ServiceWorker/issues/602.
If your openWindow / focus call is rejected with error message

"Not allowed to open a window." for openWindow
  "Not allowed to focus a window." for focus

then you didn't satisfy the requirements of openWindow / focus. For example (all points also apply to focus, not just openWindow).

*

*openWindow was called while the notification wasn't clicked.

*openWindow was called after the notificationclick handler returned, and you did not call event.waitUntil with a promise.

*openWindow was called after the promise passed to event.waitUntil was resolved.

*The promise was not resolved, but it took "too long" (10 seconds in Chrome), so the temporary permission to call openWindow expired.

It is really necessary that openWindow / focus is called at most once, and before the notificationclick handler finishes.
As I said before, the code in the question works, so I'll show another annotated example.
// serviceworker.js
self.addEventListener('notificationclick', function(event) {
    // Close notification.
    event.notification.close();

    // Example: Open window after 3 seconds.
    // (doing so is a terrible user experience by the way, because
    //  the user is left wondering what happens for 3 seconds.)
    var promise = new Promise(function(resolve) {
        setTimeout(resolve, 3000);
    }).then(function() {
        // return the promise returned by openWindow, just in case.
        // Opening any origin only works in Chrome 43+.
        return clients.openWindow('https://example.com');
    });

    // Now wait for the promise to keep the permission alive.
    event.waitUntil(promise);
});

index.html
<button id="show-notification-btn">Show notification</button>
<script>
navigator.serviceWorker.register('serviceworker.js');
document.getElementById('show-notification-btn').onclick = function() {
    Notification.requestPermission(function(result) {
        // result = 'allowed' / 'denied' / 'default'
        if (result !== 'denied') {
            navigator.serviceWorker.ready.then(function(registration) {
                // Show notification. If the user clicks on this
                // notification, then "notificationclick" is fired.
                registration.showNotification('Test');
            });
        }
    });
}
</script>

PS. Service workers are still in development, so it's worth mentioning that I've verified that the above remarks are correct in Chrome 49, and that the example works in Chrome 43+ (and opening / instead of https://example.com also works in Chrome 42).

A: This worked for me
You should define Promise that will fire when your operation is finished.
Example bellow shows how to return chained Promise
First Promise returns list of windows. If it's not empty we are focusing one and returning Promise.resolve() - which is resolve immediately.
If no windows found we are returning next chained Promise - first on opens new window second tries to focus it.
addEventListener('notificationclick', (event) => {
    console.log('---- notification clicked ----')
    console.log(event)

    //using notification data to constract specific path
    const data = event.notification.data
    console.log(data)
    let url  = 'https://exmaple.com'
    if(data){
        url += data['business'] ?
            `/business/messages/${data['respondent']}` :
            `/store/${data['respondent']}/questions`
    }

    console.log('new window url: ' + url)
    event.notification.close()
    //event should wait until we done
    event.waitUntil(
        //do we have some windows of our app?
        self.clients.matchAll({includeUncontrolled: true, type: 'window'})
            .then(list=>{
                console.log('total clients: '+list.length)
                if(list.length === 0){
                    //no windows of our app. We will open new one
                    console.log('no clients found')
                    return self.clients.openWindow(url)
                        .then((windowClient) => {
                            //we should focus new window and return Promise to terminate our event
                            return windowClient ? windowClient.focus() : Promise.resolve()
                        })
                }
                const client = list[0]
                console.log(client)
                //we have a window of our app. Let's focus it and return Promise
                client.focus()
                console.log('--window focused---')
                return Promise.resolve()
            }))

})


text:
Q: React-Native: Panresponder inside of a scrollview on Android Essentially my issue is accurately presented and answered in this blog post from Oct 2015:
http://browniefed.com/blog/react-native-pan-responder-inside-of-a-scrollview/
Since the time of writing, scrollEnabled has been implemented in Android, however it does not seem to be a solution that works in my use case. I have a ScrollView that contains elements which utilize a panresponder that relies on scrollEnabled to toggle the ScrollView's, well, scrolling feature.
My code works perfectly on iOS as described in the above blog post, but on Android the ScrollView does not take responding away from the children when scrollEnabled is set to true.
Struggling to find a workaround. Does anyone know how to properly do this? Or does the implementation of scrollEnabled on Android not support this panresponder handoff?

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does QWebEngine.loadFinished.connect() do? from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *

app = QApplication([])

view = QWebEngineView()
view.show()

url = 'http://gama-gama.ru/search/?searchField=titan'
view.load(QUrl(url))

#what does this function call do?
view.loadFinished.connect(lambda x: view.grab().save('img.jpg'))

app.exec()

What does the loadFinished function do? I know that it is a "signal" but calling view.loadFinished() says TypeError: native Qt signal is not callable.
Can I use view.loadFinished.connect(is_finished_function) to prevent the page from thinking its loaded until a certain bit of text is present?

A: Loadfinished is a QSignal.
QSignal is a class that has implemented the following methods: connect(), disconnect() and emit(), this can only be an attribute of a class that inherits from QObject.

void QWebView::loadFinished(bool ok)
This signal is emitted when a load of the page is finished. ok will
  indicate whether the load was successful or any error occurred.

In your case I think that you are using it to let you know when I completely load the page (with or without errors), at that moment you call the function:
 lambda x: view.grab().save('img.jpg')


text:
Q: Make Twilio wait on hold for me and then call me when someone picks up Does anyone know if the Twilio api allows for the following use case? I can't find a good example in any of the documentation.

*

*I call a number through Twilio where I expect to be placed on hold

*Twilio recognizes that I am on hold and waits until someone picks up

*When a human picks up, Twilio calls me and connects me to the call.

Essentially, I don't want to wait on hold!
PS: I found this but I don't think it's what I need. Anyone agree/disagree? https://www.twilio.com/docs/voice/answering-machine-detection

A: The challenge with this is the definition of "hold". Basically, you have an established call and you are waiting for a human to connect (while you wait in queue).
You need some logic to listen to the media portion of this existing call to identify utterances that sound similar to when an agent connects to a customer (vs. the on hold music and ads). However, the issue is the agent will probably say hello a few times and if you don't answer they will hang-up.
You could play back, please hold while I connect you to Nick but the agent may find that strange and may hang-up.
You could ask the agent to press any key (DTMF) to connect you to them but again, the agent may find that strange and hang-up (they expect the customer to be there when they get connected).
Anyway, for the stream processing, you would need to use something like Twilio Media Streams to fork the media to some processing logic for the voice stream and if that logic identifies patterns in the voice stream that appears to be the agent speaking, it would need to tell Twilio to call you back to connect you to that agent. The actual processing of the voice stream isn't something Twilio offers, you would need to use a service from a third party and at what expense, given it sounds like really long hold times.
So ultimately, not sure how realistic this would be. Maybe the most cost effective would be to have the agent press a key to reach you one they are connected to you.
Really, the contact center needs to have a callback option when an agent is available, which would do away with all this - that works really well.
Media Streams
How to transcribe live phone calls using Twilio Media Streams


text:
Q: Check Array length - giv me a [0] in array that's how I'll get some data via get url, it appears on the page. But when I eg select two or just one.
When I get elected them I need / set as the me this:

Array[0]

Angularjs:
var url = "/JsonClass/ColorAddToUppers";
$http.get(url).success(function (response) {
    $scope.ColorAddUppers = response;
});

//Overdel
$scope.NextLvlThree = function () {
    //Check Color Values

    $scope.selectedTextValuesByWatch = [];

    $scope.$watchCollection('ColorAddUppers|filter:{selected:true}', function (nv, ov) {
        $scope.selectedTextValuesByWatch = nv.filter(function (value) {
            return value.selected;
        }).map(function (value) {
            return value.Text;
        });
    }, true);

    $scope.getSelectedTextValues = function () {
        return $scope.ColorAddUppers.filter(function (value) {
            return value.selected;
        }).map(function (value) {
            return value.Text;
        });
    }

    console.log($scope.selectedTextValuesByWatch);

    if ($scope.selectedTextValuesByWatch.length > 0)
    {
        alert('Succes!');
    }
    else
    {
        alert('Given array is empty!');
    }

}

Error:
Every time I eg just choose one so give it to me this one error

Given array is empty!

What I would want it to do it is such as to tell me how many you just chose for the individual areas.


text:
Q: Recover file deleted using git mergetool I had git merge conflicts after deleting some files (on OSX) and ran:
git mergetool

After running through most of the conflicts, I accidentally deleted a local file I meant to keep:
Deleted merge conflict for 'app/xxxapp/xxxapp/AppDelegate.swift':
  {local}: created file
  {remote}: deleted
Use (c)reated or (d)eleted file, or (a)bort? d

Is there any way to recover the file?

A: Yes: after git mergetool finishes (or in another window), run:
git checkout --ours app/xxxapp/xxxapp/AppDelegate.swift
git add app/xxxapp/xxxapp/AppDelegate.swift

The first command extracts the HEAD version of the file into the work-tree, and the second tells Git that this is the correct resolution (vs what you already told Git through git mergetool: that the correct resolution was to discard the file).
You can also or instead use:
git checkout HEAD app/xxxapp/xxxapp/AppDelegate.swift

The latter has the advantage of marking the item resolved all in one command.


text:
Q: How to align principal axes of 3D density map in numpy with Cartesian axes? I have an n x n x n numpy array that contains density values on a cubic grid. I'm trying to align the principal axes of inertia of the density map with the cartesian x,y,z axes of the grid. I have the following so far:
import numpy as np
from scipy import ndimage

def center_rho(rho):
    """Move density map so its center of mass aligns with the center of the grid"""
    rhocom = np.array(ndimage.measurements.center_of_mass(rho))
    gridcenter = np.array(rho.shape)/2.
    shift = gridcenter-rhocom
    rho = ndimage.interpolation.shift(rho,shift,order=1,mode='wrap')
    return rho

def inertia_tensor(rho,side):
    """Calculate the moment of inertia tensor for the given density map."""
    halfside = side/2.
    n = rho.shape[0]
    x_ = np.linspace(-halfside,halfside,n)
    x,y,z = np.meshgrid(x_,x_,x_,indexing='ij')
    Ixx = np.sum(rho*(y**2 + z**2))
    Iyy = np.sum(rho*(x**2 + z**2))
    Izz = np.sum(rho*(x**2 + y**2))
    Ixy = -np.sum(rho*x*y)
    Iyz = -np.sum(rho*y*z)
    Ixz = -np.sum(rho*x*z)
    I = np.array([[Ixx, Ixy, Ixz],
                  [Ixy, Iyy, Iyz],
                  [Ixz, Iyz, Izz]])
    return I

def principal_axes(I):
    """Calculate the principal inertia axes and order them in ascending order."""
    w,v = np.linalg.eigh(I)
    return w,v

#number of grid points along side
n = 10
#note n <= 3 produces unit eigenvectors, not sure why
#in practice, n typically between 10 and 50
np.random.seed(1)
rho = np.random.random(size=(n,n,n))
side = 1. #physical width of box, set to 1.0 for simplicity

rho = center_rho(rho)
I = inertia_tensor(rho,side)
PAw, PAv = principal_axes(I)

#print magnitude and direction of principal axes
print "Eigenvalues/eigenvectors before rotation:"
for i in range(3):
    print PAw[i], PAv[:,i]

#sanity check that I = R * D * R.T
#where R is the rotation matrix and D is the diagonalized matrix of eigenvalues
D = np.eye(3)*PAw
print np.allclose(np.dot(PAv,np.dot(D,PAv.T)),I)

#rotate rho to align principal axes with cartesian axes
newrho = ndimage.interpolation.affine_transform(rho,PAv.T,order=1,mode='wrap')

#recalculate principal axes
newI = inertia_tensor(newrho,side)
newPAw, newPAv = principal_axes(newI)

#print magnitude and direction of new principal axes
print "Eigenvalues/eigenvectors before rotation:"
for i in range(3):
    print newPAw[i], newPAv[:,i]

Here I'm assuming that the eigenvectors of the inertia tensor define the rotation matrix (which based on this question and Google results such as this webpage seems correct?) However this doesn't give me the correct result.
I expect the printed matrix to be:
[1 0 0]
[0 1 0]
[0 0 1]

(which could be wrong) but don't even get unit vectors to start with. What I get is:
Eigenvalues/eigenvectors before rotation:
102.405523732 [-0.05954221 -0.8616362   0.5040216 ]
103.177395578 [-0.30020273  0.49699978  0.81416801]
104.175688943 [-0.95201526 -0.10283129 -0.288258  ]
True
Eigenvalues/eigenvectors after rotation:
104.414931478 [ 0.38786    -0.90425086  0.17859172]
104.731536038 [-0.74968553 -0.19676735  0.63186566]
106.151322662 [-0.53622405 -0.37896304 -0.75422197]

I'm not sure if the problem is my code or my assumptions about rotating principal axes, but any help would be appreciated.

A: Here is the link to the code I developed to do such alignment.
Given a set of scatter points with coordinates (x,y,z), the objective is to match the eigenvector associated to the minimum eigenvalue with the X-axis of a 3D cartesian axis and the eigenvector associated to the median eigenvalue with the Y axis from the same 3D cartesian axis.
For this purpose, I followed the following steps:

*

*Translate the set of points with centroid in (xmn, ymn, zmn) to a new set of points with centroid in (0,0,0) only by doing: (x-xmn, y-ymn, z-zmn).

*Calculate the angle THETA (rotation around z) between the xy-projection of the eigenvector associated to the minimum eigenvalue (min_eigen) and the  x-axis in a cartesian axis. After obtention of the resulting tetha, rotate the min_eigen the given theta so that it is contained in the xy-plane. Let's call this resulting vector: rotz

*Calculate the angle PHI between rotz and x-axis in order to perform a rotation around the y-axis. Once the phi is obtained, a rotation is applied to rotz aound the  y axis. With this last rotation, the eigenvector associated to the medium eigenvector (medium_eigen) is then in the yz proyection of the cartesian axis, so we will just need to find the angle between medium_eigen and the y-axis of the cartesian axis.

*Calculate the angle ALPHA between the medium_eigen and y-axis. Apply the rotation around the x-axis aaaand: IT'S DONE!

NOTE: After applying steps 1,2,3 to your set of points, you have to recalculate the 3D_SVD (3D_single value decomposition) and from the resulting set of eigenvectors, then implement the 4th step with the new medium_eigen.

I really hope this helps.
The rotations are implemented by means of the rotation matrix defined here: Rotating a Vector in 3D Space


text:
Q: iText PDFSweep RegexBasedCleanupStrategy not work in some case I'm trying to use iText PDFSweep RegexBasedCleanupStrategy to redact some words from pdf,  however I only want to redact the word but not appear in other word, eg.
I want to redact "al" as single word, but I don't want to redact the "al" in "mineral".
So I add the word boundary("\b") in the Regex as parameter to RegexBasedCleanupStrategy,
  new RegexBasedCleanupStrategy("\\bal\\b")

however the pdfAutoSweep.cleanUp not work if the word is at the end of line.

A: In short
The cause of this issue is that the routine that flattens the extracted text chunks into a single String for applying the regular expression does not insert any indicator for a line break. Thus, in that String the last letter from one line is immediately followed by the first letter of the next which hides the word boundary. One can fix the behavior by adding an appropriate character to the String in case of a line break.
The problematic code
The routine that flattens the extracted text chunks into a single String is CharacterRenderInfo.mapString(List<CharacterRenderInfo>) in the package com.itextpdf.kernel.pdf.canvas.parser.listener. In case of a merely horizontal gap this routine inserts a space character but in case of a vertical offset, i.e. a line break, it adds nothing extra to the StringBuilder in which the String representation is generated:
if (chunk.sameLine(lastChunk)) {
    // we only insert a blank space if the trailing character of the previous string wasn't a space, and the leading character of the current string isn't a space
    if (chunk.getLocation().isAtWordBoundary(lastChunk.getLocation()) && !chunk.getText().startsWith(" ") && !chunk.getText().endsWith(" ")) {
        sb.append(' ');
    }
    indexMap.put(sb.length(), i);
    sb.append(chunk.getText());
} else {
    indexMap.put(sb.length(), i);
    sb.append(chunk.getText());
}

A possible fix
One can extend the code above to insert a newline character in case of a line break:
if (chunk.sameLine(lastChunk)) {
    // we only insert a blank space if the trailing character of the previous string wasn't a space, and the leading character of the current string isn't a space
    if (chunk.getLocation().isAtWordBoundary(lastChunk.getLocation()) && !chunk.getText().startsWith(" ") && !chunk.getText().endsWith(" ")) {
        sb.append(' ');
    }
    indexMap.put(sb.length(), i);
    sb.append(chunk.getText());
} else {
    sb.append('\n');
    indexMap.put(sb.length(), i);
    sb.append(chunk.getText());
}

This CharacterRenderInfo.mapString method is only called from the RegexBasedLocationExtractionStrategy method getResultantLocations() (package com.itextpdf.kernel.pdf.canvas.parser.listener), and only for the task mentioned, i.e. applying the regular expression in question. Thus, enabling it to properly allow recognition of word boundaries should not break anything but indeed should be considered a fix.
One merely might consider adding a different character for a line break, e.g. a plain space ' ' if one does not want to treat vertical gaps any different than horizontal ones. For a general fix one might, therefore, consider making this character a settable property of the strategy.
Versions
I tested with iText 7.1.4-SNAPSHOT and PDFSweep 2.0.3-SNAPSHOT.


text:
Q: Is the intersection of two non-open/non-measurable sets non-open/non-measurable? Very simple question. If I have two sets A and B that are both non-open in some topological space, is their intersection necessarily non-open?
And similarly, is the intersection of two non-measurable sets non-measurable?
I think the answer is that it could go either way. But I can't find any good discussion of this on the internet, and I am having trouble thinking of counterexamples...

A: In both cases, make the intersection empty, which is both open and measurable.
For other examples, $$(1,2]\cap [0,2)=(1,2). $$ And, take disjoint  non-measurable sets $E_1,E_2$ and a disjoint (to both) measurable set $D $. Then $$A=E_1\cup D,\ \ \ \ B=E_2\cup D $$ are non-measurable and $$A\cap B=D $$ is measurable.

A: Onsider $A=(0,1)\cup[2,3]$ and $B=(0,1)\cup[4,5]$. They are both not open but their intersection surely is.

A: No. Take $[-1,1)$ and $(0,2]$ They are both non-open in $\mathbb R$ with respect to the usual topology, but their intersection is $(0,1)$, which is open.
And of course, for any two disjoint non-measurable sets, their intersection is empty and therefore measurable.

A: In the same style as the counterexample AJ gave for non-openness, you can construct a counterexample for measurability. Let $C$ be a non-measurable subset of $[2,3]$ and $D$ be a non-measurable subset of $[4,5]$, then $A=]0,1[\cup C$ and $B=]0,1[\cup D$ are non-measurable with a clearly measurable intersection.

A: For a large swathe of counterexamples, let $U \subset \mathbb{R}^n$ be an open subset, and let $x \ne y \in \mathbb{R}^n-U$ be two points. The subsets $U \cup \{x\}$ and $U \cup \{y\}$ are not open, and their intersection $U$ is open. A similar construction will work in many topological spaces.

A: Answers of the both question is NO.

*

*Take two disjoint non-open sets. Then their intersection is empty set which is open.

*Similarly for non measurable sets, take two disjoint non measurable sets (infact we can choose a non measurable set and it's complement).Then their intersection is empty set which is measurable.
Non trivial examples:

*

*$A=[0, 2) $ and $B=(1, 2]$ . Then both are non-open in the euclidean space but $A\cap B=(1, 2) $ is open.

*Let $\mathcal{B}\subset \Bbb{R}$ is a Bernstein set.Then $\mathcal{B}$ is non measurable( see here).
Let $A=\mathcal{B}\cup [0, 1]$ and $B=\mathcal{B}^c \cap [0, 1]$
Then $A\cap B=[0, 1]$ is measurable.


text:
Q: USB wifi adapter for kali linux 2017.1 in raspberry pi 3 I'm thinking of buying-
1) Panda PAU05-https://www.amazon.com/dp/B00EQT0YK2/?tag=whtnb-20
2)The Detroit DIY Electronics Wifi Antenna For Raspberry Pi-
https://www.amazon.com/gp/product/B00H95C0A2/?tag=whtnb-20
I would like to know if they are compatible with updated kali linux.

A: The panda pau05 is a nano 2.4Ghz usb realtek adapter, the 2nd a 2.4GHz  ralink too.
Both are compatible with the Linux kernel, and conversely with Kali Linux. However:
I do not recommend buying neither a nano wifi adapter the range is too low, especially for using in AP mode (the photo of that one does not show an external antena connector).
nor do I recommend buying a wifi adapter  with a realtek chipset. They are too buggy, and give loads of problems. see Wi-Fi problems using ASUS USB-N13 adapter
If I am not mistaken, the Detroit DIY Electronics Wifi Antenna also uses a very old ralink chipset.
As for the frequency, you are much better with an adapter that supports dual frequency, either for ethical hacking, AP mode or escaping the terrible noise in residential areas.
As for the external antennas, 2dB gain is nothing special.
For that kind of money I would buy a ralink dual frequency chipset based adapter in aliexpress that is also supported by linux and works so much better. I actually have two and they work quite well. https://www.aliexpress.com/item/YOC-300Mbps-Dual-Band-2-4Ghz-5Ghz-Wireless-N-USB-WiFi-Adapter-802-11-a-b/32773231343.html
Be aware that the recommended chipset for wifi ethical hacking is the atheros chipset, but it will cost more. The linux compatile ones are capable of both doing monitor mode AND packet injection.
So I recommend a dual frequency ralink for price or atheros as the expensive alternative.
I would not buy neither of the adapters you mention.


text:
Q: Store print_r result into a variable as a string or text If I use print_r or var_dump it displays the result on the screen, but I want this data to be stored in a variable so that I can write it to a file.
How do I do this?

A:    $var = print_r($what, true);

You must add true into print_r.

A: ob_start();
var_dump($someVar);
$result = ob_get_clean();

it works.

A: What you do while you print or dump? Basically you send your data (result or anything) to Show it on screen. Keep your mind clear that its not saved, it is just displayed,
To save the data , so a simple thing, just declare a variable and assign the data to it..
for example you are printing some array like this..
print_r(myArray);

to save this, you just have to add an option , set Return to TRUE and assign it to a variable
$myVariable=print_r(myArray, TRUE);

if you need some more information, Follow this
hoping this will help you understanding the concept


text:
Q: Intellij Error: Internal caches are corrupted or have outdated format I am getting an error intermittently when I build my Java project in Intellij.
Internal caches are corrupted or have outdated format, forcing project rebuild: java.io.FileNotFoundException: C:\target\classes\ehcache.xml (Access is denied)
I have run File->Invalidate caches. I have restarted Intellij and killed all Java processes. I eventually get it to build again but not sure what thing I try does the trick.
When I try to access the 'Target' folder, it says Access Denied.
Anyone seen this before?

A: As mentioned in my comment, I received the same message, but without any access right issues involved whatsoever.
It seemed to be some kind of confusion on IDEA's end. I was able to fix this by deleting the system directory in C:\Users\%USERNAME%\.IdeaIC13 (the path obviously depends on the IntelliJ IDEA version).
This stores all caches and indices among other things. I have to confess that I can't tell why exactly this helps, but it seems to be a rougher way to "invalidate caches" and it works. Your project history is not deleted this way, so you can practically continue working - just that all files have to be scanned again and all indices have to be rebuilt.
In any event, this was not an access rights problem at all.

A: For me, I just had to clean all modules (and ensure they didn't require sudo permission), and rebuild.
The File->Invalidate Caches/Restart... did not work for me.

A: If you can't access the folder have to either change the rights for the entire hierarchy starting from your project root folder as described here, or move your project to some other directory that you are allowed to access

A: Tried all the above, but none worked for me.  Finally running Intellij 14 in admin mode did the trick.

A: I had this exact problem, I tried all of the above solutions but none of them worked for me.
The I tried the oldest one in the book (ie rebooting my laptop) and that fixed everything!

A: Similar to pdinklag's answer, I had to delete my user-level Android Studio caches to get rid of this error. However, Android Studio caches are stored in ~/.android/.
I shut down Android Studio, then ran:
cd
rm .android/cache build-cache build-cache.lock

Then restarted Android Studio, and things worked.

A: I had the same problem in Intellij 17 version for Mac.
Rebuilding the project, changing the directory of the project, cleaning the module, and running IntelliJ 17 with admin mode did not work.
Updating Intellij to 2019 version solved the error. It seems the application was not able to get the admin permissions.


text:
Q: U-Boot - Embedded Linux - Terminal Connection I have an embedded linux board with a max3222e RS232 converter. The pins are availlable on soldering pins. I think I've figured out the ground pin, the TX pin and the RX pin. When I connect my pc with a terminal program, I can see the boot logs of the embedde linux system. Also I can stop u-boot with pressing any key. But when I try to use some boot arguments then the characters of the pressed key are not the same like on the pc. For example:
Enter->y
a -> 0
s -> F
Can anybody tell me what's wrong. The serial settings are 115200 Baut 8N1 and no Flowcontrol.
Thanks a lot
Karl-Heinz

A: What terminal you use ? I use minicom. I have set
`NO PROGRAMING FLOW CONTROL,'

`YES DEVICE FLOW CONTROL`.

And u-boot char is send good.
You try other terminal for example putty for windows ?


text:
Q: nuget command to IncludeReferencedProjects in azure devops In Azure devops I want to issue a nuget pack command that passes the option IncludeReferencedProjects.  My repo is in TFVC so I do not believe I can use azure-pipelines.yml.  I believe I must do this through the visual designer.  I don't see an option to pass additional arguments to the nuget with the pack command type.  This makes me think I have to use the custom command type for nuget.  When I'm using the custom command type, I can specify -IncludeReferencedProjects but I do not seem to be able to specify **\*.csproj as the items to pack.  If I do this the command fails with:
[command]C:\hostedtoolcache\windows\NuGet\4.1.0\x64\nuget.exe pack **\*.csproj -IncludeReferencedProjects -Symbols -Verbosity Detailed -NonInteractive
System.IO.IOException: The filename, directory name, or volume label syntax is incorrect.

How can I pack all csproj output with the IncludeReferencedProjects flag using the visual designer?  Here's a picture of what I have in designer:

A:
How can I pack all csproj output with the IncludeReferencedProjects flag using the visual designer?

I am afraid you could not pack all csproj output with the IncludeReferencedProjects flag.
That because pack command (NuGet CLI) does not support wildcard.
When you use nuget pack command line with wildcard, you will always get the error Unknown command: '**\*.csproj'. (This error also exists locally.)
To resolve this issue, we could add multiple nuget pack tasks to pack those projects.
Hope this helps.

A: For me, passing IncludeReferencedProjects=true worked.
- task: DotNetCoreCLI@2
  displayName: Pack Core.Shared
  inputs:
    command: 'pack'
    packagesToPack: '**/*.csproj'
    versioningScheme: 'byPrereleaseNumber'
    majorVersion: '1'
    minorVersion: '0'
    patchVersion: '0'
    buildProperties: 'IncludeReferencedProjects=true'


text:
Q: titanium iOS application sometimes show alert "App May Slow Down Your iPhone.." I create some business application on Appcelerator Studio(sdk version:6.1.0.v20161230103702).
It run iOS simulator(iPhone 7(OS 10.2)),
so sometimes popup "App May Slow Down Your iPhone.." alert.
I wanna prevent this alert.
would appreciate any comments or suggestions.

A: This alert is supposedly shown for apps developed for the 32 bit architecture.
read here
I wonder though how the ti sdk 6.1.0 would get you this issue.
what Xcode are using ?
Update :
Where did you get that sdk version ?
For production, use one of the GA titanium sdk versions, the latest one (as of the moment of writing this) is at 6.0.2.GA
To install Ti SDKs use this command
appc ti install sdk 6.0.2.GA

If you don't have an appcelerator indie account, you can use this node package tisdk to install new titanium sdk GA releases.

A: You might want to take a look at this SO Q&A, this other Q&A,  and this third one. There could be something there that you could adapt to Appcelerator Studio.

A: You might be using the latest SDK with the compatible XCode, but are you using any external modules which may not be 64-bit comptible. Can you remove any additional modules, and see if you are getting the error or not. If not, then you need to recompile the modules with the latest SDK or atleast a minimum of 3.5.0.GA from which the 64-bit support was provided.


text:
Q: ChipGroup ChipChanged Listener is not working I have a chip group and have bunch of chips inside that particular group. I applied setOnCheckedChangeListener
private fun prefDialog(context: Context): Dialog {
        val dialog = Dialog(context)
        dialog.setContentView(R.layout.pref_dialog)
        val chipGroup = dialog.findViewById<ChipGroup>(R.id.genre_chip_group)
        chipGroup.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.popChip -> Log.i(TAG, "onCheckedChanged: checked")
            }
        }
        return dialog
    }

but it's not being triggered. Kindly guide me how to achieve this


text:
Q: Wifi router near fusebox Can I place a WiFi router near our fusebox?
My concern is whether the fusebox will disturb the WiFi.

A: Most likely you will have no issues aside from the metal fuse box attenuating the wifi signal in one direction. Fuse boxes are typically on an outside wall, though, so this shouldn't cause a problem. No harm can come from trying it out.


text:
Q: Returning Multiple Objects with Creation within a Single Statement This
Range("Table1[#All]").Copy Destination:=Workbooks(5).ActiveSheet.Range("A1")

works as I understand to expect but this will not and gives
Run-time-error '1004':
Application-defined or object-defined error
Range("Table1[#All]").Copy Destination:=Workbooks.Add.ActiveSheet.Range("A1")

Tried understanding help here but just not getting there
What are the rules governing usage of brackets in VBA function calls?

A: Alright so imagining it last night while driving to eat I wondered if Workbook.Add() setting the new workbook as active might be part of the problem by changing the ActiveWorkbook before the implicit Range("Table1[#All]") is evaluated.
So
Workbooks("*Initial*").ActiveSheet.Range("Table1[#All]").Copy Destination:=Workbooks.Add().ActiveSheet.Range("A1")
does work.
I learned or reinforced 3 main things:

*

*Parentheses are needed for .Add even without using arguments to return a Workbook from the Workbooks collection just like would be required using an implicit call to the default member of Workbooks, Workbooks.Item() with an argument.

*Order of how operations are executed within a single instruction

*Watch out for Implicit references and secondary operations

Thanks to everyone that responded.  Before I posted this question I expected the 1st response to be "Why?", and was not disappointed.  I almost didn't even post.
Yes before I posted I knew I could just do Workbooks.Add 1st but then I would have just used the clipboard to copy the table 1st which would have been maybe slightly less desirable I almost did just that and would have kept trucking.  More importantly I would not have learned what I have.
I'm always open to any advice.  Many here are tried and true on the topic of Excel VBA whereas I maybe write a little macro once or twice a year.  I didn't persist for stubbornness of doing something my way but to understand from my point of view.


text:
Q: Children of ViewPager When I'm trying to get child's X of ViewPager I always get strange numbers, not correct ones.
@Override
        public void onPageScrolled(int position, float positionOffset,
                int positionOffsetPixels) {
            int realPosition = position;

            for (int i =0 ; i < getChildCount(); i++) {
                Log.d("TAG", "X: " + getChildAt(i).getX());
            }

I always get
D/TAG﹕ X: 41.0
D/TAG﹕ X: 1000.0
D/TAG﹕ X: 1960.0
D/TAG﹕ X: 2920.0
D/TAG﹕ X: 3880.0

How to get children which are currently visible on screen and how to get their real X's?
I want to set Alpha to child views depending on their position.

A: Try ViewPager.PageTransformer for setting alpha
http://developer.android.com/training/animation/screen-slide.html
Example:
viewPager.setPageTransformer(true, new AlphaPageTransformer());

public class AlphaPageTransformer implements ViewPager.PageTransformer {
        private static final float MIN_SCALE = 0.75f;

        public void transformPage(View view, float position) {
            int pageWidth = view.getWidth();

            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                view.setAlpha(0);

            } else if (position <= 0) { // [-1,0]
                // Use the default slide transition when moving to the left page
                view.setAlpha(1);

            } else if (position <= 1) { // (0,1]
                // Fade the page out.
                view.setAlpha(1 - position);

            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                view.setAlpha(0);
            }
        }
    }


text:
Q: Calculating "area" of probability of density function (pdf) I have a piecewise equation of a probability of density function  like this:
$$f(x)= \begin{cases}\frac{x}{6} + k, & \text{for } 0\le x \le 3, \\ \\0, & \text{for } x < 0 \lor x > 3 \end{cases}$$
I have to find k. To solve this I do
$$\frac{width * height}{2} = 1$$
$$\frac{3*(\frac{3}{6}+k)}{2} = 1$$
$$\frac{3}{2}+3k = 2$$
$$\frac{3}{2}+3k = 2$$
$$\frac{6k}{2} = 2 - \frac{3}{2}$$
$$\frac{1}{6} = k$$
I tried in Wolfram Alpha and I get the same result.
However, by schoolbook says the right answer is $$\frac{1}{12}$$
What am I doing wrong?$$\\$$
Please keep you answers somewhat basic. I haven't learnt about integral functions yet, or anything that involves this $\int_{}$ symbol .
Also, there is no more information to this problem. The function is all my book gives me.

A: Why do you impose $\frac{width * height}{2} = 1$ ?
That's incorrect. What you know is that the area below the graph of $f(x)$ must be $1$. The formula above corresponds to the area of a triangle. But your density $f(x)$ does not form a triangle, but a trapezium, with heights $f(0)=k$ and $f(3)=k+1/2$ (sketch a graph if you don't see this)
Can you go on from here?

A: The height is the average height at the endpoints. (of the non-zero portion)
$(k + (k+\frac 36))\frac 12$
And the area the equals $3k + \frac 34 = 1$


text:
Q: Selenium can't download correct file in headless mode Even after implementing the enable_download_headless(driver, path) that was suggested in the following thread, the download of the file is incorrect. While the non headless version can always download the file of the site correctly the headless version downloads an "chargeinfo.xhtml" excerpt, which is the last extension of the link of the download page "https://www.xxxxx.de/xxx/chargeinfo.xhtml". Interestingly, when I call the suggested enable_download_headless(driver, path) in non headless mode, it downloads the "chargeinfo.xhtml" as well.
Also, taking a screenshot before clicking the download shows the same webpage layout as in non headless.
Any help is highly appreciated.
Here is my driver setup:
def excerpt():
    ## declare driver and allow
    options = webdriver.ChromeOptions()
    ##declaring headless
    options.add_argument("--headless")
    user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36'
    options.add_argument(f'user-agent={user_agent}')
    options.add_argument('--ignore-certificate-errors')
    options.add_argument('--allow-running-insecure-content')
    options.add_argument("--window-size=1920,1080")
    driver_path = "path/to/chromedriver"
    driver = webdriver.Chrome(driver_path,options=options)

    ####cause the non headless version to also download "chargeinfo.xhtml"
    enable_download_headless(driver, "/Download/Path/")

    driver.get("https://www.xxxxx.de/xxx/chargeinfo.xhtml")
    time.sleep(10)
    driver.find_element('xpath', "//span[@class='ui-button-text ui-c' and contains(text(), 'Download')]").click()

def enable_download_headless(browser,download_dir):
    browser.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
    params = {'cmd':'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
    browser.execute("send_command", params)

A: If anyone is having a similar problem, for me the only way to get this running was switching to get the request response body. I clicked the download button with selenium and than fetched the response as follows:
    for request in driver.requests:
    if request.response:
        if request.url == "https://www.xxxxx.de/xxx/chargeinfo.xhtml":
            print(
                request.url,
                request.response.status_code,
                request.response.body
            )

            with open('out.pdf', 'wb') as f:
                f.write(request.response.body)


text:
Q: How to link against GLFW on Windows I am looking to learn how to use OpenGL with C++, and I am following the tutorial at open.gl. I am at this part in the tutorial, and I am using GLFW. I tried following the instructions to build GLFW,

After you've downloaded the GLFW binaries package from the website or
compiled the library yourself, you'll find the headers in the include
folder and the libraries for your compiler in one of the lib folders.
-Add the appropriate lib folder to your library path and link with GLFW.
-Add the include folder to your include path.

I downloaded it, and moved the include folder into my MinGW include folder, but I was unsure where to find the lib folder, how to add it to my library path, or how to link it with OpenGL. This was not explained in the tutorial, and I could not find any instruction online about what this meant or how to do it. I proceeded without doing the other two steps, and when attempting to run the test code from the tutorial:
#include <GLFW/glfw3.h>
#include <thread>

int main()
{
    glfwInit();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    glfwTerminate();
}

I received this error:
In file included from c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\thread:35:0,
                 from D:\Files\Documents\Programming\opengl_tut.cpp:2:
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.

I added -std=c++11 to my compiler flags, and I received this error:
D:\Files\Documents\Programming\opengl_tut.cpp: In function 'int main()':
D:\Files\Documents\Programming\opengl_tut.cpp:7:10: error: 'std::this_thread' has not been declared
     std::this_thread::sleep_for(std::chrono::seconds(1));

Thinking the problem might just be with std::this_thread, I removed that line from my program, and ran it to see if initializing and terminating GLFW would return any errors. I got this:
C:\Users\Brett\AppData\Local\Temp\ccCJrDGj.o:opengl_tut.cpp:(.text+0xc): undefined reference to `glfwInit'
C:\Users\Brett\AppData\Local\Temp\ccCJrDGj.o:opengl_tut.cpp:(.text+0x11): undefined reference to `glfwTerminate'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: C:\Users\Brett\AppData\Local\Temp\ccCJrDGj.o: bad reloc address 0x20 in section `.eh_frame'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link failed: Invalid operation
collect2.exe: error: ld returned 1 exit status

I think this may be because of the fact that I skipped earlier parts of the tutorials.
TL;DR

*

*Tried to follow tutorial to use OpenGL

*Couldn't figure out how to link GLFW

*Couldn't find lib folder

*Got errors relating to std::this_thread

*Got error relating to GLFW

EDIT
I found some info on the GLFW site saying to use Cmake. I downloaded it and tried using it to build from the downloaded files. It made a new folder, but I'm not sure what to do with it.

A: *

*First, it's easy to do such config in Visual Studio, just NuGet, and search glfw, install, Visual Studi/NuGet will handle everything like set proper Include path, Additional Library path, add additional library files

*Second, it looks like your link issue, try to add these to your gcc cmd line

*

*g++ -o example.exe example.o -L. -lexample_dll

*Third, check the glfw library you downloaded, use MinGW-w64 lib files. Also remember distinguish the static and dynamic libs

A: It looks like you've downloaded the source files. This will require building (using CMake). You should go download the precompiled binaries. To do this, go back to glfw.org and instead of hitting the download button on the home page, go to the download tab in the top right and under "Windows pre-compiled binaries" select the 32 or 64 bit version and click download. See the attached image
Then, when you extract from the .zip folder you should find in it several folders - the include folder, as well folders with names beginning with "lib" (like lib-mingw, lib-mingw-w64, lib-vc2010, lib-vc2012, etc). You only need one of them, which depends on the compiler you're using - minGW or Visual C++ (vc). Choose the appropriate folder and inside you should find .lib and .dll files.
Now, whenever you compile your OpenGL program, you must tell the compiler (the linker, really) to link those files to your program's object files. You do this by using the proper compiler command line arguments. You can read about doing that in MinGW here: http://mingw.org/wiki/Specify_the_libraries_for_the_linker_to_use
For that tutorial you'll probably only need to link glfw3.lib (for MSVC) or libglfw3.a (for MinGW). If you're using GLEW, you'll probably just need glew32.lib and glew32.dll (the latter is found in the "bin" folder not the "lib" folder).
Hope that helps answer your question.


text:
Q: Setting custom font to Textview I am using custom fonts in my application
So I have used following code
public class BrandonBlackTextView extends TextView {

public BrandonBlackTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

public BrandonBlackTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public BrandonBlackTextView(Context context) {
    super(context);
    init();
}

public void init() {
    Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font/brandon_blk.ttf");
    setTypeface(tf ,1);

}

wherever I wants to use I use this textview. It works.
But problem is sometimes I don't know why but text inside textview becomes bold. I don't know why this happening. And this is very inconsistent, it doesn't happen every time.

A: Try adding this to your init:
int flags = getPaintFlags() | Paint.ANTI_ALIAS_FLAG |  Paint.SUBPIXEL_TEXT_FLAG;
setPaintFlags(flags);

Also you should cache the typeface somewhere instead of loading it again for every TextView.


text:
Q: Cleaning up the Garbage Output File I am pretty new to Python and tried to read a jpg file and write it as a simple practice. The file was not huge, only 142 KBytes but when I used the buffer chunks of 50000 Bytes to read and write it to a new.jpg file, it gave limited space error and ate up all of my remaining 4GB of space in the C:\ drive on my desktop and never released that memory. How can I see and free up the memory used by Python. Here is my code:
def main():

    buffersize = 50000
    infile = open('olives.jpg', 'rb')
    outfile = open('new.jpg', 'wb')
    buffer = infile.read(buffersize)
    while(len(buffer)):
        outfile.write(buffer)
        print('.', end = '')
        infile.read(buffersize)
    print()
    print('Done')

if __name__ == "__main__": main()

Please let me know how I can free this memory as my C:\ Drive is short in memory.
Thank you!

A: In your loop, you never change buffer. You need to assign the read result, or you just keep writing the same original buffer contents over and over, the loop never ends. Change the final line of this while loop:
while(len(buffer)):
    outfile.write(buffer)
    print('.', end = '')
    infile.read(buffersize) # <-- Not assigning result

to:
    buffer = infile.read(buffersize)

Also, for style points, change while(len(buffer)): to just while buffer:; bytes objects (like all sequences) are truthy when non-zero length, and falsy when zero-length (and Python doesn't require parens for conditional statements unless they're needed for something like grouping tests).
As for "freeing the memory" (meaning "cleaning up the garbage output file"), just delete it. At the command line, you can just visit the working directory you ran the script in and run del new.jpg, or navigate there the same way in the file browser. If you have no idea where the file is, rerunning your script after fixing the infinite loop problem will truncate the original file before writing to it (because your mode included w), which will also solve the problem.


text:
Q: Redirect to home page after form processing with Elementor Forms API (Wordpress) I have a multi step form built with Elementor in my Wordpress application. I am using the Elementor Forms API in PHP to grab data submitted by the form and create a custom post within Wordpress (5.7.1). Once the form has been successfully submitted I want to redirect to another page in the application.
I have been trying to use wp_redirect to do this but all I get is an error reported by the form (it only shows x parse error on the page). The code I am having trouble with is this part at the very end (everything else is working fine):-
   //redirect after successful form submission
    wp_redirect( home_url() );
    exit();

I have tried different values for the wp_redirect argument even hard coding a URL but I still get the same issue.
Could anyone please give me a pointer to where I am going wrong??
The code is quite large but I thought it better to include it for completeness below:-
// Create a custom post and populate custom fields from a standard Elementor form
add_action( 'elementor_pro/forms/new_record', function( $record, $handler ) {

    //make sure its our form
    $form_name = $record->get_form_settings( 'form_name' );

     if ( 'Member_Details_Form' !== $form_name ) {
        return;
    }

    // iterate all the fields and get them into an array
    $raw_fields = $record->get( 'fields' );
    $fields = [];
    foreach ( $raw_fields as $id => $field ) {
        $fields[ $id ] = $field['value'];
    }

    // assign each field to its own variable - member details
    $address = $fields['member_address'];
    $postcode = $fields ['member_post_code'];
    $contact_number = $fields ['contact_number'];
    $date_of_birth = $fields ['date_of_birth'];

    // assign each field to its own variable - emergency contact details
    $full_name = $fields ['full_name'];
    $relationship = $fields['relationship'];
    $emergency_address = $fields['address'];
    $post_code = $fields['post_code'];
    $telephone_number = $fields['telephone_number'];

    // assign each field to its own variable - courses
    $courses = $fields['courses'];

    // assign each field to its own variable - sign off box
    $consent_for_marketing = $fields['consent_for_marketing'];
    $date = $fields['date'];

    //check if a current members_details post exists - only ever want just one
        $user_id = get_current_user_id(); //the logged in user's id
        $post_type = 'member_details';
        $posts = count_user_posts( $user_id, $post_type ); //count user's posts

    //if no current members_details post exist create a new one
            if( $posts < 1 ){
                //user has no posts so we will create a new one

         global $user_ID;
         $new_post = array(
        'post_title' => $name,
        'post_status' => 'publish',
        'post_date' => date('Y-m-d H:i:s'),
        'post_author' => $user_ID,
        'post_type' => 'member_details',
        'post_category' => array(0)
        );
        $post_id = wp_insert_post($new_post);

        //change the title of the post to the current logged in user
        set_title($post_id);
            }

    //make sure we have the latest post_id
    $latest_cpt = get_posts("post_type=member_details&numberposts=1");
    $post_id = $latest_cpt[0]->ID;

   //change the title of the post to the current logged in user
    set_title($post_id);

   //populate some custom fields on the custom post from the Elementor form data

   // add member address details.
   $field_key = "member_address";// map this to an elementor field
   $value = $address;
   update_field( $field_key, $value, $post_id );

   // add member post code.
   $field_key = "member_post_code";// map this to an elementor field
   $value = $postcode;
   update_field( $field_key, $value, $post_id );

   // add member contact number
   $field_key = "contact_number";// map this to an elementor field
   $value = $contact_number;
   update_field( $field_key, $value, $post_id );

   // add member date_of_birth
   $field_key = "date_of_birth";// map this to an elementor field
   //$date_of_birth = new DateTime($date_of_birth);
   $value = $date_of_birth;
   update_field( $field_key, $value, $post_id );

   // add emergency contact name
   $field_key = "full_name";// map this to an elementor field
   $value = $full_name;
   update_field( $field_key, $value, $post_id ); // map this to an elementor field

    // Save a checkbox or select value.
    $field_key = "relationship";
    $value = array($relationship);
    update_field( $field_key, $value, $post_id );

   // add emergency contact address details.
   $field_key = "address";// map this to an elementor field
   $value = $emergency_address;
   update_field( $field_key, $value, $post_id );

   // add emergency contact  post code.
   $field_key = "post_code";// map this to an elementor field
   $value = $post_code;
   update_field( $field_key, $value, $post_id );

   // add emergency contact  contact number
   $field_key = "telephone_number";// map this to an elementor field
   $value = $telephone_number;
   update_field( $field_key, $value, $post_id );

    // add info on courses they are interested in
    $field_key = "courses";
    $value = array($courses);
    update_field( $field_key, $value, $post_id );

    // add consent for marketing
    $field_key = "consent_for_marketing";
    $value = array($consent_for_marketing);
    update_field( $field_key, $value, $post_id );

    // add signature date
    $field_key = "date";// map this to an elementor field
    $value = $date;
    update_field( $field_key, $value, $post_id );

    //since a post exists make sure the user role is set to member
    $current_user = wp_get_current_user();
    $wp_user_object = new WP_User($current_user->ID);
    $wp_user_object->add_role( 'member' );

    //redirect after successful form submission
    wp_redirect( home_url() );
    exit();

}, 10, 2 ;

A: You need to do it the Elementor way with record and handler.
Below you can find a general code to be used by anybody for an Elementor redirect:
//redirect URL to be setup
$redirect_url = '/after-form?encoding='.base64_encode($fields['email']);

//add to record the redirect URL
$redirect_to = $record->replace_setting_shortcodes( $redirect_url );

// Set redirect action to handler
$handler->add_response_data( 'redirect_url', $redirect_to );

In the example above the form is redirected with an encoding in the GET parameter.


text:
Q: magento2 add discount to quote from custom rest api I have used this example to create a custom api for updating quote by rest: https://www.thirdandgrove.com/creating-custom-rest-api-magento2
Also I have found this example to add discount to quote:
https://webkul.com/blog/set-custom-discount-fee-cart-magento-2/
How to combine this examples to add discount to magento2 quote by custom rest api?

A: I have the answer already: I have added a coupon code in Magento and did a put request to carts/{ID}/coupons/{coupon code} with empty request body to add discount to cart.


text:
Q: Minimization in single component of BSpline to extract points I smoothed some data with a BSpline $B[t] = (x[t],y[t])$. I would like to extract certain points from this spline by their x-Values, $x_0$. The easiest way I came up with was to minimize $B[t][[1]]-x_0$ for  $t \in  [0,1]$. So for finding the parameter t at which the x value is 13.46 if have the following code:
data = {{9.93114`, 379022.8`}, {11.71875`, 321705.7`}, {13.46983`,
280830.8`}, {15.625`, 243949.8`}, {18.60119`, 206915}, {21.70139`,
 179663.2`}, {24.93351`, 158942.4`}, {29.29688`,
138396.2`}, {33.48214`, 123873.8`}};

spline = BSplineFunction[data, SplineDegree -> 3];
tstfc[t_] := spline[t][[1]]

FindMinimum[Abs[tstfc[x] - 13.46] , {x, 0}]

It seems like the Spline is not getting evaluated. How can I solve this? And is there a standard way to extract points from a spline? Thanks!

A: data = {{9.93114`, 379022.8`}, {11.71875`, 321705.7`}, {13.46983`,
280830.8`}, {15.625`, 243949.8`}, {18.60119`, 206915}, {21.70139`,
179663.2`}, {24.93351`, 158942.4`}, {29.29688`, 138396.2`}, {33.48214`,
123873.8`}};

spline = BSplineFunction[data, SplineDegree -> 3];

Clear[tstfc];

You need to restrict the definition of tstfc to numeric arguments. Using the symbolic result causes your problem.
tstfc[t_?NumericQ] := spline[t][[1]]

The function being minimized clearly has a local minimum:
Plot[Abs[tstfc[x] - 13.46], {x, 0, 1}]

Plot[Abs[tstfc[x] - 13.46], {x, 0.17, .173}]

You should also constrain x.Even so, FindMinimum has some difficulty.
FindMinimum[{Abs[tstfc[x] - 13.46], 0 <= x <= 1}, {x, .2}]

FindMinimum::eit: The algorithm does not converge to the tolerance of 4.806217383937354`*^-6 in 500 iterations. The best estimated solution, with feasibility residual, KKT residual, or complementary residual of {2.00154,0.757541,1.00077}, is returned. >>
{0.000010463696439089176,
   {x -> 0.17147137220615655}}
NMinimize works better.
NMinimize[{Abs[tstfc[x] - 13.46], 0 <= x <= 1}, x]

{1.0658141036401503*^-13,
   {x -> 0.17147210562361115}}

A: If your aim is to find the parameter value t that maps to {13.46, _} in the B spline you could use:
data = {{9.93114`, 379022.8`}, {11.71875`, 321705.7`}, {13.46983`,
    280830.8`}, {15.625`, 243949.8`}, {18.60119`, 206915}, {21.70139`,
     179663.2`}, {24.93351`, 158942.4`}, {29.29688`,
    138396.2`}, {33.48214`, 123873.8`}};
bf = BSplineFunction[data, SplineDegree -> 3];
d = Table[{bf[t][[1]], t}, {t, 0, 1, 0.01}];
ifn = Interpolation[d];

Then
ans = ifn[13.46]

yields:
0.171472
and the point on spline:
bf[ans]

{13.46, 283497.}
You could adjust to desired precision.

A: A workaround is a Newton algorithm, if the spline is used with a Modulo 1 parameter, modelling a periodic spline function. The function to be minimized is then       spline[t_] := Abs[spline[t][[1]] - x0];
getPointNewton[x0_, splinein_, tstart_] :=
 Module[{d, t, dert, dt, spline},
  spline[t_] := Abs[spline[t][[1]] - x0];
  t = tstart;
  dt = 0.001;
  d = 1;
  While[d > 0.00000005,
   dert = (spline[t + dt] - spline[t - dt])/(2 dt);
   t = Mod[t - spline[t]/dert, 1];
  d = Abs[splinein[t][[1]] - x0];
   ];
  t
  ]

Edit: Works fine for this dataset, gives 0.171472 after 345 iterations, but has problems converging in more extreme data (higher derivatives/values) and close to boundaries.
The standard minimization routines in Mathematica seem to take a lot of time for convergence.
A better algorithm, which converges on the wished parameter from the left only is this one:
getPointLeft[x0_, spline_, tstart_] :=
 Module[{i, t, basestep, points}, i = 0;
  t = tstart;
 basestep = 1;
  points = {0};
  While[Abs[spline[t][[1]] - x0] > 0.000005,
  If[spline[t + (1/2)^i basestep][[1]] > x0, i++,
    t = t + (1/2)^i basestep;
    AppendTo[points, N[t]]]];
  points]

data = {{9.93114`, 379022.8`}, {11.71875`, 321705.7`}, {13.46983`,
    280830.8`}, {15.625`, 243949.8`}, {18.60119`, 206915}, {21.70139`,
     179663.2`}, {24.93351`, 158942.4`}, {29.29688`,
    138396.2`}, {33.48214`, 123873.8`}};

spline = BSplineFunction[data, SplineDegree -> 3];
points = getPointLeft[13.46, spline, 0]
Show[Plot[Abs[spline[t][[1]] - 13.46], {t, 0, 0.2}],
 Graphics[{PointSize[Large], Red,
   Point[Transpose[{points,
      Abs[spline[#][[1]] - 13.46] & /@ points}]]}]]

It halfs the stepsize as long as the next step would overshoot. This works well to find the next local minimum, which is fine for a case in which the dependent variable looked for is a monotonous function of the parameter t. Result:0.171472 after 33 iterations.

A: The documentation says in its very first sentence:

FindMinimum[f, x] searches for a local minimum in f, starting from an
  automatically selected point.

Not ANY minimum but a LOCAL minimum.
Google it with http://en.wikipedia.org/wiki/Maxima_and_minima
As already stated yesterday, your data doesn't contain LOCAL minima and/or maxima. Your data has one GLOBAL maximum and one GLOBAL minimum which, thanks Mathematica, can be found as follows:
{First@data, Last@data}

Aside from this, your "getPointNewton" simply doesn't work. If it works with you, could you provide an example?


text:
Q: detecting whether picture selected is form camera or camera roll i'm using UIImagePickerController in order the user have the choice of choosing a picture to upload either from a camera or from the camera roll. however, i want to add the option of letting pictures taken by the camera be automatically added to the camera roll as well and images taken from the camera roll don't be re-added to camera roll. i tried:

UIImageWriteToSavedPhotosAlbum(info[UIImagePickerControllerOriginalImage], nil, nil, nil);

and it's saving fine, but when i choose a picture from the camera roll it add a duplicate. so i want to stop that. is there a way to know whether the image is taken from the camera or camera roll? i tried identifying the media type but in either cases it returns public.image, so it didn't help.

A: In your imagePickerController:didFinishPickingMediaWithInfo: delegate method, check the sourceType of the picker parameter:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    // Do whatever you need

    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        // save image to camera roll
    }
}


text:
Q: RecurringJob or BackgroundJob + loop for infinite task I'm wondering to use Hangfire to program an update task. I want this task to be executed every time. So when the task finish I want to execute it again.
I don't know if the best method to use is RecurringJob or use a loop and a BackgroundJob for it.
What do you recommend me? Are there any other options?

A: You can use RecurringJob which triggers every x minutes or x hours (based on your requirement - can set CRON expression) , which will trigger the task/work after every such interval. This you need to use in conjunction with DisableConcurrentExecution attribute, so that multiple instances of same task are not triggered, also this attributes makes sure once your first instance is completely, then only second one will be processed.
Alternatively, you can use BackGroundJob to enqueue a task/job but this does the processing of job only one time. So you need to write some code to check this Jobs status and re-enqueue the same job again, once the first is completed. In this approach you need to write some code to do that.
I would suggest the best way is to use RecurringJob.AddOrUpdate in conjunction with DisableConcurrentExecution


text:
Q: codeigniter email->send being send twice i am using codeigniter 2 with the tank_auth library.
in the model named user_model it has an function (_send_email()) to send an email:
function _send_email($type, $email, &$data)
{
    $this->load->library('email');
    $this->config->set_item('language', 'dutch');

    $this->email->set_newline("\r\n");
    $this->email->from($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
    //$this->email->reply_to($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
    $this->email->to($email);
    $this->email->subject(sprintf($this->lang->line('auth_subject_'.$type), $this->config->item('website_name', 'tank_auth')));
    $this->email->message($this->load->view('email/'.$type.'-html', $data, TRUE));
    $this->email->set_alt_message($this->load->view('email/'.$type.'-txt', $data, TRUE));

    if($this->email->send()){
        echo "sendit";
    }
}

i try to call this function from a controller like this:
public function email($value='')
{
    $this->lang->load('tank_auth', 'dutch');
    $this->load->model('user_model');
    $data = array("site_name" => "site name");
    $this->user_model->_send_email('bestelling_geplaatst', "my_email@hotmail.com",$data); // send
}

the problem is that the email is being sent twice to the email adres
anyone who run across this problem an know's where to look for an solution ( or the problem)
More info:
i am trying to make a method in my controller just like the example in the use guide like here: https://www.codeigniter.com/user_guide/libraries/email.html
    $this->load->library('email');

$this->email->from('your@example.com', 'Your Name');
$this->email->to('someone@example.com');
$this->email->cc('another@another-example.com');
$this->email->bcc('them@their-example.com');

$this->email->subject('Email Test');
$this->email->message('Testing the email class.');

$this->email->send();

This method also sends the email twice!

A: The reason is i have the plugin Firebug Lite for Google Chrome. after i deactivated this the page only requested once!
found awnser right here:
https://stackoverflow.com/a/10580841/1108772
Thanks everyone for replying and all you help

A: Remove this code
if($this->email->send())
{
    echo "sendit";
}

from
function _send_email($type, $email, &$data)

A: First of all, This is wrong approach. Use model function only to interactive with database. The function that sends the mail should be in controller.


text:
Q: CUDA Nsight - find out what CPU is doing between kernel/runtime api calls I'm wondering if there's any way to discover in Nsight what CPU function calls are made between two runtime API/driver or kernel calls (an image's worth a thousand words):

Is it possible?

A: Using the NVIDA Tools Extension API you can get a variety of information about CPU activity (in addition to GPU activity) in the Nsight VSE profiler display.
There are a variety of examples given in the Nsight VSE 3.0 documentation.
The same API works with the standalone visual profiler -- nvvp.


text:
Q: Priors and nested random effects in MCMCglmm? I am trying to construct a zero inflation Poisson GLMM using MCMCglmm(). I am new to Bayesian Statistics and this function and I am struggling to understand a couple of things.
For my data I am looking at the species richness of high risk species counted around sensitive sites, I have calculated some variables to explain this distribution and I have a nested random effect structure; with the Date of the count nested within the Location of the site (in glmer terms; (Day.of.the.Year|Location) ).
I have struggled to find methods to construct nested random effects in MCMCglmm syntax (maybe I am looking in the wrong places!) but I found one method that said I needed to create a new column with both in;
HRnaomit$DaynestLoc <- paste0(HRnaomit$Day.of.the.Year,HRnaomit$Location)

Am I doing this correctly? As I said I am new to this, so if I am doing it correctly, I'd love to understand a bit more as to why I am doing it correctly.
The model below is just for looking at random effects, this is where my error code comes into play;
NESTHRRM1<-MCMCglmm(HRRich~1, random = ~DaynestLoc, data=HRnaomit, family="zipoisson", rcov=~idh(trait):units, prior=prior)
prior<-list(R=list(V=diag(2)/2,nu=0.05), G=list(G1=list(V=diag(2)/2,nu=0.05)))
Error in priorformat(if (NOpriorG) { :
  V is the wrong dimension for some prior$G/prior$R elements

So the prior I have here is likely wrong beyond the V being in the wrong dimension as I do not fully understand how to define the V value; I understand G is for the random effects, is the V value the value of all the levels within random effects? I am right in saying the higher the value of nu the more informative the prior?
How do you decide how informative a prior should be?
If anyone has any walkthroughs on constructing priors they could point me towards I would also be grateful!

A: It would help if you posted a reproducible example to look at what your data looks like. I'm no expert either but will try to help.
For what I can see without looking at an example, you have two problems. One with your prior and another in your model set-up. In the prior, the dimension of V within each structure depends on the number of response variables you have. So if you have only one response variable, your R structure should be V=1 (or V=diag(1)). As for your random structure, your G structure should have V=1 for each random effect, which is only the nested effect (which counts as one). Your nested random effect is backwards I think, since the notation for nested effects in MCMCglmm works as (Larger hierarchy/Smaller hierarchy) so I would set it as:
DaynestLoc <- paste0(HRnaomit$Location,HRnaomit$Day.of.the.Year)

And your prior
prior <- list(R=list(V=diag(1),nu=0.002),
        G=list(G1=list(V=diag(1),nu=0.002)))

In the prior, you want to have a flat non-informative prior, unless your data is insufficient for the model to converge, in that case you may want to look at an informative prior.
The other problem you have is in the rcov determination in the model configuration. You have a single response variable, hence you can't calculate a covariance structure with other responses, because they don't exist!
Try this in the rcov:
rcov:~units

Again, I'm no expert either but I think that should help.


text:
Q: C# project reference and hintpath using variable We have a VS2017 C# solution which contains multiple projects. Each project contains several references and some contain a hintpath. This path is currently a hardcoded string.
Does VS2017 provide the ability to define a variable/macro at solution level that will be resolved if used as part of hintpath.
For example, currently the hintpath might say
"c:\thirdparty\comp\1.2.3\my_assembly.dll"
and we would like something like this;
"${thirdparty}\comp\1.2.3\my_assembly.dll"
Appreciate any input.


text:
Q: What does a[href^="..."] do in CSS? I have used CSS before and I came across the below CSS style, don't have a clue what it does.
a[href^="http:"] {
   background: url(img/keys.gif) no-repeat right top;
}
a[href^="http://mysite.com"], a[href^="http://www.mysite.com"] {
   background-image: none; padding-right:0;
}

A: Those are attribute-starts-with selectors, they'll select  elements with an href attribute starting with that value, e.g. a[href^="http:"] matches any anchors with an href starting with href="http:....", for example:
Test
Test

A: a[href^="http:"]

Selects an  element whose href attribute value begins with http:.
For example:
p[title^="para"] {background: green;}

Will match the following:

 This paragraph should have a green background.

A: For every link which's "href" parameter starts with "http:", set the background to a key image (without repetition, positioned in the top-right corner).
For every link which's "href" parameter starts with "http://mysite.com" or "http://www.mysite.com", set the background image to nothing (and the right-side padding to 0).
To me, this seems like a clever CSS trick that will make your users aware of when they are leaving your website through an external link by displaying a key image.
(I think I'll use it in the future. :)

A: That's one of the substring-matching attribute selectors available in CSS3. It matches links with href attributes whose values start with the given string.
To illustrate, we'll take your example CSS, and add some defaults:
a {
   background: none; padding: 0 1em;
}

a[href^="http:"] {
   background: url(img/keys.gif) no-repeat right top;
}

a[href^="http://mysite.com"], a[href^="http://www.mysite.com"] {
   background-image: none; padding-right:0;
}

And style the following HTML with it. The output styles are summarized in comments:

My site's page

External link

My site's base URL without www

My site's base URL with www

A page in my site with base URL

What's happening?

*

*Selected by a only
This element's href="/index.php" attribute doesn't start with http: or the other values.
There is no background, but there is left and right padding.

*Selected by a[href^="http:"] only
This element's href="http://example.com" attribute starts with http: but doesn't start with http://mysite.com.
There is both left and right padding, and a background image.

*Selected by a[href^="http:"] and a[href^="http://mysite.com"]
This element's href="http://mysite.com" attribute starts with http: and further starts with http://mysite.com.
Since the second selector overrules the first selector, the background image and right padding are removed.

*Selected by a[href^="http:"] and a[href^="http://www.mysite.com"]
This element's href="http://www.mysite.com" attribute starts with http: and further starts with http://www.mysite.com (notice the www).
Since the second selector overrules the first selector, the background image and right padding are removed.

*Selected by a[href^="http:"] and a[href^="http://mysite.com"]
This element's href="http://mysite.com/page.php" attribute starts with http: and further starts with http://mysite.com.
Notice that, compared to the third link, the attribute in this one contains more than just the base URL; however, the ^= indicates that the attribute's value just needs to start with your site's base URL, as opposed to = which would mean "select links that only point to http://mysite.com". Therefore, this link is matched by the second selector.
Since the second selector overrules the first selector, the background image and right padding are removed.

A: The rules say, according to the W3C docs:

*

*All anchors which have an href attribute that starts with http:

*All anchors which have an href attribute that start with http://mysite.com or http://www.mysite.com

A: It's an attribute selector.
The ^= part means that the href attribute of the anchor tags must begin with http: in your first example.


text:
Q: Api.ai context limit(10 contexts per intent) I am adding output context in my intent in Api.ai but after creating the 10th output context in intent,api.ai is giving me this "The number of output contexts per intent has reached the limit of 10" and I am unable to further add output context in that intent.Is there a way to increase the context per intent limit.I need to create more than 15-20 output contexts in my api.ai agent.

A: Not sure why you would need that many, but there is no way of adding more than 10 contexts at this time

A: Dialogflow.com has now come up with Standard & Enterprise editions. As mentioned in this snap, you should contact support@dialogflow.com to apply for higher quotas. You may need to pay for this.


text:
Q: Java игнорирует переменную среды Path в Windows XP Решил переустановить jdk в другую директорию. Переписал переменные среды, но при проверке работоспособности java (java -version) пытается запуститься из старого каталога и выдает ошибку.
Подскажите может где то нужно что-то подчистить?
Изначально jdk стоял в папке

D:\Стас\П\Java\Библиотеки\jdk 7.79

Переставил в папку

D:\Стас\Java\Библиотеки\jdk 7.79

Переменные среды:
JAVA_HOME = D:\Стас\Java\Библиотеки\jdk 7.79
Path = %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Program Files\Kaspersky Lab\Kaspersky Endpoint Security 10 for Windows\;%JAVA_HOME%\bin
При запуске java -version выдает вот такое:

Error: could not open `D:\╤Єрё\╧\Java\┴шсышюЄхъш\jre 7\lib\i386\jvm.cfg

A: Огромное спасибо Vartlok.
В папке C:\WINDOWS\system32 действительно был java.exe
Как только удалил его то сразу (даже без перезагрузки) все заработало.


text:
Q: How to return only particular fields to list using LINQ lambda expressions
Possible Duplicate:
Retrieve an object from entityframework without ONE field

I am working on asp.net mvc. currently i am using EF 4.1 code first model. Here i have list of records(43). My class is like,
public class MyTable
{
public string field1{get; set;}
public string field2{get; set;}
.
.
.
public string field20{get; set;}
}

and i am returning them as a list like List. But i dont want the field20 to return. so how could i skip particular field in my list. I have used like,
(from m in context.MyTable select new{m.field1,m.field2,...,m.field19}).ToList();

Its working very fine. but i want same result using lambda expression syntax like
context.MyTable.Skip() or any etc.

How to return only particular fields to list.

A: well you can write
context.MyTable.Select(x => new { x.field1, x.field2, ..., x.field19}).ToList();

If you don't want to write all 19 fields, you can make you MyTable class implement IEnumerable
public class MyTable : IEnumerable<object>

public IEnumerator<object> GetEnumerator()
{
    List<object> list = new List<object>();
    list.Add(field1);
    list.Add(field2);
    ...
    list.Add(field20);
    return list.GetEnumerator();
}

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
    return GetEnumerator();
}

And then you can write
context.MyTable.Select(x => x.Take(19).ToList()).ToList();


text:
Q: Android Studio Layout - Horizontal centering in parent of two textviews that are next to each other on same line I have a beginners question about relative layouts and centering of two textviews in Android Studio. I have two textviews that are aligned on the same line and the right one is aligned "toEndOf" the left textview. Now how do I center them both horizontally in the parent so the line of text is centered left to right on the screen? See image.

With the given layout, "I Am" is nicely centered horizontally, but I want the both textviews taken together to be centered so that "I Am Poor" is centered.

A: I would put them inside another layout (as linear with horizontal orientation) and then center that other layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ONE"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TWO"/>
    </LinearLayout>

</RelativeLayout>

A: The modern replacement for RelativeLayout is ConstraintLayout. In a ConstraintLayout, you can create what are called chains of views, and then define centering behavior for the entire chain.
Here's how you'd do it:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/small"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="short"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@id/large"/>

    <TextView
        android:id="@+id/large"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="very very very long"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toEndOf="@id/small"
        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

The chain is formed by connecting both the start and the end of both views to each other and to the parent:
android:id="@+id/small"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toStartOf="@id/large"

android:id="@+id/large"
app:layout_constraintStart_toEndOf="@id/small"
app:layout_constraintEnd_toEndOf="parent"

You then also apply the packed style so that the views are positioned exactly next to each other, rather than spread out with space between them:
app:layout_constraintHorizontal_chainStyle="packed"

In the end, this is the result:


text:
Q: How to pass a collection of Entities to .NET RIA Data Service? Is it possible to pass a collection of objects to a RIA Data Service query? I have no issues sending an Entity, an Int or an array of primitive types, but as soon as i declare a method like this
public void GetLessonsConflicts(Lesson[] lessons)
{
}

i get a compilation error

" Operation named
  'GetLessonsConflicts' does not conform
  to the required signature. Parameter
  types must be an entity type or one of
  the predefined serializable
  types"

I am just trying to do some validation on the server side before i save the data. I've tried List, IEnumerable etc.
Thanks

A: I think the problem is actually the lack of a return value.  As I understand it, you can identify DomainOperations by convention or by attribute.  You're not showing an attribute so RIA will be trying to match it by convention.
For example, by convention, an insert method must:

*

*have Insert, Add or Create as the method name prefix, e.g. InsertEmployee

*match the signature public void name(Entity e);

a query method must:

*

*be public

*return IEnumerable, IQueryable or T (where T is an entity).

a custom domain operation must

*

*be public

*return void

*have an Entity as the first parameter.

EDIT: See Rami A's comment below.  I believe this was true at the time but I'm not currently working with this technology so I'm not current enough on it to update this answer other than to note that it may be incorrect.
Or you can use Attributes such as [Insert],[Delete],[Update],[Query],[Custom].  From my docs, all the attributes do is remove the requirement for the name convention - it's not clear from them, to me, what the [Query] and [Custom] attributes achieve.
As well as DomainOperations, you can define ServiceOperations (using the [ServiceOperation] attribute) and InvokeOperations.
This article might help (although I think it's a bit out of date).


text:
Q: Java Exception: unknown protocol: udp I am trying to run a basic java program as part of reverse engineering an application.
I am getting

java.net.MalformedURLException: unknown protocol: udp

exception while running following code
public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("udp://xxx.xxxx.com:1234/");
    }

Thanks in Advance.

A: the problem here is really that udp is not a protocol; it's a transport, like tcp. You can't use a tcp://host:port/ URL either.

A: Cause
You are using a version of the Java Developer Kit (JDK) that was released prior to JDK 1.4.


text:
Q: How to deal with open array of TControls I have this code which does not compile:
function IsControlOneOf(AControl: TControl; AControls: array of TControl): Boolean;
begin
  Result := False;
  // if AControls <> nil then // does not compile!
  if Length(AControls) <> 0 then // this compiles
    Result := AControl in AControls; // does not compile!
end;

I am probably mistaking dynamic array with open array.
How can I test that "AControl in AControls"?
Should I iterate Low(AControls) to High(AControls) and test for match, or what?
Also, Is there a way to set a default value for the open array?
AControls: array of TControl = []

Does not compile either.

A: The in operator is used with sets. You cannot use it to test whether an element is present in an open array parameter. In fact you can never use in to test if an element is a member of any type of array. You will need to iterate over the array and check each element.
It is expected that you cannot compare an open array parameter with nil. Remember that open arrays are not the same as dynamic arrays, no matter how similar their syntax appears.
Finally, I suggest that you do not pass open array parameters by value. That results in a copy of the array being made which is of course expensive for large arrays, not to mention needless. Declare the open array parameter as const.

In your question edit you ask about default parameters. You cannot specify default values for open array parameters. So in order to achieve the flexibility you need you will have to use overloaded procedures instead.

A: The best way to handle this is with an enumeration:
function IsControlOneOf(AControl: TControl; const AControls: array of TControl): Boolean;
var
  lControl: TControl;
begin
  for lControl in AControls do
    if lControl = AControl then
      exit(true);
  result := False;
end;

Unfortunately, this is tagged Delphi 7, so you don't have a few of those language features.  So you'll have to do it the old-fashioned way:
function IsControlOneOf(AControl: TControl; const AControls: array of TControl): Boolean;
var
  i: integer;
begin
  for i := 0 to high(AControls) do
    if AControl = AControls[i] then
    begin
      result := true;
      exit;
    end;
  result := False;
end;


text:
Q: C#. Console.ReadLine() for two different obejcts I'm learning C# and very new to this topic. Currently, I'm working on a small console app (just doing tasks to strengthen my knowledge) Battleship game. I want to assign two names: Player 1 and Player 2.
Question is: Can I use one reader instead of two, to assign different names? I tried to use one reader, but it assigned one name to both players.
Here is my code:
public void StartGame(Game game)
        {
            if (game.GameStage == GameStage.Start)
            {
                Console.WriteLine("Welcome to Battleship 2020.");
                Console.WriteLine("Player 1 enter your name:");

                var reader1 = Console.ReadLine();
                Player player1 = new Player();
                player1.Name = reader1;

                Console.WriteLine($"Welcome {player1.Name}");

                Console.WriteLine("Player 2 enter your name:");
                Player player2 = new Player();
                var reader2 = Console.ReadLine();
                player2.Name = reader2;

                Console.WriteLine($"Welcome {player2.Name}");
            }
        }

A: If you want to get both player names in one read, (you may first prompt the user) and tell them to enter players name comma or space separated and then after reading the player names separate them yourself
 var reader = Console.ReadLine();
 var playerNames = reader.Split(' '); // payerNames[0], playerNames[1] contains player names

If you mean just to reuse the reader variable. you can use it any times you want but the first time you need to declare it.
 var reader = Console.ReadLine();
 ...
 reader = Console.ReadLine();
 ...
 reader = Console.ReadLine();

You may put this in a loop like:
for(int i = 0; i < 2; i++)
{
    var reader = Console.ReadLine();
    ...
}

if you want to make sure that no empty value is entered, you may use do...while and loop till a valid value is set. (retry on empty or invalid values):
for(int i = 0; i < 2; i++)
{
    do
    {
        player[i] = Console.ReadLine();
    } while(player[i].Trim() != "");
}

A: Console.ReadLine() does not return any "reader". It just returns String object which contains text grabbed from console input.
The line in method name means it will read everything available on the input until it will encounter line break.
If there is no line break, it will wait forever until user will press "enter" key.
If there are many text lines in the bufffer, you need to call ReadLine() many times.
You can assign player name diretly using:
 player1.Name = Console.ReadLine();


text:
Q: php multidimensional array get first date value I need help once again. I have an array and I need to extract earliest day weight value.
EDIT - EDIT - EDIT

array (
  3 =>
  array (
    'id' => '20110211',
    'Date' => '2011-02-11',
    'Weight' => '195',
  ),
  4 =>
  array (
    'id' => '20110213',
    'Date' => '2011-02-13',
    'Weight' => '160',
  ),
  6 =>
  array (
    'id' => '20110310',
    'Date' => '2011-03-10',
    'Weight' => '200',
  ),
  12 =>
  array (
    'id' => '20110301',
    'Date' => '2011-03-01',
    'Weight' => '55',
  ),
  21 =>
  array (
    'id' => '20110215',
    'Date' => '2011-02-15',
    'Weight' => '120',
  ),
  25 =>
  array (
    'id' => '20110322',
    'Date' => '2011-03-22',
    'Weight' => '250',
  ),
)

I've edited this and this code works:

function sortByDate ($arr1, $arr2)
{
   return strcmp($arr1['Date'], $arr2['Date']);
}
// $arr is your array
usort($weight_tracker, 'sortByDate');
$earliest = $weight_tracker[0]['Weight'];
echo $earliest;

But since I have a form on this page which updates the array when array is updated - I got message Fatal error: Cannot use string offset as an array in
EDIT -> I've re-declared this as string, hence the ERROR ! be careful when using global and includes as everything can become a mess ! PHP is forgiving, but that "forgiveness" can cost a lot of time later on...  :)
Thanks,
Peter

A: You could sort the array with a custom callback using usort() and then take the first element.
// $arr is your array
usort($arr, 'sortByDate');
$earliest = $arr[0];

function sortByDate ($arr1, $arr2)
{
   return strcmp($arr1['Date'], $arr2['Date']);
}

A: This is one way of doing it:
function filter_min($a, $b) {
  return ($a['Date'] < $b['date']) ? $a : $b;
}

$result = array_reduce($array, 'filter_min');
echo $result['Weight'];

Another way is to simply iterate over the array and find the smallest date.

A: $smallest = null; // array index of entry with smallest weight.
foreach ($array as $idx => $data) {
    if (($data['Weight'] < $array[$smallest]['Weight']) || (is_null($smallest))) {
      $smallest = $idx; // found a small weight, so save the index
    }
}

echo $array[$smallest]['Date'];

A: I noticed that the dates are in reverse order with the latest date being pulled in first, and the earliest date last.  Will it always be like that?  If so, you can do this:
$index = count($array) - 1;
$earliestdate = $array[$index]['Date'];

You could also use array_reverse() to invert the array and make the first element the formerly last element.
If this is being pulled in from MySQL you could also alter the query to ORDER BY 'Date' DESC (or is it ASC that would get you what you want, can't remember)


text:
Q: Views show child taxonomy terms I have a vocabulary like this:
Parent 1
- Child 1
- Child 2
- Child 3
Parent 2
- Child 1
- Child 2

Now i would like to use a view to create a list of all the child terms under one parent.
So i thought i just created a term Views and pass the Parent term as an argument and it will filter out all the child terms of that parent.
But this doesn't seem to be possible with the standard views.
The only thing that's possible is to get the parent term when you supply the child term, but not the other way around.
Anyone an idea how i can do this?

A: The Views module has a  taxonomy_term View which you can use.  You need to edit the View so that under the Arguments -> Taxonomy: Term ID (with depth) -> change the depth so that you can grab as many levels of child objects as you want.  If you want to exclude the parent item, you can do this by adding a filter to exclude the parent term.

A: There is an filter argument for "Taxonomy term: Parent term"
If you set that to bee less than 1. You will only get root elements in your taxonomy.

A: Here is the quick solution, go to admin/structure/views/import, import below views and update views according to your requirement.
$view = new view();
$view->name = 'locations2';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'taxonomy_term_data';
$view->human_name = 'Product Categories';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Product Categories';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['distinct'] = TRUE;
$handler->display->display_options['query']['options']['pure_distinct'] = TRUE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'grid';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Taxonomy term: Parent term */
$handler->display->display_options['relationships']['parent']['id'] = 'parent';
$handler->display->display_options['relationships']['parent']['table'] = 'taxonomy_term_hierarchy';
$handler->display->display_options['relationships']['parent']['field'] = 'parent';
/* Field: Global: View result counter */
$handler->display->display_options['fields']['counter']['id'] = 'counter';
$handler->display->display_options['fields']['counter']['table'] = 'views';
$handler->display->display_options['fields']['counter']['field'] = 'counter';
$handler->display->display_options['fields']['counter']['label'] = '#';
$handler->display->display_options['fields']['counter']['counter_start'] = '1';
$handler->display->display_options['fields']['counter']['reverse'] = 1;
/* Field: Taxonomy term: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'taxonomy_term_data';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['name']['link_to_taxonomy'] = TRUE;
/* Filter criterion: Taxonomy vocabulary: Machine name */
$handler->display->display_options['filters']['machine_name']['id'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['table'] = 'taxonomy_vocabulary';
$handler->display->display_options['filters']['machine_name']['field'] = 'machine_name';
$handler->display->display_options['filters']['machine_name']['relationship'] = 'parent';
$handler->display->display_options['filters']['machine_name']['operator'] = 'not empty';

/* Display: Product Categories List */
$handler = $view->new_display('block', 'Product Categories List', 'block_2');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'counter' => 'counter',
  'name' => 'name',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'counter' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'name' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;