text:
Q: Testcafe role problems with logout I use the Testcafe roles in my script to avoid new logins each test inside a fixture. It works really good, but I run into a problem where I cannot find any solution.
If I use the role to log in into the page and I use the common page functions to logout of the page, it means to click the selector Logout, then the upcoming script still thinks that the role is still logged in and the test fails.
As sample:
test('Login und Logout', async t => {
        const loginheader = Selector('.login-header')
        await t
        .useRole(bc3Tester)
        .navigateTo(inputStore.metaUrl)
        .click(Selector('.cl-sidemenu-button'))
        .click(Selector('.side-menu-logout.cl-asset-button-animation'))
    await t
           .wait(2000)
           .expect(loginheader.exists).ok()
});

If I run this test a second time it will fail at
.click(Selector('.cl-sidemenu-button'))

because the role script not work (No auto login again)
const bc3Tester = Role(inputStore.metaUrl, async t => {
await t
   .typeText(Selector('#email'), inputStore.clLogin, {
      caretPos: 0
   })
   .typeText(Selector('#password'), inputStore.clPassword, {
       caretPos: 0
   })
   .click(Selector('span').withText('Login'))
});

Because it will not log in. Any idea?


text:
Q: Timestamp, misc, and date accessed for Bibtex This question has been addressed in parts in many other places (BibTeX and "accessed" field for web page)
(URL date access missing)
but I could not find a satisfactory answer.
I use JabRef to create my bibtex file (it does not matter though, I think). I have hundreds of @misc entries pointing to a website where there is no "url-date" field but there is a timestamp field. I want the timestamp field to be reflected as the date accessed in my main .tex file. How do I do that with minimum manual effort? I do not want to use the manual "Note, Online, date accessed = XXX" idea.
I am using BibTex and pdflatex.
Example:
@Misc{AustraliaPost2018,
  author      = {{Australia Post}},
  title       = {Fast facts about {Australia Post}},
  year        = {2018},
  institution = {Australia Post},
  timestamp   = {2020-05-25},
  url         = {https://auspost.com.au/about-us/news-media/fast-facts-about-australia-post},
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error: Connection lost: The server closed the connection I have just put my node.js app in a local server in order to host it, so some users will be able to use it and I am having the following issue:
Everything works fine when I run the app, even after some minutes it keeps working well. However, if I leave it running for some some days, it stops working and I get this error. For instance, I ran it the last friday and today (Monday) I have seen this error when I connected remotelly to the server.
This is my server file:
const express = require('express');
const bodyParser = require("body-parser");
const crypto = require('crypto');
var session = require('express-session');
const internalIp = require('internal-ip');
const getPrices = require('./scrapers/getPrices.js');
const dbConnection = require('./dbConnection.js');
const app = express();
app.use('/assets', express.static('./assets/'));
const localIP = internalIp.v4.sync();
var hotelNames = [];
var urlsHotels = [];
var usersList = [];
var userInfo = new Object();

userInfo.id = undefined;
userInfo.role = 0;

app.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
}));

app.get('/', function (req, res) {
    if (req.session.loggedin && userInfo.role == 0) {
        getHotelsdata(res);
    } else if (req.session.loggedin && userInfo.role == 1) {
        loadAdminPage(res);
    } else {
        res.redirect('/login');
    }
});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/login',function(req,res){
    globalRes = res
    //res.sendFile(__dirname + "/views/login.html");
    res.render('./login.ejs', {
        'localIP':localIP,
    });
});
app.post('/submitlogin',function(req,res){
    const password = crypto.createHash('sha256').update(req.body.password).digest('hex');
    const users = new Promise((resolve, reject) => {
        dbConnection
        .getUsers()
        .then(data => {
            resolve(data)
        })
    });
    Promise.all([users])
    .then(data => {
        usersList = data[0];
        var loginSuccess = "0";
        for(var i = 0; i < data[0].length; i++) {
            if(data[0][i][1] == req.body.user && data[0][i][2] == password) {
                req.session.loggedin = true;
                req.session.username = req.body.user;
                loginSuccess = "1";
                userInfo.id = data[0][i][0];
                userInfo.role = data[0][i][3];
            }
        }
        res.end(loginSuccess);
    });
});

app.post('/deleteUser', function(req, res) {
    const deleteUser = new Promise((resolve, reject) => {
        dbConnection
        .deleteUser(req.body.user)
        .then(data => {
            resolve(data)
            response = data[0];
        })
    });
    Promise.all([deleteUser])
    .then(data=> {
        getUsersData(res, response);
    });
})

app.post('/changePwd', function(req, res) {
    const currentPassword = crypto.createHash('sha256').update(req.body.currentPassword).digest('hex');
    const newPassword = crypto.createHash('sha256').update(req.body.newPassword).digest('hex');
    const changePwd = new Promise((resolve, reject) => {
        dbConnection
        .changePwd(currentPassword, newPassword)
        .then(data => {
            resolve(data)
            response = data[0];
        })
    });
    Promise.all([changePwd])
    .then(data=> {
        res.end(data[0]);
    });
})

app.post('/addUser', function(req, res) {
    const password = crypto.createHash('sha256').update(req.body.password).digest('hex');
    var response;
    const insertUser = new Promise((resolve, reject) => {
        dbConnection
        .registerUser(req.body.user, password)
        .then(data => {
            resolve(data)
            response = data;
        })
    });
    Promise.all([insertUser])
    .then(data => {
        getUsersData(res, response);
    });
});

app.get('/compare/:visitDay&:visitMonth&:visitYear&:leavingDay&:leavingMonth&:leavingYear', async function(req, res, next) {
    if (req.session.loggedin) {
        var results = new Array();
        const date1 = new Date(req.params.visitMonth + '-' + req.params.visitDay + '-' + req.params.visitYear);
        const date2 = new Date(req.params.leavingMonth + '-' + req.params.leavingDay + '-' + req.params.leavingYear);
        const timeDiff = Math.abs(date2.getTime() - date1.getTime());
        const nights = Math.ceil(timeDiff / (1000 * 3600 * 24));
        assignurls(req.params.visitYear, req.params.visitMonth, req.params.visitDay, req.params.leavingYear, req.params.leavingMonth, req.params.leavingDay);
            const getPrices = new Promise((resolve, reject) => {
            getPrices
            .getPrices(results, nights, urlsHotels)
            .then(data => {
                resolve(data)
            })
        });
        Promise.all([getPrices])
        .then(data => {
            loadPage(res, JSON.stringify(hotelNames), JSON.stringify(results), req.params.visitDay + "/" + req.params.visitMonth + "/" + req.params.visitYear, req.params.leavingDay + "/" + req.params.leavingMonth + "/" + req.params.leavingYear);
        });
    } else {
        res.redirect('/login');
    }
});

app.get('/addHotel&:url&:name', function(req, res, next) {
    if (req.session.loggedin) {
        let url = req.params.url.split('');
        url.splice(44, 3);
        url[44] = 'visitYear';
        url.splice(46, 1);
        url[46] = 'visitMonth';
        url.splice(48, 1);
        url[48] = 'visitDay';
        url.splice(70, 3);
        url[70] = 'leavingYear';
        url.splice(72, 1);
        url[72] = 'leavingMonth';
        url.splice(74, 1);
        url[74] = 'leavingDay';
        url = url.join('');
        const insertHotel = new Promise((resolve, reject) => {
            dbConnection
            .insertValues(hotelNames, url, req.params.name, userInfo.id)
            .then(data => {
                resolve(data)
            })
        });
        Promise.all([insertHotel])
        .then(data => {
            getHotelsdata(res, data);
        });
    } else {
        res.redirect('/login');
    }
});

app.get('/deleteHotel&:name', function(req, res, next) {
    if (req.session.loggedin) {
        const deleteHotel = new Promise((resolve, reject) => {
            dbConnection
            .deleteValues(req.params.name)
            .then(data => {
                resolve(data)
            })
        });
        Promise.all([deleteHotel])
        .then(data => {
            getHotelsdata(res, data);
        });
    } else {
        res.redirect('/login');
    }
});

app.get('/logout', function(req, res, next) {
    req.session.loggedin = false;
    res.redirect('/');
});

function assignurls(visitYear, visitMonth, visitDay, leavingYear, leavingMonth, leavingDay) {
    for(var i = 0; i<urlsHotels.length; i++) {
        var finalurl = urlsHotels[i].replace('visitYear', visitYear);
        finalurl = finalurl.replace('visitMonth', visitMonth);
        finalurl = finalurl.replace('visitDay', visitDay);
        finalurl = finalurl.replace('leavingYear', leavingYear);
        finalurl = finalurl.replace('leavingMonth', leavingMonth);
        finalurl = finalurl.replace('leavingDay', leavingDay);
        urlsHotels[i] = finalurl;
    }
}

function getUsersData(res, response) {
    const users = new Promise((resolve, reject) => {
        dbConnection
        .getUsers()
        .then(data => {
            resolve(data);
        })
    });
    Promise.all([users])
    .then(data => {
        usersList = data[0];
        res.end(response);
    });
}

function getHotelsdata(res, results) {
    const getNotelNames = new Promise((resolve, reject) => {
        dbConnection
        .getHotelNames(userInfo.id)
        .then(data => {
            resolve(data)
        })
    });

    const getURLs = new Promise((resolve, reject) => {
        dbConnection
        .getURLs(userInfo.id)
        .then(data => {
            resolve(data)
        })
    });
    Promise.all([getNotelNames, getURLs])
    .then(data => {
        hotelNames = data[0];
        urlsHotels = data[1];
        loadPage(res, JSON.stringify(hotelNames), JSON.stringify([results]));
    });
}

function loadPage(res, param1, param2, param3, param4) {
    res.render('./comparatorPage.ejs', {
        'hotelNames':param1,
        'results': param2,
        'checkInDate': param3,
        'checkOutDate': param4,
        'localIP': localIP,
    });
}

function loadAdminPage(res) {
    res.render('./adminPage.ejs', {
        'usersList': JSON.stringify(usersList),
        'localIP': localIP
    });
}

app.listen(process.env.PORT || 3000);

That is the error I get:

As I said, everything works fine until it is running during some days.
How can I solve this? Node.js is a sever-side language, so this should not be happening.
Thank you in advance.
Additional info: I use Windows Server 2008 R2 Standard.


text:
Q: How to extract substring in parentheses using Regex pattern This is probably a simple problem, but unfortunately I wasn't able to get the results I wanted...
Say, I have the following line:
"Wouldn't It Be Nice" (B. Wilson/Asher/Love)

I would have to look for this pattern:
" (<any string>)

In order to retrieve:
B. Wilson/Asher/Love

I tried something like "" (([^))]*)) but it doesn't seem to work. Also, I'd like to use Match.Submatches(0) so that might complicate things a bit because it relies on brackets...

A: Not strictly an answer to your question, but sometimes, for things this simple, good ol' string functions are less confusing and more concise than Regex.
Function BetweenParentheses(s As String) As String
    BetweenParentheses = Mid(s, InStr(s, "(") + 1, _
        InStr(s, ")") - InStr(s, "(") - 1)
End Function

Usage:
Debug.Print BetweenParentheses("""Wouldn't It Be Nice"" (B. Wilson/Asher/Love)")
'B. Wilson/Asher/Love

EDIT @alan points our that this will falsely match the contents of parentheses in the song title. This is easily circumvented with a little modification:
Function BetweenParentheses(s As String) As String
    Dim iEndQuote As Long
    Dim iLeftParenthesis As Long
    Dim iRightParenthesis As Long

    iEndQuote = InStrRev(s, """")
    iLeftParenthesis = InStr(iEndQuote, s, "(")
    iRightParenthesis = InStr(iEndQuote, s, ")")

    If iLeftParenthesis <> 0 And iRightParenthesis <> 0 Then
        BetweenParentheses = Mid(s, iLeftParenthesis + 1, _
            iRightParenthesis - iLeftParenthesis - 1)
    End If
End Function

Usage:
Debug.Print BetweenParentheses("""Wouldn't It Be Nice"" (B. Wilson/Asher/Love)")
'B. Wilson/Asher/Love
Debug.Print BetweenParentheses("""Don't talk (yell)""")
' returns empty string

Of course this is less concise than before!

A: This a nice regex
".*\(([^)]*)

In VBA/VBScript:
Dim myRegExp, ResultString, myMatches, myMatch As Match
Dim myRegExp As RegExp
Set myRegExp = New RegExp
myRegExp.Pattern = """.*\(([^)]*)"
Set myMatches = myRegExp.Execute(SubjectString)
If myMatches.Count >= 1 Then
    Set myMatch = myMatches(0)
    If myMatch.SubMatches.Count >= 3 Then
        ResultString = myMatch.SubMatches(3-1)
    Else
        ResultString = ""
    End If
Else
    ResultString = ""
End If

This matches
Put Your Head on My Shoulder

in
"Don't Talk (Put Your Head on My Shoulder)"

Update 1
I let the regex loose on your doc file and it matches as requested. Quite sure the regex is fine. I'm not fluent in VBA/VBScript but my guess is that's where it goes wrong
If you want to discuss the regex some further that's fine with me. I'm not eager to start digging into this VBscript API which looks arcane.
Given the new input the regex is tweaked to
".*".*\(([^)]*)

So that it doesn't falsely match (Put Your Head on My Shoulder) which appears inside the quotes.

A: Edit: After examining your document, the problem is that there are non-breaking spaces before the parentheses, not regular spaces. So this regex should work: ""[ \xA0]*\(([^)]+)\)
""       'quote (twice to escape)
[ \xA0]* 'zero or more non-breaking (\xA0) or a regular spaces
\(       'left parenthesis
(        'open capturing group
[^)]+    'anything not a right parenthesis
)        'close capturing group
\)       'right parenthesis

In a function:
Public Function GetStringInParens(search_str As String)
Dim regEx As New VBScript_RegExp_55.RegExp
Dim matches
    GetStringInParens = ""
    regEx.Pattern = """[ \xA0]*\(([^)]+)\)"
    regEx.Global = True
    If regEx.test(search_str) Then
        Set matches = regEx.Execute(search_str)
        GetStringInParens = matches(0).SubMatches(0)
    End If
End Function

A: This function worked on your example string:
Function GetArtist(songMeta As String) As String
  Dim artist As String
  ' split string by ")" and take last portion
  artist = Split(songMeta, "(")(UBound(Split(songMeta, "(")))
  ' remove closing parenthesis
  artist = Replace(artist, ")", "")
End Function

Ex:
Sub Test()

  Dim songMeta As String

  songMeta = """Wouldn't It Be Nice"" (B. Wilson/Asher/Love)"

  Debug.Print GetArtist(songMeta)

End Sub

prints "B. Wilson/Asher/Love" to the Immediate Window.
It also solves the problem alan mentioned. Ex:
Sub Test()

  Dim songMeta As String

  songMeta = """Wouldn't (It Be) Nice"" (B. Wilson/Asher/Love)"

  Debug.Print GetArtist(songMeta)

End Sub

also prints "B. Wilson/Asher/Love" to the Immediate Window. Unless of course, the artist names also include parentheses.

A: This another Regex tested with a vbscript (?:\()(.*)(?:\)) Demo Here

Data = """Wouldn't It Be Nice"" (B. Wilson/Asher/Love)"
wscript.echo Extract(Data)
'---------------------------------------------------------------
Function Extract(Data)
Dim strPattern,oRegExp,Matches
strPattern = "(?:\()(.*)(?:\))"
Set oRegExp = New RegExp
oRegExp.IgnoreCase = True
oRegExp.Pattern = strPattern
set Matches = oRegExp.Execute(Data)
If Matches.Count > 0 Then Extract = Matches(0).SubMatches(0)
End Function
'---------------------------------------------------------------

A: I think you need a better data file ;)  You might want to consider pre-processing the file to a temp file for modification, so that outliers that don't fit your pattern are modified to where they'll meet your pattern.  It's a bit time consuming to do, but it is always difficult when a data file lacks consistency.


text:
Q: Windows 10 laptop doesn't connect to internet via wifi I have an HP Pavilion laptop running windows 10. Suddenly it stopped connecting to the Internet through WiFi. Meaning, I can connect to the WiFi but computer can't reach the web. I've formatted and re-installed a fresh copy of Windows 10, but I am still having the issue!
But the laptop's WiFi adapter (Ralink) works fine when LAN gaming.
Means laptop WiFi adapter is working right?
What could be a possible solution?
I tried different WiFi networks at my home / university and public WiFi non of these working with my laptop.
On my WiFi status It shows
IPV4 connectivity: internet
IPV6 connectivity: no network access

A:
Means I can connect to the wifi but computer can't reach the internet.

This looks like the adapter can't resolve Internet addresses. I would recommend you to open a command line window (Win+R -> cmd) and then test this:

*

*ipconfig to see what IP your gateway have (e.g. 192.168.0.1) and to check, if your WLAN adapter got a valid IP address

*ping 192.168.0.1 (your gateway) to see, if there is a response.

*If the ping was successful you could ping to the google DNS with ping 8.8.8.8

*If that was successful, try to ping google.com, if you get an error, then most probably the DNS servers are wrong.

*To see what DNS are set, you could do a ipconfig /all and scroll to the DNS section of your WLAN adapter.

*To set DNS you could follow this steps: https://www.lifewire.com/how-to-change-dns-servers-in-windows-2626242. You could use 8.8.8.8 and 8.8.4.4 (google DNS) or set it to automatically, if something wrong is set.

A: Initially check device manager , network adapter  whether a correct wifi driver is installed in your laptop. If its fine check your router page to see the dhcp settings in order to get the internet working


text:
Q: Discrete uniform probability on a sample space of prime cardinality My question is to show that if I have a fair die with $p$ faces, where $p$ is prime, and the experiment consists of rolling it once, no two proper events can be independent.
Here is my approach:
Suppose $A$ and $B$ are independent events. Then $$P(A \cap B) = P(A) * P(B) = \frac{|A|}{p} * \frac{|B|}{p} = \frac{|A||B|}{p^{2}} < 1$$
Not sure where a contradiction would happen to know how to proceed.
Any help?

A: Neat question!
The outcomes of the die are $\{1,2,\cdots,p\}$. Suppose we have a pair of proper events $A,B$ and we assume they are independent. I'm assuming here that "proper" means neither event is empty and neither event is equal to the whole space. If $A\cap B=\{\emptyset\}$ we immediately get a contradiction, so suppose that $A\cap B=C$, for some proper event $C$. We have:
$\frac{|C|}{p}=P(A\cap B)=P(A)P(B)=\frac{|A||B|}{p^2}$.
Rearranging this gives:
$$p|C|=|A||B|.$$
Since neither $A$ nor $B$ is the full space, $0<|A|<p$ and $0<|B|<p$. Since $|C|>0$ and $p$ is prime, $p$ must divide either $|A|$ or $|B|$. This is clearly a contradiction. Note that if $p$ was not prime (say, $p=4$), then you would only need the factors of $p$ to divide either $|A|,|B|$, so $p$ being prime is necessary.


text:
Q: What are the INFINITY constants in Java, really? I just recently ran across the constants in the primitive type wrapper classes like Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY.  In the API, it defines the first as:

A constant holding the positive infinity of type double. It is equal to the value returned by Double.longBitsToDouble(0x7ff0000000000000L).

The others have definitions along these same lines.
What I'm having trouble with is understanding what these constants actually are.  They can't actually be or represent positive/negative infinities, because the system is by nature finite.  Is it just some arbitrary setting of bits which the Java creators deemed would define the concept of infinity?  Or do these actually have some kind of special value?  If it is just an arbitrary string of bits interpreted as a double, then is there some normal number out there that, when interpreted as a double will return POSITIVE_INFINITY instead of whatever value is actually expected?
Forgive me if the answer to this is obvious given the Double.longBitsToDouble(0x7ff0000000000000L) part of the API.  Truthfully, that description is pretty arcane to me and I won't pretend to understand what the hexadecimal values actually mean or represent.

A: They do indeed represent positive and negative infinity, which are clearly defined concepts in the IEEE floating point standard. For example, dividing a positive floating point number by zero yields positive infinity. As for the bit pattern itself, it is just a pattern that has been chosen to represent infinity.

A: The IEEE Standard 754 Floating Point Numbers states:
"The values +infinity and -infinity are denoted with an exponent of all 1s and a fraction of all 0s. The sign bit distinguishes between negative infinity and positive infinity. Being able to denote infinity as a specific value is useful because it allows operations to continue past overflow situations. Operations with infinite values are well defined in IEEE floating point."
Also:
"Operations on special numbers are well-defined by IEEE. In the simplest case, any operation with a NaN yields a NaN result. Other operations are as follows:"
      Operation         Result
        n ÷ ±Infinity   0
±Infinity × ±Infinity   ±Infinity
±nonzero  ÷ 0           ±Infinity
Infinity  + Infinity    Infinity
       ±0 ÷ ±0          NaN
 Infinity - Infinity    NaN
±Infinity ÷ ±Infinity   NaN
±Infinity × 0           NaN

A: Java floating point is based on the IEEE 754 binary floating point standard Floating Point Standard, the first version of which was issued in about 1985, so it is much older than Java. Given widespread hardware implementation of IEEE 754 by the time Java was being defined, the Java creators had little choice.
Each IEEE 754 floating point number has three components, a sign bit, an exponent, and a mantissa. Simplifying considerably, the magnitude of a normal number is:
 mantissa * (2 ** exponent)

where "**" represents power.
The leading bit is the sign bit. In doubles, the next 11 bits are the exponent.
The bit patterns with all the exponent bits on are reserved for infinities and NaNs. All normal numbers have at least one zero bit in the exponent. The two infinities are represented by having all exponent bits on, and all mantissa bits zero. The leading sign bit distinguishes positive and negative infinity.
The choice of all exponent bits one for the special cases is not arbitrary. It is easier to chop off one of the extremes than to deal with a gap in the middle of a range of numbers, especially for hardware implementations. Taking the all bits off exponent for special cases would have prevented encoding zero with the all bits off pattern, and would have given the largest absolute magnitude values, the infinities, the smallest exponent, which would have also made hardware more complicated. The all bits on exponent is definitely the best choice for the infinities.
The two infinities are both used to represent two things, actually infinite results and results that are too large in absolute magnitude to represent in the normal number system, numbers larger than Double.MAX_VALUE or smaller than -Double.MAX_VALUE. 1.0/0.0 is infinite. So is 2*Double.MAX_VALUE.
There are some algorithms that can be simplified, with fewer special cases, by allowing intermediate results to be infinite, in either sense. Doing so also allows e.g. even a line parallel to the y-axis to have a storable gradient that can be used in calculations.


text:
Q: Azure AD B2C - Custom policy with HRD, Domain Hints and MFA I'm trying to build a B2C custom policy that makes use of Home-realm Discovery and Domain Hints.
We have 2 personas.

*

*Local User that authenticates in B2C with MFA

*External User that must to be redirected to their company's login page.

Use cases:

*

*User gets redirected to https://customdomain.b2clogin.com (no domain hint).
User gets presented with a Login page asking for the email address and depending on type of user:

*

*A local user to B2C authenticates in our B2C page
(customdomain.b2clogin.com). First, user enters email address,
then on Next  user enters password and finally enters code (received on phone)
for MFA.

*An external user first enters their email then B2C must
automatically redirect the user to the federated Identity provider to login.

*User gets redirected to https://customdomain.b2clogin.com/?domain_hint=xyz.com (with domain hint)

*

*In this case we expect the user to be automatically redirected to xyz.com identity provider. The user should NOT see our login page for customdomain.b2clogin.com
What I have tried:
By taking the home-realm-discovery-modern sample (https://github.com/azure-ad-b2c/samples/tree/master/policies/home-realm-discovery-modern) I get HRD working properly (point 1)
By taking the SocialAndLocalAccountsWithMfa sample in the B2C starter pack I get the domain_hint redirection for free (point 2 above).
However, I'm failing at combining the two together to get both working (domain_hint and HRD).
Here is the User Journey:
    <UserJourneys>
       <UserJourney Id="SignIn">

        <OrchestrationSteps>

            <OrchestrationStep Order="1" Type="ClaimsExchange">
                <ClaimsExchanges>
                    <ClaimsExchange Id="ParseDomainHint" TechnicalProfileReferenceId="ParseDomainHint" />
                </ClaimsExchanges>
            </OrchestrationStep>

            <OrchestrationStep Order="2" Type="ClaimsExchange">
                <Preconditions>
                    <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
                        <Value>isKnownCustomer</Value>
                        <Value>True</Value>
                        <Action>SkipThisOrchestrationStep</Action>
                    </Precondition>
                </Preconditions>
                <ClaimsExchanges>
                    <ClaimsExchange Id="SigninEmailExchange" TechnicalProfileReferenceId="SelfAsserted-Signin-Email" />
                </ClaimsExchanges>
            </OrchestrationStep>

            <OrchestrationStep Order="3" Type="ClaimsExchange">
                <Preconditions>
                    <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
                        <Value>isKnownCustomer</Value>
                        <Value>True</Value>
                        <Action>SkipThisOrchestrationStep</Action>
                    </Precondition>
                </Preconditions>
                <ClaimsExchanges>
                    <ClaimsExchange Id="ParseDomainHintLogic" TechnicalProfileReferenceId="HRDLogic" />
                </ClaimsExchanges>
            </OrchestrationStep>

            <!-- If the domain_hint did not match any known domain, then redirect to a default local account sign in-->
            <OrchestrationStep Order="4" Type="CombinedSignInAndSignUp" ContentDefinitionReferenceId="api.signuporsignin">
                <Preconditions>
                    <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
                        <Value>isKnownCustomer</Value>
                        <Value>True</Value>
                        <Action>SkipThisOrchestrationStep</Action>
                    </Precondition>
                </Preconditions>
                <ClaimsProviderSelections>
                    <ClaimsProviderSelection ValidationClaimsExchangeId="LocalAccountSigninEmailExchange" />
                </ClaimsProviderSelections>
                <ClaimsExchanges>
                    <ClaimsExchange Id="LocalAccountSigninEmailExchange" TechnicalProfileReferenceId="SelfAsserted-LocalAccountSignin-Email" />
                </ClaimsExchanges>
            </OrchestrationStep>

            <!-- dont run this step if the domain was known, or we have an objectid (local account sign in)-->
            <OrchestrationStep Order="5" Type="ClaimsExchange">
                <Preconditions>
                    <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
                        <Value>objectId</Value>
                        <Action>SkipThisOrchestrationStep</Action>
                    </Precondition>
                    <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
                        <Value>isKnownCustomer</Value>
                        <Value>true</Value>
                        <Action>SkipThisOrchestrationStep</Action>
                    </Precondition>
                </Preconditions>
                <ClaimsExchanges>
                    <ClaimsExchange Id="SignUpWithLogonEmailExchange" TechnicalProfileReferenceId="LocalAccountSignUpWithLogonEmail" />
                </ClaimsExchanges>
            </OrchestrationStep>

            <!-- If the domain matched any known domain, then this step will have a single IdP
                enabled due to each known IdP TP having an enablement flag via identityProviders claim -->
            <OrchestrationStep Order="6" Type="ClaimsProviderSelection" ContentDefinitionReferenceId="api.idpselections">
                <Preconditions>
                    <Precondition Type="ClaimEquals" ExecuteActionsIf="false">
                        <Value>isKnownCustomer</Value>
                        <Value>True</Value>
                        <Action>SkipThisOrchestrationStep</Action>
                    </Precondition>
                </Preconditions>
                <ClaimsProviderSelections>
                    <ClaimsProviderSelection TargetClaimsExchangeId="AADOIDC" />
                    <ClaimsProviderSelection TargetClaimsExchangeId="MSAOIDC" />
                </ClaimsProviderSelections>
            </OrchestrationStep>

            <OrchestrationStep Order="7" Type="ClaimsExchange">
                <Preconditions>
                    <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
                        <Value>objectId</Value>
                        <Action>SkipThisOrchestrationStep</Action>
                    </Precondition>
                    <Precondition Type="ClaimEquals" ExecuteActionsIf="false">
                        <Value>isKnownCustomer</Value>
                        <Value>true</Value>
                        <Action>SkipThisOrchestrationStep</Action>
                    </Precondition>
                </Preconditions>
                <ClaimsExchanges>
                    <ClaimsExchange Id="AADOIDC" TechnicalProfileReferenceId="AAD-OIDC" />
                    <ClaimsExchange Id="MSAOIDC" TechnicalProfileReferenceId="MSA-OIDC" />
                </ClaimsExchanges>
            </OrchestrationStep>

            <!-- For social IDP authentication, attempt to find the user account in the directory. -->
            <OrchestrationStep Order="8" Type="ClaimsExchange">
                <Preconditions>
                    <Precondition Type="ClaimEquals" ExecuteActionsIf="false">
                        <Value>isKnownCustomer</Value>
                        <Value>True</Value>
                        <Action>SkipThisOrchestrationStep</Action>
                    </Precondition>
                </Preconditions>
                <ClaimsExchanges>
                    <ClaimsExchange Id="AADUserReadUsingAlternativeSecurityId" TechnicalProfileReferenceId="AAD-UserReadUsingAlternativeSecurityId-NoError" />
                </ClaimsExchanges>
            </OrchestrationStep>

            <!-- Still dont have objectId (social idp user that doesnt yet exist) - write the account -->
            <OrchestrationStep Order="9" Type="ClaimsExchange">
                <Preconditions>
                    <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
                        <Value>objectId</Value>
                        <Action>SkipThisOrchestrationStep</Action>
                    </Precondition>
                </Preconditions>
                <ClaimsExchanges>
                    <ClaimsExchange Id="AADUserWrite" TechnicalProfileReferenceId="AAD-UserWriteUsingAlternativeSecurityId" />
                </ClaimsExchanges>
            </OrchestrationStep>

            <OrchestrationStep Order="10" Type="ClaimsExchange">
                <Preconditions>
                    <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
                        <Value>isKnownCustomer</Value>
                        <Value>True</Value>
                        <Action>SkipThisOrchestrationStep</Action>
                    </Precondition>
                </Preconditions>
                <ClaimsExchanges>
                    <ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-UserReadUsingObjectId" />
                </ClaimsExchanges>
            </OrchestrationStep>

            <OrchestrationStep Order="11" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />
        </OrchestrationSteps>
        <ClientDefinition ReferenceId="DefaultWeb" />
    </UserJourney>
</UserJourneys>

What I'm I missing?

A: We managed to get Home Realm Discovery (HRD) and Domain Hints to work together in a custom policy. It's based on the HomeRealmDiscoveryModern sample.
Here is the solution/sample:
https://github.com/AlbozDroid/b2c-hrd-domainhint-sample/blob/main/Alboz_susi_public.xml
The MFA part is not there but should be easy to add by following the LocalAndSocialWithMFA sample provided by Microsoft.


text:
Q: Why does Worf behave more like Klingon than Human given that he was raised by human parents? If a Chinese kid is raised by white American parents, he will most probably grow up to behave more like the white parents than Chinese. This is even more so for an alien raised by humans. At least whites and Chinese are humans.
How can Worf be so much more Klingon than human?
I may have missed out some episodes that explain this unusual phenomenon. In the episodes I watched, Worf behaved more like a Klingon than human.


text:
Q: Number of $k$ letter words on an alphabet of size $n$, excluding permutations of letters, and excluding repeated letters? How do you calculate the number of $k$ letter words on an alphabet of length $n$, with conditions:

*

*order of letters doesn't matter

*words with repeated letters are excluded

E.g. The $2$-letter words on an alphabet of size $3$ $\{A, B, C\}$ would be $3$:

*

*$AB, BC, CA$
(since by 1. $AB = BA$ etc, and by 2. $AA, BB, CC$ are excluded).

A: If the order of letters doesn't matter, and we cannot repeat letters, then we are effectively looking for the number of subsets of size $k$ of the alphabet. The formula for the binomial coefficient calculates exactly this:
$$ \binom{n}{k} = \frac{n!}{k!(n-k)!} $$

In the case $k=2$, a more intuitive method for coming to the above formula may be the following:
First, the total number of $2$-letter words on an alphabet of size $n$ is:
$$n^2$$
Since you have $n$ choices for the first letter, and $n$ choices for the second.
But since we cannot repeat letters, we are effectively choosing our first letter in our word without replacing it back to the alphabet for the second choice, so the formula becomes:
$$n(n-1)$$
And since the order of letters doesn't matter, which in words of length $2$ is equivalent to saying reflected words are identified, we cut our number of words in half:
$$\frac{n(n-1)}{2}$$
Which is equivalent to the above formula for $k=2$.

If calculating this value programatically for large numbers is a concern, the python function scipy.special.comb(n, k, exact=True) is an option.


text:
Q: Sqlcmd: 'KReadOnly': Unknown Option I am using SQL Server 2014 SP2 with AG, running this command:
sqlcmd -S ABC-ISELL -E -d ABP_SFA_BMB -K ReadOnly

Where ABC-ISELL is the listener name, I am getting this error:
Sqlcmd: 'KReadOnly': Unknown Option. Enter '-?' for help.

sqlcmd -? shows there is no -K option, it`s just this:
[-k[1|2] remove[replace] control characters]

What could be wrong here?

A: One needs to use recent enough a version of sqlcmd. The parameter for application intent is -K. Note that sqlcmd's parameters are case sensitive, which is uncommon in Windows environment.
To check sqlcmd's version, run it with -? parameter. Like so,
C:\>sqlcmd -?
Microsoft (R) SQL Server Command Line Tool
Version 14.0.1000.169 NT
Copyright (C) 2017 Microsoft Corporation. All rights reserved.

usage: Sqlcmd            [-U login id]          [-P password]
...
[-k[1|2] remove[replace] control characters]
...
-K application intent

For updated version, check Microsoft's product documentation,
 there's a link to Download center.

A: That instance was SQL 2008 R2 upgraded to 2014 SP2, database version now is: 12.0.5571, still showing this!!
C:\Windows\system32>sqlcmd -?
Microsoft (R) SQL Server Command Line Tool
Version 10.50.6000.34 NT x64
I already restarted the service & rebooted the server, same issue.
Also installed Command Line Utilities 14.0 for SQL Server, same issue.
Which is weird! Any advise?


text:
Q: Android getting Longitude and latitude always returns 0.0 I'm trying to get the longitude and latitude for android, here is my code:
    LocationManager locationManager = (LocationManager)
            this_activity.getSystemService(Context.LOCATION_SERVICE);

    LocationListener locationListener = new MyLocationListener();
    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

 public class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {
        longitude = Double.toString(loc.getLongitude());
        latitude = Double.toString(loc.getLatitude());
    }

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}
}

Manifest Permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I'm always getting 0.0s for longitude and latitude

A: except the permissions that @AshishPedhadiya mentioned you are listening only to the GPS provider.
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

GPS does not work inside. So when you test your application it will practically always return the (0,0) location. You may want to listen to NETWORK_PROVIDER as well which in absent of the GPS location it estimates the location coming from cell towers and WiFi spots.
locationManager.requestLocationUpdates(
        LocationManager.NETWORK_PROVIDER, 5000, 10, locationListener);

Furthermore to get a quick geographic location check out the Application.getLastKnownLocation() method.

A: <!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
<uses-feature android:name="android.hardware.location.gps" />

You need to add permission request in the manifest file above 5.0 version as mentioned in Android developer portal
Source

A: <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
add this permission to your manifest file


text:
Q: one question about differential geometry,show the curvature k($\phi$) One often gives a plane curve in polar coordinates by $p=p(\phi)$,$a\le\phi \le b$.
(1)Show that the arc length is $$\int_{a}^{b}\sqrt{p^2+\dot p^2}$$,where $\dot p$ means the derivative of p with respect to $\phi$.
(2) show that the curvature is $$k(\phi)={{2\dot p^2-p\ddot p+p^2}\over ({\dot p^2+p^2})^{3\over 2}}$$
This problem is from my textbook, I have finished the first question, but when I tried to finish the second question, I tried to compute $d^2\alpha(s)\over ds^2$, I got a huge and complicated derivative. I am stuck here, can someone tell me me how to finish the second question, I think my method is not good. Can someone tell me how to solve the second problem? thank you for your help!


text:
Q: Validating database condition for record existance On my site,
I have textbox where user enters URL.
Onece user enters it I show preview of that url, which contains image on that url and small description.
I fetch preview details from database.
Scenario is like this:
1. user enters url
2. Check whether url exist in table
3. If yes dont inset into db and fetch details like url title, desc, image
4. If not exist insert into table and then show the preview from it

So how first I can check whether it is present in table or not?
I have $url to check the condition.
select url from post_record where url='".$url."';

I want bool or 1/0 result for this query. How can I get it?
If True then I directly fetch record if result is 0 then I first enter the details and then show preview from table.
Is this correct way or better scenario someone can think.

A: Just select the COUNT():
SELECT COUNT(*) FROM post_record WHERE url = ?

A: SELECT COUNT(*) FROM post_record WHERE url = user_inputted_value

A: Is this correct?
    $result = mysqli_query("SELECT url from post_data where url='".$url."' and id='".$id."'");
        if ($url = @mysqli_fetch_array($result))
        {
            // do nothing
        }
        else
        {
            //insert url details
        }
            //After this fetch data from table to show preview


text:
Q: Castor XML Mapping and java.util.Map I've been using Castor these past couple of days to try to get a little serialization going between my Java program and XML in a readable way.  Though it has a few faults, Castor's automatic xml generation via reflection is actually very functional.  Unfortunately, one thing that seems to be fairly well left out of the examples is dealing with generics.  It seems the reflection API does a wonderful job as it is, but as it is inadvertently grabbing a lot of redundant data just because methods start with get___(), I wanted to write my own mapping file to stave this off.
Firstly, it seems altogether fair that in the attributes to a "field" element, one should define "type".  However, it does not specify what should be done if this type is abstract or simply an interface.  What should I put as the type then?
Secondly, most "collection" type objects specified in Castor (List, Vector, Collection, Set, etc) only require 1 generic type, so specifying "type" as what's inside and "collection="true"" are enough.  However, it does not specify what I should do in the case of a collection like a Map, where 2 types are necessary.  How can I specify both the key type and value type?
Any help at all would be greatly appreciated!

A: For the second of my questions:
When specifying something with a Map or a Table, you need to redefine org.exolab.castor.mapping.MapItem within the bind-xml element within your field element.  Example taken from here
<class name="some.example.Clazz">
  <field name="a-map" get-method="getAMap" set-method="setAMap">
    <bind-xml ...>
       <class name="org.exolab.castor.mapping.MapItem">
          <field name="key" type="java.lang.String">
            <bind-xml name="id"/>
          </field>
          <field name="value" type="com.acme.Foo"/>
       </class>
    </bind-xml>
  </field>
</class>

Also, omit the type attribute from the parent field element.

A: For my first question, the trick is to NOT specify the type in the field element and allow Castor to infer it by itself.  If you have definitions for the classes that could appear there, then it will automatically use those.  For example:
<class name="some.example.Clazz">
    <!-- can contain condition1 or condition2 elements -->
    <field name="condition" collection="arraylist" required="true">
        <bind-xml name="condition" node="element" />
    </field>
</class>

<class name="some.example.condition1">
    <field name="oneField" >
        <xml-bind name="fieldOne" />
    </field>
</class>

<class name="some.example.condition2">
    <field name="anotherField />
        <xml-bind name="fieldTwo" />
    </field>
</class>

The output of into XML by Castor would use condition1 and condition2 style XML into the "condition" field of Clazz while still referring to its proper instantiation type.


text:
Q: Selenium Webdrive (VBA) - find an element's attribute, where there are duplicate attributes of the same name I am trying to store the value "1234567!1234567" from the attribute data-orderid in a cell within my worksheet
The code I'm using in VBA is:
Cells(x,y) = d.FindElementByXPath("/html/body/table[3]/tr[@class='report']").getAttribute("data-orderid").Text

And this is an example of the HTML code I am trying to get the info from:

...

...
`

The expected output is "1234567!1234567" but the error: NoSuchElementError, ElementNotFound pops up as I try to run my code

A: Try the following. The method for selenium vba is Attribute
d.findElementByCss("[data-index='1']").Attribute("data-orderid")

You don't need .text on the end.


text:
Q: Push array into Object JavaScript I have an array of objects
 let x =[
    {
       name: x
       ratings:[
          {
             comment: 'something here',
            stars:'5',
          },

        ]
    },...]

In ratings i have to push more comments and stars:
 let newX = [
     {
          {
             comment: 'lalalalalalalal',
             stars:'4',
          },
          {
             comment: 'good',
             stars:'3',
          },
 },]

I am actually in a for loop, so I have x[i]; I have to push newX into x[i]. So I am doing x[i].ratings.push(newX) but I am getting 'push is not a function'
Any help?
Thank you.

A: As you said, x is an array, so x.ratings doesn't mean a lot. Do you want to add newX to rating inside the first element in x? If so, this is how you do it:
x[0].ratings.push(newX)


text:
Q: parse error (possibly incorrect indentation or mismatched brackets) in Haskell When I compile this code in GHC, the program tells me "parse error (possibly incorrect indentation or mismatched brackets)"
...
camino :: (Ix v,Num p) =>(Grafo v p) -> v -> v -> Bool
camino  g o d
    | d == o = True
    | otherwise = esta d (camino_rf g o d (adyacentes g o)
...

I think I'm using the correct identation.
Thank's a lot for your help.

A: The line starting with otherwise has too few closing parentheses.


text:
Q: Может ли внешний ключ одновременно являться первичным ключом? MySQL Вот схема БД и получается, что в таблицах "Журнал покупок" и "Журнал поставок" primery key совпадает с foreign key

A: Уточним термины. Внешний ключ это ограничение, которое вы накладываете на значения одного поля или нескольких полей. СУБД проверяет всё, что вы пытаетесь в них записать. Ваши значения должны встречаться среди значений похожих полей в другой таблице.
Это помогает сохранить целостность базы, когда у вас есть несколько связанных таблиц.
При этом — важный момент — поля в другой таблице должны быть уникальным ключом. Это нужно для производительности. Вы должны собрать их в индекс, и указать, что этот индекс уникальный, после этого внешний ключ может быть создан.
Итак, если у вас есть таблица, на которую наложено ограничение foreign key. Если связь между таблицами один к одному, эти поля очевидно будут уникальны.
Первичный ключ тоже должен быть уникальным. Очень часто в качестве первичного ключа используют не естественный ключ, а суррогатный — целое поле, значения в котором образуют натуральный ряд 1, 2, 3, ... Но вы можете не добавлять поле, которое используется только в качестве суррогатного ключа, если у вас всё равно уже есть поле, значения в котором гарантированно уникальны.
Таким образом да, можно взять поля в таблице, на которые наложено ограничение внешний ключ и сделать из них первичный ключ, потому что значения в этих полях гарантированно уникальны.
Стоит ли так делать? Иногда да, иногда нет. Обычно такое решение должно что-то подсказывать программисту, который поддерживает программу. В вашем примере, как я понимаю, программист пытался сказать, что каждый товар в каждой покупке может встречаться один раз. Но я бы не стал делать такой ключ, потому что журнал это независимая сущность, у которой должен быть свой, независимый ключ.
Другое дело, когда речь идёт о связи 1 к 0 или 1. Она часто встречается, когда вы пытаетесь сохранить небольшую иерархию классов в нескольких таблицах. В этом случае внешний ключ, который используется в качестве первичного ключа, подчёркивает глубокую связь между таблицами. Вы как-бы говорите, что речь идёт о большом составном объекте, в котором могут отсутствовать некоторые части. Вы раскладываете эти части в несколько таблиц, потому что так правильно с точки зрения реляционного метода, но при этом подчёркиваете, что где-то на уровень выше эти значения будут собраны в единое целое.
В этом случае первичный ключ из поля, на которое наложено ограничение *внешний ключ — прекрасная подсказка.

A: Вы неправильно интерпретируете диаграмму или употребляете неточную терминологию. Тут внешний ключ не совпадает с первичным ключом.
В таблице Журнал Покупок первичный ключ составной, т.е. состоит из двух полей (id_покупки, id_товара). Знак ключа означает является частью первичного ключа, а не является первичным ключом.
А на каждом из этих полей по отдельности есть два внешних ключа на соответствующие таблицы.
Эта абсолютно нормальная практика реализации отношения многие ко многим.
Если же говорить о том, о чем говорится в заголовке вопроса, т.е. может ли какой-то набор колонок быть одновременно и первичным и внешним ключом, то безусловно может.
Это используется для реализации отношения целое-часть, когда часть не имеет собственной идентичности, т.е. всегда используется в контексте целого.

A: Ответ на может или нет? - Может. Реализация объектной модели, а не реляционной иначе говоря
Ваш класс расширение какого-то родительского класса. Это самое простое применение и всё дальнейшее исходит из этой модели.


text:
Q: ScrollTop between 3 vertically aligned divs won't work from MID to BOT and glitches from BOT to MID UPDATE: I have tried removing the viewport size for some of the elements, and removing some of the features, but I am still experiencing the same behavior described in the 5 steps, therefor still looking for any advice.
Latest fiddle iteration
I have no clue why this is happening. I have 3 divs on top of each other and a fixed navigation. I'm using scrollTop: $("#targetDIV").offset().top - 100 to get to the each of the three divs. The scrollTop is called from one of three .click() functions; one per button.
You should be able to simulate the issue Im describing in the title by following these steps:
JSFiddle here

*

*Click on "Mid DIV" button and you're taken to the middle div with "Content of mid div"

*Now click on "Last DIV" button and nothing should happen

*REFRESH THE PAGE

*Click on "Last DIV" button and you will be taken to the last div with "Last div content"

*Now click on "Mid DIV" button and instead of to the middle div it goes straight to the top div with "this is the top level"

From the top div I can get to MID and BOT completely fine.
I'd greatly appreciate if you could tell me what am I missing,
or what could be possibly causing this weird behavior.

A: When info_overlay is scrolled, the offset().top of its children changes.
An alternative method is to save the offset().top of all its children before it is scrolled, then use the saved values for animating.
Also, since the children's IDs are related to the "btn" classnames, you can write one click handler instead of three:
$('.inf_con_block').each(function() {
  $(this).data('offset', $(this).offset().top - 100);
});

$('.inav_btn').click(function() {
  var d = '#con_'+$(this).attr('class').split('btn_')[1];
  $('#info_overlay').animate({
    scrollTop: $(d).data('offset')
  }, 1000);
});

Working Fiddle #1

Update
This can actually be done more simply.  Just add the scrollTop of info_overlay, and that will "offset" the offset().top of its children:
$('.inav_btn').click(function() {
  var d = '#con_'+$(this).attr('class').split('btn_')[1];
  $('#info_overlay').animate({
    scrollTop: ($(d).offset().top - 100) + $('#info_overlay').scrollTop()
  }, 1000);
});

Working Fiddle #2


text:
Q: Pandas: Passing format options into functions I want to extract coordinates from postcodes as a new df column.
The functionality from the geopy module is:
from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.geocode('%s tn6 3rn')

print((location.latitude, location.longitude))
(51.0459837, 0.2192646)

My function to apply to this to a single value works:
def pcodeToCoor(x):
    geolocator = Nominatim()
    location = geolocator.geocode(x)
    return ((location.latitude, location.longitude))

pcodeToCoor('%s tn6 3rn')
(51.0459837, 0.2192646)

But when passing the function to a test df:
    name    postcode
0   jd      tn6 3rn
1   hf      en6 1dg
2   ss      sw17 0ju

df['coordinate'] = df['postcode'].map(pcodeToCoor)

I get AttributeError: 'NoneType' object has no attribute 'latitude. Note I can recreate this error by removing %s from the basic api functionality.
The question is, how do I use %s in my function? I imagine the answer's very simple but nothing I've tried works!

A: You could do something like this if you are going to use this function consistently this way, or you code code a check to see if your string starts with "%s".
def pcodeToCoor(x):
    geolocator = Nominatim()
    location = geolocator.geocode('%s '+x)
    return ((location.latitude, location.longitude))

Edit:
def pcodeToCoor(x):
    if x[0:2] != '%s':
        x = '%s ' + x
    geolocator = Nominatim()
    location = geolocator.geocode(x)
    return ((location.latitude, location.longitude))

Test:
pcodeToCoor('%s tn6 3rn')

Output:
(51.0459837, 0.2192646)

Test 2:
df['postcode'].map(pcodeToCoor)

Output:
0     (51.0459837, 0.2192646)
1    (51.7206134, -0.2042041)
2    (51.3866947, -0.1800573)
Name: postcode, dtype: object


text:
Q: Is there an easy way to run DataFrames::by in parallel? I have a large dataframe I want to compute on in parallel. The call I want to parallelize is
df = by(df, [:Chromosome], some_func)

Is there a way to easily parallelize this? Preferably without any copying.
Also, I guess the kinds of parallelization used should be different depending on the size of the groups created by by.

Minimal reproducible example to use in answers:
using DataFrames, CSV, Pkg
iris = CSV.read(joinpath(Pkg.dir("DataFrames"), "test/data/iris.csv"))
iris_count = by(iris, [:Species], nrow)

A: On Windows run in console (adjust to the number of cores/threads you have):
$ set JULIA_NUM_THREADS=4
$ julia

On Linux run in console:
$ export JULIA_NUM_THREADS=4
$ julia

Now check if it works:
julia> Threads.nthreads()
4

Run the code below (I update your code to match Julia 1.0):
using CSV, DataFrames, BenchmarkTools
iris = CSV.read(joinpath(dirname(pathof(DataFrames)),"..","test/data/iris.csv"))
iris.PetalType = iris.PetalWidth .> 2;  #add an additional column for testing

Let us define some function that operates on a part of a DataFrame
 function nrow2(df::AbstractDataFrame)
     val = nrow(df)
     #do something much more complicated...
     val
 end

Now the most complicated part of the puzzle comes:
function par_by(df::AbstractDataFrame,f::Function,cols::Symbol...;block_size=40)
    #f needs to be precompiled - we precompile using the first row of the DataFrame.
    #If try to do it within @thread macro
    #Julia will crash in most ugly and unexpected ways
    #if you comment out this line you can observe a different crash with every run
    by(view(df,1:1),[cols...],f);

    nr = nrow(df)
    local dfs = DataFrame()
    blocks = Int(ceil(nr/block_size))
    s = Threads.SpinLock()
    Threads.@threads for block in 1:blocks
        startix = (block-1)*block_size+1
        endix = min(block*block_size,nr)
        rv= by(view(df,startix:endix), [cols...], f)
        Threads.lock(s)
        if nrow(dfs) == 0
            dfs = rv
        else
            append!(dfs,rv)
        end
        Threads.unlock(s)
    end
    dfs
end

Let's test it and aggregate the results
julia> res = par_by(iris,nrow2,:Species)
6×2 DataFrame
│ Row │ Species    │ x1    │
│     │ String     │ Int64 │
├─────┼────────────┼───────┤
│ 1   │ versicolor │ 20    │
│ 2   │ virginica  │ 20    │
│ 3   │ setosa     │ 10    │
│ 4   │ versicolor │ 30    │
│ 5   │ virginica  │ 30    │
│ 6   │ setosa     │ 40    │

julia> by(res, :Species) do df;DataFrame(x1=sum(df.x1));end
3×2 DataFrame
│ Row │ Species    │ x1    │
│     │ String     │ Int64 │
├─────┼────────────┼───────┤
│ 1   │ setosa     │ 50    │
│ 2   │ versicolor │ 50    │
│ 3   │ virginica  │ 50    │

The par_by also supports multiple columns
julia> res = par_by(iris,nrow2,:Species,:PetalType)
8×3 DataFrame
│ Row │ Species   │ PetalType │ x1    │
│     │ String    │ Bool      │ Int64 │
├─────┼───────────┼───────────┼───────┤
│ 1   │ setosa    │ false     │ 40    │
⋮
│ 7   │ virginica │ true      │ 13    │
│ 8   │ virginica │ false     │ 17    │

@Bogumił Kamiński commented that it is reasonable to use groupby() before threading. Unless for some reason groupby cost is to high (requires full scan) this is the recommended way - makes the aggregation simpler.
 ress = DataFrame(Species=String[],count=Int[])
 for group in groupby(iris,:Species)
     r = par_by(group,nrow2,:Species,block_size=15)
     push!(ress,[r.Species[1],sum(r.x1)])
 end

 julia> ress
 3×2 DataFrame
 │ Row │ Species    │ count │
 │     │ String     │ Int64 │
 ├─────┼────────────┼───────┤
 │ 1   │ setosa     │ 50    │
 │ 2   │ versicolor │ 50    │
 │ 3   │ virginica  │ 50    │

Note that in the example above are only three groups so we parallelize over each group. However, if you have big number of groups you could consider running:
function par_by2(df::AbstractDataFrame,f::Function,cols::Symbol...)
    res = NamedTuple[]
    s = Threads.SpinLock()
    groups = groupby(df,[cols...])
    f(view(groups[1],1:1));
    Threads.@threads for g in 1:length(groups)
        rv= f(groups[g])
        Threads.lock(s)
        key=tuple([groups[g][cc][1] for cc in cols]...)
        push!(res,(key=key,val=rv))
        Threads.unlock(s)
    end
    res
end

julia> iris.PetalType = iris.PetalWidth .> 2;

julia> par_by2(iris,nrow2,:Species,:PetalType)
4-element Array{NamedTuple,1}:
 (key = ("setosa", false), val = 50)
 (key = ("versicolor", false), val = 50)
 (key = ("virginica", true), val = 23)
 (key = ("virginica", false), val = 27)

Let me know if it worked for you.
Since more people might have similar problem I will make this code into a Julia package (and that is why I kept this code to be very general)

A: Start julia with julia -p 4 then run
using CSV, DataFrames

iris = CSV.read(joinpath(dirname(pathof(DataFrames)),"..","test/data/iris.csv"))

g = groupby(iris, :Species)

pmap(nrow, [i for i in g])

This will run groupby in parallel.


text:
Q: Override function in a module with complex file tree I have a module module containing 2 functions a and b splited into 2 different files m1.py and m2.py.
The module's file tree:
module/
    __init__.py
    m1.py
    m2.py

__init__.py contains:
from .m1 import a
from .m2 import b

m1.py contains:
def a():
    print('a')

m2.py contains:
from . import a

def b():
   a()

Now, I want to override the function a in a main.py file, such that the function b uses the new function a. I tried the following:
import module

module.a = lambda: print('c')
module.b()

But it doesn't work, module.b() still print a.

A: I found a solution, that consists in not importing with from . import a but with import module.
m2.py becomes:
import module

def b():
    module.a()


text:
Q: BNO055 no sensor data, but address can be found I'm trying to use the BNO055 sensor in my project. It's hard for me to get the sensor as a seperate IC so I buy BNO055 modules and take the ICs from the modules by heating with hot air.

In my designs I follow the Bosch BNO055 datasheet, so the schematic of the BNO055 part of my board is the same as in the picture below:

I have successfully soldered the BNO055 IC with solder paste (cream solder?) and hot air multiple times now. And got it to work with the STM32F446RET6 microcontroller on my board.
Now I will talk about 3 seperate BNO055 sensors that caused trouble for me.
This first sensor worked for a couple of weeks but recently has stopped working due to a short circuit on the board (I assume). The cause of the short circuit was the microcontroller on the board. Only reason I can think for the microcontroller to break is dust.
On this board I had I2C pull-up resistors connected to 3.3 V for the BNO055. The sensor had seperate I2C connections from the other sensors on the board.
I took the sensor out and soldered it back to the purple module board and with the Arduino I2C scanner I could find the I2C address, but when I uploaded example code for sensor data it didn't work.
But for now let's forget about this one. As I mentioned, the board this was working on had a short circuit.
On another board I had a 3.3 V pull-up and a 5 V pull-up on the same I2C lines at the same time. This was a board for the ATmega2560 (5 V logic level). I soldered the BNO055 and the address could be found, but no sensor data again. I took out the 5 V pull-ups but it still didn't work.
On yet another board I had 5 V and 3.3 V pull-ups at the same time again on the same I2C line again, but the sensor didn't work at all with a 3.3 V logic microcontroller. I took out the sensor and soldered it to the module board and it works completely fine.
I thought the 2nd sensor stopped working because of the 5 V and 3 V pull-up sensors existing at the same time but the 3rd sensor didn't do the same.
I'm so confused. Why do my sensors work and not work at the same time?
How can I find the address but read no data?
Sorry if my explanation was too much but I tried to give as much detail because usually people complain that I don't give enough detail in the posts.

A: The BNO055 was originally embedded to our PCB with STM32F446RET6.
Apparently my friend which was responsible for software forgot to change the output voltage of the pin that was connected to RESET of BNO055.
By default the pin is set to LOW voltage by the IDE. So we were constantly giving LOW voltage to RESET pin of BNO055 so it didn't work when we tried to use the embedded sensor on the PCB.
When we changed it to HIGH the problem was fixed.


text:
Q: Python - How to send numerical values via Selenium Send Keys I have an Excel spreadsheet that has numerical values that I am trying to type into the Bing search engine via Selenium Send Keys. Whenever I try to run the code it gives me an error
TypeError: object of type 'numpy.int64' has no len()

I am able to send alphanumeric strings and alphabetical strings but just not numerical values alone. How can I resolve this?
data = pd.read_excel(excel_file, sheet_name= "Sample")
value1 = data["Number"][1]
browser.get('https://www.bing.com')
browser.find_element_by_xpath('//*[@id="sb_form_q"]').send_keys(value1)

A: When you enter keys into an INPUT or any other tag type on the webpage, you are entering text (string) and not an int anyway. Just either change the type to string in your Excel sheet or convert it to string when you .send_keys().
browser.find_element_by_xpath('//*[@id="sb_form_q"]').send_keys(str(value1))

BTW, if you are going to have an XPath locator that just looks for an ID, you should use .find_element_by_id("sb_form_q"). It will be faster, easier to read, better supported, etc.


text:
Q: does gcutil addsnapshot replace existing ones? The documentation states that gcutil addsnapshot will create a new snapshot.
My question is:
If a snapshot with the same name already exists, will it replace that snapshot?

A: Although this is an old case, I'll try to answer it:
No, it won't replace that snapshot. The snapshot cannot be updated. You need to choose another name or you will get the following error message:
ERROR: RESOURCE_ALREADY_EXISTS: The resource 'projects/<project>/global/snapshots/<snapshot>' already exists

Regarding your questions in the comment, new snapshots are created based on previous snapshots.
I'm not totally sure but I think that you are charged for the number of GB you see in the Developers Console in the 'SIZE' column. Right now, every GB costs $0.124 per month as you can see at https://cloud.google.com/compute/#pricing
Regards


text:
Q: Print out TableView Data as table (not image) with custom formating using java Please help if you can otherwise skip.
I am developing a software using JavaFX. I have a TableView which I want to printout in Landscape A4 page with custom formatting. My table will contain huge rows, so it is necessary that the table must split into multiple pages. I have searched on the web but not getting the proper solution. I found many posts which does not meet my requirement.
I have a jfx table created with observable list like this:

And I want to print this table as like below:

Any idea how to do this?

A: This can be easily done with Jasper Reports Library. I found my solution using this library.


text:
Q: Generate excel file and export data can anybody help me to generate excel file in asp .net core and export model class on it? I am adding what i have tried but dont know whether its a right approach or not
[HttpPost]
    public IActionResult ExportExcel()
    {
        var myField = typeof(Cover).GetType().GetProperties();
        using (var workbook = new XLWorkbook())
        {
            var worksheet = workbook.Worksheets.Add("Excel1");
            var currentRow = 1;
            for (int i = 0; i < myField.Length; i++)
            {
                worksheet.Cell(currentRow, i + 1).Value = myField[i].Name;

            }
            using (var stream = new MemoryStream())
            {
                workbook.SaveAs(stream);
                var content = stream.ToArray();
                return File(
                    content,
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "users.xlsx");
            }
        }
    }

A: Here is the whole working demo:
Model:
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Controller:
[HttpGet]
public IActionResult ExportExcel()
{
    Student s = new Student();
    var data = new List<Student>() {
        new Student(){ Id=1,Name="aaa"},
        new Student(){ Id=2,Name="bbb"},
        new Student(){ Id=3,Name="ccc"},
    };

    var myField = s.GetType().GetProperties();

    using (var workbook = new XLWorkbook())
    {
        var worksheet = workbook.Worksheets.Add("Excel1");
        var currentRow = 1;
        for (int i = 0; i < myField.Length; i++)
        {
            worksheet.Cell(currentRow, i + 1).Value = myField[i].Name;
        }

        for (int index = 1; index <= data.Count; index++)
        {
            worksheet.Cell(index + 1, 1).Value = data[index - 1].Id;
            worksheet.Cell(index + 1, 2).Value = data[index - 1].Name;
        }

        using (var stream = new MemoryStream())
        {
            workbook.SaveAs(stream);
            var content = stream.ToArray();
            return File(
                content,
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "users.xlsx");
        }
    }
}

Result:


text:
Q: prevent certain column values from returning when calling an active record instance (without limiting access to them in future) I have a database which is postgis enabled which has some records (in a given table, there are many) that have enormous :spatial column values.
I often use the awesome_print gem to view records quickly while working. It colorizes and nicely displays a given record (or records') information for quick review. The problem in this case is that 99% of the terminal display is devoting to showing these spatial column's multi-page length list of coordinates in the WKT format.
I'd like for activerecord to not return these objects when viewing these with the ap (awesome print) command. Is there any way to do that without breaking something else? Can I just instruct ActiveRecord to hide these column's values unless specifically requested or is that too much to ask?

A: One way or another you need to designate which fields to print, or not to print. For instance you could define a helper for this and put it, say, in the your console config file, e.g.:
def ap_article(article, cols=%w[col1 col2 col3])
  ap article.attributes.slice(*cols)
end

or perhaps something like this if you just want to ignore the spatial columns
def ap_article(article)
  cols = article.class.columns.select {|c| c.type != :spatial}.map(&:name)
  ap article.attributes.slice(*cols)
end


text:
Q: Assistance needed - Map does not load properly in JQuery UI Tabs - NOT A DUPLICATE None of the "Answers" from the other post resolve my issue.  Please Read My Post and Attempt to guide me in the right direction
EDIT - EDIT - EDIT
I have updated the java script to include the recommended function
I have included the HTML here for those who do not like jsfiddle
I have read tons of questions and answers here and I cannot get my Google Map to load properly in the JQueryUI Tab that it is called in.
I understand that the map must load first but I am not able to get the Tab to load then return to the Home tab.  I have tried the Off Left Technique to no avail.
I need help.  A fresh set of Eyes would be extremely Helpful.
Any help would be greatly appreciated as I am extremely far behind on this project.
Please review the jsfiddle referenced below, and tell me where I am going wrong.  I am at my whits end and really could use a little intervention with this.  One of you Java/jqueryui Guru's surely can see where i am going wrong with a quick little peak.
The issue is on the LOCATION Tab
The jsfiddle - http://jsfiddle.net/hughesjoseph/hNKPY/
The test site http://l2technotes.dyndns.org
Loads correctly if you go to address/#tabs-4
Complete Java Script
        (function (mapDemo, $, undefined) {
    mapDemo.Directions = (function () {
        function _Directions() {
            var map,
            directionsService, directionsDisplay,
            autoSrc, autoDest, pinA, pinB,

            markerA = new google.maps.MarkerImage('images/car.png'),
                markerB = new google.maps.MarkerImage('images/gmaplogo.png'),

            // Caching the Selectors
                $Selectors = {
                    mapCanvas: jQuery('#mapCanvas')[0],
                    dirPanel: jQuery('#directionsPanel'),
                    dirInputs: jQuery('.directionInputs'),
                    dirSrc: jQuery('#dirSource'),
                    dirDst: jQuery('#dirDestination'),
                    getDirBtn: jQuery('#getDirections'),
                    dirSteps: jQuery('#directionSteps'),
                    paneToggle: jQuery('#paneToggle'),
                    useGPSBtn: jQuery('#useGPS'),
                    paneResetBtn: jQuery('#paneReset')
                },

                autoCompleteSetup = function () {
                    autoSrc = new google.maps.places.Autocomplete($Selectors.dirSrc[0]);
                    autoDest = new google.maps.places.Autocomplete($Selectors.dirDst[0]);
                }, // autoCompleteSetup Ends

                directionsSetup = function () {
                    directionsService = new google.maps.DirectionsService();
                    directionsDisplay = new google.maps.DirectionsRenderer({
                        suppressMarkers: true
                    });

                    directionsDisplay.setPanel($Selectors.dirSteps[0]);
                }, // direstionsSetup Ends

                trafficSetup = function () {
                    // Creating a Custom Control and appending it to the map
                    var controlDiv = document.createElement('div'),
                        controlUI = document.createElement('div'),
                        trafficLayer = new google.maps.TrafficLayer();

                    jQuery(controlDiv).addClass('gmap-control-container').addClass('gmnoprint');
                    jQuery(controlUI).text('Traffic').addClass('gmap-control');
                    jQuery(controlDiv).append(controlUI);

                    // Traffic Btn Click Event
                    google.maps.event.addDomListener(controlUI, 'click', function () {
                        if (typeof trafficLayer.getMap() == 'undefined' || trafficLayer.getMap() === null) {
                            jQuery(controlUI).addClass('gmap-control-active');
                            trafficLayer.setMap(map);
                        } else {
                            trafficLayer.setMap(null);
                            jQuery(controlUI).removeClass('gmap-control-active');
                        }
                    });
                    map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);
                }, // trafficSetup Ends

                mapSetup = function () {
                    map = new google.maps.Map($Selectors.mapCanvas, {
                        zoom: 16,
                        center: new google.maps.LatLng(32.565243, -97.130531),

                        mapTypeControl: true,
                        mapTypeControlOptions: {
                            style: google.maps.MapTypeControlStyle.DEFAULT,
                            position: google.maps.ControlPosition.TOP_RIGHT
                        },

                        panControl: true,
                        panControlOptions: {
                            position: google.maps.ControlPosition.RIGHT_TOP
                        },

                        zoomControl: true,
                        zoomControlOptions: {
                            style: google.maps.ZoomControlStyle.LARGE,
                            position: google.maps.ControlPosition.RIGHT_TOP
                        },

                        scaleControl: true,
                        streetViewControl: true,
                        overviewMapControl: true,

                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    });

                    var marker1 = new google.maps.Marker({
                        position: new google.maps.LatLng(32.565243, -97.130531),
                        map: map,
                        icon: markerB
                    });

                    autoCompleteSetup();
                    directionsSetup();
                    trafficSetup();
                }, // mapSetup Ends

                directionsRender = function (source, destination) {
                    $Selectors.dirSteps.find('.msg').hide();
                    directionsDisplay.setMap(map);

                    var request = {
                        origin: source,
                        destination: destination,
                        provideRouteAlternatives: false,
                        travelMode: google.maps.DirectionsTravelMode.DRIVING
                    };

                    directionsService.route(request, function (response, status) {
                        if (status == google.maps.DirectionsStatus.OK) {

                            directionsDisplay.setDirections(response);

                            var _route = response.routes[0].legs[0];

                            pinA = new google.maps.Marker({
                                position: _route.start_location,
                                map: map,
                                icon: markerA
                            });
                        }
                    });
                }, // directionsRender Ends

                fetchAddress = function (p) {
                    var Position = new google.maps.LatLng(p.coords.latitude, p.coords.longitude),
                        Locater = new google.maps.Geocoder();

                    Locater.geocode({
                        'latLng': Position
                    }, function (results, status) {
                        if (status == google.maps.GeocoderStatus.OK) {
                            var _r = results[0];
                            $Selectors.dirSrc.val(_r.formatted_address);
                        }
                    });
                }, // fetchAddress Ends

                invokeEvents = function () {
                    // Get Directions
                    $Selectors.getDirBtn.on('click', function (e) {
                        e.preventDefault();
                        var src = $Selectors.dirSrc.val(),
                            dst = $Selectors.dirDst.val();

                        directionsRender(src, dst);
                    });

                    // Reset Btn
                    $Selectors.paneResetBtn.on('click', function (e) {
                        $Selectors.dirSteps.html('');
                        $Selectors.dirSrc.val('');
                        $Selectors.dirDst.val('');

                        if (pinA) pinA.setMap(null);
                        if (pinB) pinB.setMap(null);

                        directionsDisplay.setMap(null);
                    });

                    // Toggle Btn
                    $Selectors.paneToggle.toggle(function (e) {
                        $Selectors.dirPanel.animate({
                            'left': '-=305px'
                        });
                        jQuery(this).html('>');
                    }, function () {
                        $Selectors.dirPanel.animate({
                            'left': '+=305px'
                        });
                        jQuery(this).html('<');
                    });

                    // Use My Location / Geo Location Btn
                    $Selectors.useGPSBtn.on('click', function (e) {
                        if (navigator.geolocation) {
                            navigator.geolocation.getCurrentPosition(function (position) {
                                fetchAddress(position);
                            });
                        }
                    });
                }, //invokeEvents Ends

                _init = function () {
                    mapSetup();
                    invokeEvents();
                }; // _init Ends

            this.init = function () {
                _init();
                return this; // Refers to: mapDemo.Directions
            };
            return this.init(); // Refers to: mapDemo.Directions.init()
        } // _Directions Ends
        return new _Directions(); // Creating a new object of _Directions rather than a function
    } ()); // mapDemo.Directions Ends
})(window.mapDemo = window.mapDemo || {}, jQuery);
var mapFirstClick = false;
$("#maptab").click(function () {
    mapFirstClick || setTimeout(function () {
        google.maps.event.trigger(map, 'resize');
        mapFirstClick = true;
        map.setCenter(32.565243, -97.130531);
    }, 250);
});
function PrintElem(elem) {
    Popup($(elem).html());
}
function Popup(data) {
    var mywindow = window.open('', 'my div', 'height=600,width=800');
    mywindow.document.write('<title>Driving Directions to Electrolysis by Bridgett</title>');
    mywindow.document.write('');
    mywindow.document.write(data);
    mywindow.document.write('');
    mywindow.print();
    mywindow.close();
    return true;
}
$(function () {
    $("#tabs").tabs();
});
$(function () {
    $("#accordion").accordion({
        collapsible: true,
        active: false,
        heightStyle: "content"
    });
});

Pertinent HTML

        <meta charset="utf-8">
        <title>Electrolysis by Bridgett</title>

        <link rel="shortcut icon" href="images/beLogoColor3D.png" />
        <link href="css/style.css" rel="stylesheet" type="text/css" />

 Location

                        <form>

                                Driving From :

                                <input type="text" value="" id="dirSource" style="width:98%;" />

                            <input type="hidden" value="1003 E. Broad St., 76063" id="dirDestination" />

Get Directions to
Electrolysis by Bridgett

                                <input type="button" value="Print Directions" onclick="PrintElem('#directionSteps')" />

                        </form>

Step by Step Directions Appear Here

A: I've had this problem too:
google.maps.event.trigger(map, 'resize');

trigger this when tab is done fading in (default after 250 ms). This piece of code worked for me:
        var mapFirstClick = false;
        $("#tabMap").click(function() {
            mapFirstClick || setTimeout(function() {
                google.maps.event.trigger(map, 'resize');
                mapFirstClick = true;
                map.setCenter(latLng);
            }, 250);
        });


text:
Q: First word from every line Hi i have this code that prints last word of every line , i want something that do exactly that this code does but with first word (don't mock me i'm not a programmer)
private static void readFile1(String in, String out) throws IOException
{
    FileInputStream fis = new FileInputStream(new File(in));

    BufferedReader br = new BufferedReader(new InputStreamReader(fis));

    BufferedWriter writer = null;

    writer = new BufferedWriter(new OutputStreamWriter(
          new FileOutputStream(out), "utf-8"));

    String line = null;
    while ((line = br.readLine()) != null)
    {
        if(line.length() > 0)
        {
            String[] words = line.split("\\s+");
            //System.out.println(words[words.length - 1]);
            writer.write(words[words.length - 1]);
            writer.newLine();
        }
    }

    br.close();
    writer.close();
    fis.close();
}

A: Instead of:
writer.write(words[words.length - 1]);

Use
writer.write(words[0]);//assuming you wont have empty line.

if you could have empty line, then try using:
if (words.length != 0) {
    writer.write(words[0]);
}

A: Replace :
writer.write(words[words.length - 1]);

with :
writer.write(words[0]);

Cheers!

A: Replace:
writer.write(words[words.length - 1]);
With: writer.write(words[0]);
Or use:
while((line = br.hasNextLine()))
    {...
        writer.write(words[0]);
    ...}


text:
Q: PM2 Cluster Mode. Execution on one process blocks the event loop on other processes as well I am using PM2 in cluster mode and have 2 instances of my node.js application running. I have some long executing cron jobs (about 30 seconds) that I am trying to run. I am placing an if statement before the execution of the cron jobs to ensure that they only run on the first process via
if (process.env.NODE_APP_INSTANCE === 0) {
    myCronFunction()
}

The goal was that since there are two processes, and PM2 should be load balancing them, if the cron job executes on process one, then process two would still be available to respond to the request. I am not sure what's going on, if PM2 is not successfully load balancing them, or what. But when my cron job executes on instance one, instance two is still not responding to requests until after the job on instance one finishes executing.
I'm not sure why that is. It is my understanding that they are supposed to be completely independent of one another.
Anyone have any ideas?


text:
Q: android app crashing after home button tapped I have an app that crashes if i press the home button,
back button goes fine to the dashboard, but if I press home it crashes with:

07-02 16:50:51.834: E/AndroidRuntime(343): java.lang.RuntimeException:
  Unable to pause activity
  {com.rt.paging/com.rt.paging.MKpagerActivity}:
  java.lang.NullPointerException

this is my code
public class MKpagerActivity extends FragmentActivity {

    private PagerAdapter mPagerAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

      //initialsie the pager
            this.initialisePaging(); //crea un metodo! y lo implementa abajo!
    }

    /**
     * Initialise the fragments to be paged
     */
    private void initialisePaging() {

        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this, Fragmen1.class.getName()));
        fragments.add(Fragment.instantiate(this, Fragmen2.class.getName()));
        this.mPagerAdapter  = new com.orchard.paging.PagerAdapter(super.getSupportFragmentManager(), fragments); //por que hay q decirle el paquete??

        //
        ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager);
        pager.setAdapter(this.mPagerAdapter);

    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        // your stuff or nothing
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // your stuff or nothing
    }

}

this is my logCat
07-02 17:15:11.545: E/AndroidRuntime(327): FATAL EXCEPTION: main
07-02 17:15:11.545: E/AndroidRuntime(327): java.lang.RuntimeException: Unable to pause activity {com.orchard.paging/com.orchard.paging.MKpagerActivity}: java.lang.NullPointerException
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2354)
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2311)
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:2291)
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.app.ActivityThread.access$1700(ActivityThread.java:117)
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:938)
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.os.Looper.loop(Looper.java:123)
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.app.ActivityThread.main(ActivityThread.java:3683)
07-02 17:15:11.545: E/AndroidRuntime(327):  at java.lang.reflect.Method.invokeNative(Native Method)
07-02 17:15:11.545: E/AndroidRuntime(327):  at java.lang.reflect.Method.invoke(Method.java:507)
07-02 17:15:11.545: E/AndroidRuntime(327):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-02 17:15:11.545: E/AndroidRuntime(327):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-02 17:15:11.545: E/AndroidRuntime(327):  at dalvik.system.NativeStart.main(Native Method)
07-02 17:15:11.545: E/AndroidRuntime(327): Caused by: java.lang.NullPointerException
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1576)
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.support.v4.app.FragmentManagerImpl.saveAllState(FragmentManager.java:1617)
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.support.v4.app.FragmentActivity.onSaveInstanceState(FragmentActivity.java:481)
07-02 17:15:11.545: E/AndroidRuntime(327):  at com.orchard.paging.MKpagerActivity.onSaveInstanceState(MKpagerActivity.java:50)
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.app.Activity.performSaveInstanceState(Activity.java:1037)
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1181)
07-02 17:15:11.545: E/AndroidRuntime(327):  at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2336)
07-02 17:15:11.545: E/AndroidRuntime(327):  ... 12 more

So, what Im I missing?, why the crash?
How to read what line is the offender bit of code?
thanks!

A: The problem is of the JAR file , you will need to do changes in that, or will have to get download the updated version of the jar file.
You can have a look at this answer to understand more.


text:
Q: Why can't I use a Java map to change the type of object in my stream? I'm dealing with a web-service which loads ApplicationResponse objects n at a time. I want to to make a stream which will allow me to consume all of them without having to worry about paging, hence my (incomplete) use of Java streams.

I've got a stream which generates the page numbers. I wanted to map those numbers to streams of responses using a function I had previously written.
The trouble is, it seems to want my arrow function to return an int and not the Stream which was what I was expecting.
How can I rewrite this expression so that the map operation works?

A: The IntStream.map() methods takes IntUnaryOperator as argument. As you can see in the Java documentation:

public interface IntUnaryOperator
Represents an operation on a single int-valued operand that produces an int-valued result. This is the primitive type specialization of UnaryOperator for int.

this type of Function consumes int and produces int.
As suggested by nickb, you should use the mapToObj method, which accepts IntFunction argument types (Java documentation):

public interface IntFunction
Represents a function that accepts an int-valued argument and produces a result. This is the int-consuming primitive specialization for Function.

Those can produce any type of objects.

A: Because you are using IntStream which .map method is expected to return also InstStream, in case you want to convert IntStream to usual Stream of objects you either should use .boxed() which will return you Stream of Integer, or call mapToObj() which will map your ints to some other objects using specified mapping function.


text:
Q: Is there anything like webrick for ASP.NET? This might seem a really bizarre question, but just go with me for a second.
When you install rails, you have to opportunity to test your development on webrick, a very simple web server (or you can use mongrel if you have the gem installed).
I know when developing ASP.NET you can use the built-in server that comes with Visual Studio, but I wondered if there was something you could have if you didn't have a copy of visual studio or didn't know how to configure IIS but still wanted to run an ASP.NET web application, say on your home PC or laptop.
As I said, a bizarre question, but I just thought I'd ask.

A: You could use IIS Express which is a lightweight free version of IIS.


text:
Q: regex pattern to match n leading spaces followed by a phrase I have the following regex defined which looks for the occurence
of the phrase USER NUMBER in a text file preceded by 19 spaces:
^[\\s{19}USER NUMBER]

It doesn't find a match. I know the answer must be ridiculously simple
but I just cannot seem place my finger on the solution.

A: You almost got it working, you just didn't need the character class []:
\\s{19}USER NUMBER

This will find all the places in the file where there is 19 spaces \\s{19} followed by the phrase USER NUMBER.
Your original expression:
^[\\s{19}USER NUMBER]

Matches the start-of-line ^ then it would either match a space , {, }, 1, 9, or any of the characters U, S, E, R, N, U, M, B, E, R.
This is because any character you use inside a character class [] is taken literally (well except for some special escape sequences).


text:
Q: How to combine Spring REST and WebSocket? I'm new to Spring and working on a university project.
The goal: Have a REST POST endpoint that saves data, but also sends a broadcast message using websocket.
Now, my RestController seems to be working fine, but dont really know how to implement the websocket part?
Here is how the endpoint looks like:
@PostMapping("/employees")
 Employee newEmployee(@RequestBody Employee newEmployee) {
    return repository.save(newEmployee);
 }

My previous ideas:
-Create a @Controller with a method that has @SendTo annotation?
-Can I use the @SendTo on the RestController newEmployee method?
What is the most efficient way?

A: Just like spring provides @RestController, it also provides @EnableWebSocket annotation and ways to handle bi-direction communication, below is the step by step method to create websocket connection in spring
First make a configuration class for making our WebSocketConnection class bean which will be handler for websocket connection, disconnection and message from client and add it to the WebSocketHandlerRegister with it's namespace.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfiguration implements WebSocketConfigurer {

    @Bean
    public WebSocketConnection getWebSocketConnection() {
        return new WebSocketConnection();
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        webSocketHandlerRegistry.addHandler(getWebSocketConnection(), "/websocket");
    }
}

Now let us make our WebSocketConnection class
public class WebSocketConnection  extends TextWebSocketHandler {

    private static final Logger log = LoggerFactory.getLogger(WebSocketConnection.class);

    private static final Gson gson = new GsonBuilder().create();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("connected with the websocket client : " + session.getId());
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        JsonObject parsedMessage = gson.fromJson(message.getPayload(), JsonObject.class);

        log.info("The message got from the client is " + parsedMessage);

        JsonObject responseMessage = new JsonObject();
        responseMessage.addProperty("response", "Your response was recorded by the server");
        responseMessage.addProperty("messageReceivedtime", LocalDateTime.now().toLocalDate().toString());
        int max = 100;
        int min = 20;
        responseMessage.addProperty("randomNo", (int) Math.floor(Math.random() * (max - min + 1) + min));

        session.sendMessage(new TextMessage(responseMessage.toString())); //sending message back to the client
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("connection closed from the websocket client : " + session.getId());
    }
}

and you are done here.
now from client side in javascript, you will have to make websocket client object like below
const webSocketClient = new WebSocket('ws://localhost:port/websocket');
//const webSocketClient = new WebSocket('wss://ip:port/websocket') for cases of secure connection

for more info about WebSocket client in javascript, please refer to this
https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
you mentioned your goal i.e
'Have a REST POST endpoint that saves data, but also sends a broadcast message using websocket' should not be in 1 go.
what you can do is that when user saves the data, you can return the response from the server to the user whose data has been saved, then let that user send message to the websocket server which websocket server will broadcast to other users.


text:
Q: 1151: A conflict exists with definition mcPlayer in namespace internal Every time I try to run my ActionScript 3 program, I get this error:

1151: A conflict exists with definition mcPlayer in namespace internal.

Here is my script:
package
{
    import flash.display.MovieClip;

    public class Knight extends MovieClip
    {
        var mcPlayer:MovieClip;

        public function Knight()
        {
            stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown)
            stage.addEventListener(KeyboardEvent.KEY_UP, keyUp)
        }

        private function keyUp(e:KeyboardEvent):void
        {
            trace(e.keyCode)

        }

        private function keyDown(e:KeyboardEvent):void
        {

        }
    }
}

How can I fix it?

A: If I understand things correct, your Library contains some object with class Knight and inside this object there's a child MovieClip of instance name mcPlayer. The thing is, all designed elements go to namespace public, while all the class fields/methods with no explicitly stated namespaces go to internal.
Always declare designed elements as public:
        public var mcPlayer:MovieClip;