text:
Q: Trying to access hosted SharePoint 2013 from Java app gives me 401 although I use correct OAuth token I'm trying to access our company SharePoint 2013 instance, which is hosted at ourinstance.sharepoint.com, with small Java web application.
I registered application through _layouts/15/AppRegNew.aspx this way:

*

*I let SP generate Client ID, Client Secret,

*to App Domain I set: ourdomain:8443

*to Redirect URL I set: https://ourdomain:8443/our-redirect-processing
I edited application permissions with _layouts/15/appinv.aspx, where I looked it up by client ID and edited its Permission Request XML to contain:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://insideidc.sharepoint.com/oursite/web" Right="FullControl"/>
</AppPermissionRequests>

Handler behind https://ourdomain:8443/our-redirect-processing is doing this:
JsonWebSignature jws = JsonWebSignature.parse(new JacksonFactory(), request.getParameter("SPAppToken"));
JsonParser jsonParser = new JacksonFactory().createJsonParser(jws.getPayload().get("appctx").toString());
AppCtx appCtx = jsonParser.parse(AppCtx.class, new CustomizeJsonParser());
String appctxsender=jws.getPayload().get("appctxsender").toString();
String[] splitApptxSender = appctxsender.split("@");
String sharepointServerHostName = new URL(request.getParameter("SPSiteUrl")).getHost();
String resource = splitApptxSender[0] + "/" + sharepointServerHostName + "@" + splitApptxSender[1];
AuthorizationCodeTokenRequest tokenRequest = new AuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(),
    new GenericUrl(appCtx.getSecurityTokenServiceUri()), jws.getPayload().get("refreshtoken").toString());
tokenRequest.setRedirectUri(request.getRequestURL().toString());
String aud = (String) jws.getPayload().getAudience();
tokenRequest.setClientAuthentication(new ClientParametersAuthentication(aud, secrets.get(aud)));
tokenRequest.setGrantType("refresh_token");
tokenRequest.set("resource", resource);
tokenRequest.set("refresh_token", jws.getPayload().get("refreshtoken").toString());
TokenResponse response = tokenRequest.execute();
token = response.getAccessToken();

It uses com.google.api.client. auth, http and json classes.
The token I get I use in REST call to this URL:
https://ourinstance.sharepoint.com/oursite/_api/web/getFolderByServerRelativeUrl('/thefolderIwant')/Files

with these Headers:
Accept: application/json;odata=verbose
Authorization: Bearer theToken

The response asks me for logging in, while response header has WWW-Authenticate: NTLM set.
First question: should such complex process of obtaining OAuth token end up with another credentials request?
Second and main question: how can I construct domain\username for NTLM Authenticator, which I can build, when SharePoint is hosted for us?

A: I had a similar experience when trying to access Microsoft's Project Online.
I found some helpful information from AllThatJS which pointed me in the right direction. He suggested sniffing the packets using Fiddler. Once I did that, I saw what was actually going on.
Here is some Java code I used to solve this problem, using Apache's HttpClient, Apache's common-io, and log4j to solve this :
/**

    This is for using Java to connect with Microsoft's Project Online

    If you go into your Project Online, go to 'Server Settings' -> 'Manage Users', and look under the column 'User Logon Account'

    If it looks like :
        i:0#.w|domain\\username
    then you can just scroll down to where I call

                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM, AuthScope.ANY_SCHEME),
                        new NTCredentials(
                                USERNAME,
                                PASSWORD,
                                url.getHost(),
                                DOMAIN));

    However, if it looks more like :
        i:0#.f|membership|username@yourcompany.com
    then you'll need to use OAuth, which is what this file demonstrates.

*/

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.UUID;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.io.IOUtils;// from commons-io-2.4.jar
import org.apache.http.Header;// from httpcore-4.2.4.jar
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;// from log4j.jar
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class ProjectOnline {

    private static final Logger logger         = Logger.getLogger(ProjectOnline.class);

    private static final String USERNAME       = "your user's email address";
    private static final String PASSWORD       = "password";
    private static final String DOMAIN         = "YOURDOMAIN";
    private static final String PROJECT_SERVER = "https://your.project.online.sharepoint.com";
    private static final String EMAIL_DOMAIN   = "@your.company.com";

    public static void main(String[] args) {

        ProjectOnline dao = new ProjectOnline();
        System.out.println(dao.getOAuthCookie());

    }

    private boolean needToUseOAuth(String username) {
        if (username == null) return false;
        return username.toLowerCase().endsWith(EMAIL_DOMAIN.toLowerCase());
    }

    public String getOAuthCookie() {

        if (needToUseOAuth(USERNAME)) {

            String samlSecurityToken = postLoginCredentialsToOurOAuthService();

            if (samlSecurityToken != null && samlSecurityToken.isEmpty() == false) {

                String binarySecurityToken = postSamlSecurityTokenToSecondSite(samlSecurityToken);

                if (binarySecurityToken != null && binarySecurityToken.isEmpty() == false) {

                    String spoidcrlCookie = getSpoidcrlCookie(binarySecurityToken);
                    return spoidcrlCookie;
                } else {
                    //System.out.println("getXMLDocument - OAuth authentication / authorization failed : Binary Security Token was not found");
                    logger.error("getOAuthCookie - OAuth authentication / authorization failed : Binary Security Token was not found");
                }
            } else {
                //System.out.println("getXMLDocument - OAuth authentication / authorization failed : SAML Security Token was not found");
                logger.error("getOAuthCookie - OAuth authentication / authorization failed : SAML Security Token was not found");
            }
        }

        return "";
    }

    // Step 1 - Find the URL to your company's OAuth site
    private String getOurOAuthServerURL(String emailAddress) {

        DefaultHttpClient httpclient = new DefaultHttpClient();

        // Go to this site, passing in email address. Should tell the URL for your company's OAuth site
        HttpPost httppost = new HttpPost("https://login.microsoftonline.com/GetUserRealm.srf?xml=1&login=" + emailAddress);

        try {

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            String status = response.getStatusLine().toString();
            //System.out.println("getOurOAuthServerURL - status = " + status);
            logger.info("getOurOAuthServerURL - status = " + status);

            // If response status doesn't equal 'OK' then it didn't work.
            if (entity != null && "HTTP/1.1 200 OK".equals(status)) {

                StringWriter writer = new StringWriter();
                IOUtils.copy(entity.getContent(), writer, "utf-8");
                String xml = writer.toString();

                //System.out.println(xml);
                //logger.debug(xml);

                String ourAuthURL = getSTSAuthURL(xml);
                //System.out.println("ourAuthURL = " + ourAuthURL);
                return ourAuthURL;

            }
        } catch (UnsupportedEncodingException e) {
            logger.error("getOurOAuthServerURL ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (ClientProtocolException e) {
            logger.error("getOurOAuthServerURL ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (IllegalStateException e) {
            logger.error("getOurOAuthServerURL ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (IOException e) {
            logger.error("getOurOAuthServerURL ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
        return "";
    }

    private String getBinarySecurityToken(String xml) {
        return getValuesBetweenTags(xml, "<wsse:BinarySecurityToken Id=\"Compact0\">", "</wsse:BinarySecurityToken>");
    }

    private String getSTSAuthURL(String xml) {
        return getValuesBetweenTags(xml, "<STSAuthURL>", "</STSAuthURL>");
    }

    private String getSamlSecurityToken(String xml) {
        return getValuesBetweenTags(xml, "<t:RequestedSecurityToken>", "</t:RequestedSecurityToken>");
    }

    private String getValuesBetweenTags(String xml, String tagToLeft, String tagToRight) {
        if (xml == null || xml.isEmpty()) return "";

        int startToken = xml.indexOf(tagToLeft);
        if (startToken > -1) {
            return xml.substring(startToken + tagToLeft.length(), xml.indexOf(tagToRight, startToken));
        } else {
            return "";
        }
    }

    private String getTimeString(int minutesInFuture) {
        Calendar rightNow = Calendar.getInstance();
        rightNow.add(Calendar.SECOND, (((rightNow.get(Calendar.ZONE_OFFSET) + (rightNow.get(Calendar.DST_OFFSET)))/-1000)));
        rightNow.add(Calendar.MINUTE, minutesInFuture);
        String timeString = String.format("%d-%02d-%02dT%02d:%02d:%02d.0000000Z",
                                     rightNow.get(Calendar.YEAR),
                                    (rightNow.get(Calendar.MONTH) + 1),
                                     rightNow.get(Calendar.DATE),
                                     rightNow.get(Calendar.HOUR_OF_DAY),
                                     rightNow.get(Calendar.MINUTE),
                                     rightNow.get(Calendar.SECOND));
        return timeString;
    }

    // Step 2 - POST an XML message, with a few key fields filled in (rest can be left as-is)
    // This should be sent to your company's OAuth site
    private String postLoginCredentialsToOurOAuthService() {

        String ourOAuthService = getOurOAuthServerURL(USERNAME);

        DefaultHttpClient httpclient = new DefaultHttpClient();

        StringBuilder xmlString = new StringBuilder();

        xmlString.append("<s:Envelope xmlns:s=\"http://www.w3.org/2003/05/soap-envelope\" ");
        xmlString.append("xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"  ");
        xmlString.append("xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"  ");
        xmlString.append("xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\"  ");
        xmlString.append("xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\"  ");
        xmlString.append("xmlns:wsa=\"http://www.w3.org/2005/08/addressing\"  ");
        xmlString.append("xmlns:wssc=\"http://schemas.xmlsoap.org/ws/2005/02/sc\"  ");
        xmlString.append("xmlns:wst=\"http://schemas.xmlsoap.org/ws/2005/02/trust\"> ");
        xmlString.append("<s:Header> ");
        xmlString.append("<wsa:Action s:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action> ");
        xmlString.append("<wsa:To s:mustUnderstand=\"1\">" + ourOAuthService + "</wsa:To> ");
        xmlString.append("<wsa:MessageID>").append(UUID.randomUUID().toString()).append("</wsa:MessageID> ");
        xmlString.append("<ps:AuthInfo xmlns:ps=\"http://schemas.microsoft.com/Passport/SoapServices/PPCRL\" Id=\"PPAuthInfo\"> ");
        xmlString.append("<ps:HostingApp>Managed IDCRL</ps:HostingApp> ");
        xmlString.append("<ps:BinaryVersion>6</ps:BinaryVersion> ");
        xmlString.append("<ps:UIVersion>1</ps:UIVersion> ");
        xmlString.append("<ps:Cookies></ps:Cookies> ");
        xmlString.append("<ps:RequestParams>AQAAAAIAAABsYwQAAAAxMDMz</ps:RequestParams> ");
        xmlString.append("</ps:AuthInfo> ");
        xmlString.append("<wsse:Security> ");
        xmlString.append("<wsse:UsernameToken wsu:Id=\"user\"> ");
        xmlString.append("<wsse:Username>").append(USERNAME).append("</wsse:Username> ");
        xmlString.append("<wsse:Password>").append(PASSWORD).append("</wsse:Password> ");
        xmlString.append("</wsse:UsernameToken> ");
        xmlString.append("<wsu:Timestamp Id=\"Timestamp\"> ");
        xmlString.append("<wsu:Created>" + getTimeString(0) + "</wsu:Created> ");
        xmlString.append("<wsu:Expires>" + getTimeString(10) + "</wsu:Expires> ");
        xmlString.append("</wsu:Timestamp> ");
        xmlString.append("</wsse:Security> ");
        xmlString.append("</s:Header> ");
        xmlString.append("<s:Body> ");
        xmlString.append("<wst:RequestSecurityToken Id=\"RST0\"> ");
        xmlString.append("<wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType> ");
        xmlString.append("<wsp:AppliesTo> ");
        xmlString.append("<wsa:EndpointReference> ");
        xmlString.append("<wsa:Address>urn:federation:MicrosoftOnline</wsa:Address> ");
        xmlString.append("</wsa:EndpointReference> ");
        xmlString.append("</wsp:AppliesTo> ");
        xmlString.append("<wst:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</wst:KeyType> ");
        xmlString.append("</wst:RequestSecurityToken> ");
        xmlString.append("</s:Body> ");
        xmlString.append("</s:Envelope> ");

        HttpPost httppost = new HttpPost(ourOAuthService);

        try {

            httppost.addHeader("Content-Type", "application/soap+xml; charset=utf-8");

            httppost.setEntity(new StringEntity(xmlString.toString()));// Set this in the body

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            String status = response.getStatusLine().toString();
            //System.out.println("postLoginCredentialsToOurOAuthService - status = " + status);
            logger.info("postLoginCredentialsToOurOAuthService - status = " + status);

            // If response status doesn't equal 'OK' then it didn't work.
            if (entity != null && "HTTP/1.1 200 OK".equals(status)) {

                StringWriter writer = new StringWriter();
                IOUtils.copy(entity.getContent(), writer, "utf-8");
                String xml = writer.toString();

                //System.out.println(xml);
                //logger.debug(xml);

                // Now, extract out the SAML Security Token. It is several lines (~49, if you parse it out).
                String samlSecurityToken = getSamlSecurityToken(xml);
                //System.out.println("samlSecurityToken = " + samlSecurityToken);
                return samlSecurityToken;

            }
        } catch (UnsupportedEncodingException e) {
            logger.error("postLoginCredentialsToOurOAuthService ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (ClientProtocolException e) {
            logger.error("postLoginCredentialsToOurOAuthService ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (IllegalStateException e) {
            logger.error("postLoginCredentialsToOurOAuthService ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (IOException e) {
            logger.error("postLoginCredentialsToOurOAuthService ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }
        return "";
    }

    // Step 3 - Now that you have the SAML Security Token, you embed it within some other generic XML, and send back to Microsoft server
    private String postSamlSecurityTokenToSecondSite(String samlSecurityToken) {

        DefaultHttpClient httpclient = new DefaultHttpClient();

        try {

            HttpPost httppost = new HttpPost("https://login.microsoftonline.com/rst2.srf");

            httppost.addHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)");

            StringBuilder xmlString = new StringBuilder();

            xmlString.append("<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\" ");
            xmlString.append("xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" ");
            xmlString.append("xmlns:wsp=\"http://schemas.xmlsoap.org/ws/2004/09/policy\" ");
            xmlString.append("xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" ");
            xmlString.append("xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" ");
            xmlString.append("xmlns:wst=\"http://schemas.xmlsoap.org/ws/2005/02/trust\">");
            xmlString.append("<S:Header>");
            xmlString.append("<wsa:Action S:mustUnderstand=\"1\">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action>");
            xmlString.append("<wsa:To S:mustUnderstand=\"1\">https://login.microsoftonline.com/rst2.srf</wsa:To>");
            xmlString.append("<ps:AuthInfo xmlns:ps=\"http://schemas.microsoft.com/LiveID/SoapServices/v1\" Id=\"PPAuthInfo\">");
            xmlString.append("<ps:BinaryVersion>5</ps:BinaryVersion>");
            xmlString.append("<ps:HostingApp>Managed IDCRL</ps:HostingApp>");
            xmlString.append("</ps:AuthInfo>");
            xmlString.append("<wsse:Security>");
            xmlString.append(samlSecurityToken);
            xmlString.append("</wsse:Security>");
            xmlString.append("</S:Header>");
            xmlString.append("<S:Body>");
            xmlString.append("<wst:RequestSecurityToken xmlns:wst=\"http://schemas.xmlsoap.org/ws/2005/02/trust\" Id=\"RST0\">");
            xmlString.append("<wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType>");
            xmlString.append("<wsp:AppliesTo>");
            xmlString.append("<wsa:EndpointReference>");
            xmlString.append("<wsa:Address>sharepoint.com</wsa:Address>");
            xmlString.append("</wsa:EndpointReference>");
            xmlString.append("</wsp:AppliesTo>");
            xmlString.append("<wsp:PolicyReference URI=\"MBI\"></wsp:PolicyReference>");
            xmlString.append("</wst:RequestSecurityToken>");
            xmlString.append("</S:Body>");
            xmlString.append("</S:Envelope>");

            httppost.addHeader("Content-Type", "application/soap+xml; charset=utf-8");

            httppost.setEntity(new StringEntity(xmlString.toString()));

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            String status = response.getStatusLine().toString();
            //System.out.println("postSamlSecurityTokenToSecondSite - status = " + status);
            logger.info("postSamlSecurityTokenToSecondSite - status = " + status);

            // If response status doesn't equal 'OK' then it didn't work.
            if (entity != null && "HTTP/1.1 200 OK".equals(status)) {

                StringWriter writer = new StringWriter();
                IOUtils.copy(entity.getContent(), writer, "utf-8");
                String xml = writer.toString();

                //System.out.println(xml);
                //logger.debug(xml);

                // Extract out the value from just one, single line of this returned XML file
                String binarySecurityToken = getBinarySecurityToken(xml);
                //System.out.println("binarySecurityToken = " + binarySecurityToken);
                return binarySecurityToken;

            }
        } catch (UnsupportedEncodingException e) {
            logger.error("postSamlSecurityTokenToSecondSite ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (ClientProtocolException e) {
            logger.error("postSamlSecurityTokenToSecondSite ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (IllegalStateException e) {
            logger.error("postSamlSecurityTokenToSecondSite ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (IOException e) {
            logger.error("postSamlSecurityTokenToSecondSite ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }

        return "";
    }

    // Step 4 - Using the extracted value, the Binary Security Token, build a header, and add it to the next request
    // This will go to your own Project Online server, which should return back a reply message, containing a 'Set-Cookie' cookie with 'SPOIDCRL' in the value
    private String getSpoidcrlCookie(String binarySecurityToken) {
        try {

            HttpGet httpget = new HttpGet(PROJECT_SERVER + "/_vti_bin/idcrl.svc/");

            httpget.addHeader("Authorization", "BPOSIDCRL " + binarySecurityToken);

            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httpget);

            String status = response.getStatusLine().toString();
            //System.out.println("getSpoidcrlCookie - status = " + status);
            logger.info("getSpoidcrlCookie - status = " + status);

            // If response status doesn't equal 'OK' then it didn't work.
            if ("HTTP/1.1 200 OK".equals(status)) {

                Header[] headers = response.getHeaders("Set-Cookie");
                for (Header header : headers) {
                    if (header.getValue().contains("SPOIDCRL")) {
                        String spoidcrlCookie = header.getValue();
                        //System.out.println("Found SPOIDCRL cookie : " + spoidcrlCookie);
                        return spoidcrlCookie;
                    }
                }
            }
        } catch (ClientProtocolException e) {
            logger.error("getSpoidcrlCookie ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (IOException e) {
            logger.error("getSpoidcrlCookie ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (Exception e) {
            logger.error("getSpoidcrlCookie ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        }
        return null;
    }

    public Document getXMLDocument(String strURL) {

        String spoidcrlCookie = getOAuthCookie();

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet(strURL);

        try {

            URL url = new URL(strURL);

            if (needToUseOAuth(USERNAME)) {

                httpget.addHeader("Cookie", spoidcrlCookie);

            } else {

                // Otherwise, can just use this simple way of logging in, using the Domain
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM, AuthScope.ANY_SCHEME),
                        new NTCredentials(
                                USERNAME,
                                PASSWORD,
                                url.getHost(),
                                DOMAIN));

            }

            //System.out.println("getXMLDocument - strURL " + strURL);
            //logger.info("getXMLDocument - strURL " + strURL);
            //logger.info("getXMLDocument - executing request " + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget);//httppost
            HttpEntity entity = response.getEntity();

            //logger.info("getXMLDocument - ----------------------------------------");
            //for (Header header : response.getAllHeaders()) {
            //  System.out.println("getXMLDocument - header = " + header.toString());
            //}
            String status = response.getStatusLine().toString();
            //System.out.println("getXMLDocument - status = " + status);
            //logger.info("getXMLDocument - status = " + status);

            // If response status doesn't equal 'OK' then it didn't work.
            if (entity != null && "HTTP/1.1 200 OK".equals(status)) {

                DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

                StringWriter writer = new StringWriter();
                IOUtils.copy(entity.getContent(), writer, "utf-8");
                String xml = writer.toString();

                //System.out.println(xml);
                //logger.debug(xml);

                if (xml.endsWith("</feed>") == false) {
                    //logger.warn("The XML did not end with </feed>");
                    xml = xml + "</feed>";
                }

                InputStream inputStream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
                Document doc = docBuilder.parse(inputStream);
                return doc;

            } else {

                logger.error("getXMLDocument - status = " + status);

            }

        } catch (ClientProtocolException e) {
            logger.error("getXMLDocument ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (IOException e) {
            logger.error("getXMLDocument ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (ParserConfigurationException e) {
            logger.error("getXMLDocument ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (IllegalStateException e) {
            logger.error("getXMLDocument ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (SAXException e) {
            logger.error("getXMLDocument ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } catch (Exception e) {
            logger.error("getXMLDocument ERROR | SHORT ERROR MESSAGE: " + e.getMessage() + " FULL ERROR MESSAGE: " + e.toString());
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }

        logger.warn("Exiting from getXMLDocument but returning null");
        return null;
    }
}


text:
Q: cellForRowAtIndexPath not called for all sections I have a UITableView that has five sections. Just as the title describes cellForRowAtIndexPath is only being called for the first four.  All connections have been made concerning the datasource and delegate.  Also, my numberOfSectionsInTableView clearly returns 5.  Printing out the number of sections from within cellForRowAtIndexPath shows the correct number, thus confirming that cellForRowAtIndexPath is simply not being called for all sections.  What on earth is going on?  I looked pretty hard for an answer to this question but could't find one.  If this has already been answered please forgive me and point me in the correct direction.
My cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    switch (indexPath.section) {
        case 0:
            cell.textLabel.text = ticket.description;
            break;
        case 1:
            cell.textLabel.text = ticket.ticketStatus;
            break;
        case 2:
            cell.textLabel.text = ticket.priority;
            break;
        case 3:
            cell.textLabel.text = ticket.customerOfficePhone;
            break;
        case 4: {
            //This never ever gets executed
            Comment *comment = [ticket.comments objectAtIndex:indexPath.row];
            cell.textLabel.text = comment.commentContent;
            break;
        }
    }

    return cell;
}

My numberOfSectionsInTableView:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

My numberOfRowsInSection:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger numberOfRows;

    if (section == 4) {
        numberOfRows = [ticket.comments count];
    }
    else {
        numberOfRows = 1;
    }

    return numberOfRows;
}

Any suggestions are appreciated.  Thanks in advance.

A: Ah-ha!  I figured it out.  I had forgotten that I had hard coded the frame for my table view and added it as a subview with the scroll disabled to a scroll view.  Unfortunately both the scroll view and the tableview were too small in terms of height to hold the fifth section which i suppose was the reason cellForRowAtIndexPath was being called for all sections except the fifth one.  Readjusting the height of my table view and scroll view to be a little bigger has solved my problem.

A: Consider this as a comment. Actually I can't do all this in the comment.
EDIT:
For
[ticket.comments count];  is not Zero means then what is the count?.
 Check an if condition in your cellForRowAtIndexPath: method to print ticket.comments array only if section == 4 like this.
if(indexPath.section == 4){

NSLog(@"Ticket Array:%@",ticket.comments);

}

And Another Question:
What is ticket.comments actually? If that is an array, then is that having "Comment" object or anything else? If it's having comment object then try this in case 4.
case 4:
         {
            Comment *comment = (Comment *)[ticket.comments objectAtIndex:indexPath.row];
            cell.textLabel.text = comment.commentContent;
            break;
         }

I hope this comment will help you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is Visual Studio just an IDE? For Windows Development I mean.
Looking over other questions there are alternatives to VS, but they seem to be web based ones, which is fine, or you could program an entire .net website in notepad, should the urge drive you to.
But is there more to it than just an IDE for Windows Development? I.E. Is it possible for me to create an application in just notepad, is the compiler part of Visual Studio, or is it separate, which could be called via command line or something?
I don't want to not use VS, I'm happy with it, does what I need etc etc, just more a facet I'm curious about.

A: Compilers are available separately.
For C# it would be the csc.exe. You could call it from the command line any time. Pass along the name of the source files to compile, the libraries to reference, compilation option and here you go.
I believe Visual Studio itself calls the compiler over the command line when you ask it to build your project. The build output messages you see is what the command-line compiler returns.
Apart from this Visual Studio is more than just a GUI for a compiler. It has a nice text editor, debugger, designer tools, SQL browser, also integrates with test tools, versioning control and other instrumentary (it's extendable through plug-ins). You'd be striving hard to find an equivalent product (for the Microsoft stack) with a comparable level of consolidation.

A: Not only is the compiler completely separate, so is anything else you might need to build a .net project.  Visual Studio solution and project files are just XML that is understood by MSBuild (another command line tool), which in turn calls the relevant compiler.
Yes, Visual Studio is just an IDE.  That integrates most of the individual tools that you might use during the SDLC (SQL Server, StyleCop, etc.) into a single application.
That's all!

A: I would like to add my two cents. I would say you can't use the words "just an IDE". The way you word your question it's almost that you are saying "is Visual Studio just a fancy text editor?". Remember it has a debugger, tools for SQL, a visual designer, tools for mobile development, viewers for inspecting memory, etc. Visual Studio is an IDE and an IDE is a suite of development/debugging tools.
I think you got the answer you were searching for, which was compilers can be downloaded separately, but I want develpors to realize how much an IDE brings to the table. Even the ability to organize your project is a beautiful thing. I guess this soap box is more "please learn the tools" than anything else. You could use visual studio to debug system problems as well.


text:
Q: how to pull variable out of clickListener for use in another clickListener what i'm trying to do is have a list of platforms for the user to choose from. by clicking a platform it puts in the name of the corresponding sql table name in a variable. but i can't figure out how to use that variable in my submit buttons clickListener. here is the section of code i am working with.
String platformText;

platform.setOnItemClickListener(new OnItemClickListener()
{
   @Override
   public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
   {
     String temp;

       if(position == 1)
       {
            temp = "ps3games";
       }
       else if(position == 2)
       {
            temp = "xbox360games";
       }
    }
});
platformText = temp;

    submitButton.setOnClickListener(new OnClickListener()
{
     public void onClick(View v)
     {
             addProduct(platformText)
         }
    });

i've cut out code not essential to the question.

A: Try this:
String platformText;

platform.setOnItemClickListener(new OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
    {
        String temp;

        if(position == 1)
        {
            temp = "ps3games";
        }
        else if(position == 2)
        {
            temp = "xbox360games";
        }
        platformText = temp;
      }
 });

submitButton.setOnClickListener(new OnClickListener()
{
     public void onClick(View v)
     {
         addProduct(platformText)
     }
});

You needed to set platformTitle=temp within your onClickListener, you were doing that outside of it before.


text:
Q: How to execute long job and then update widget from widget onclick method? I'm logging to bank account and getting account balance.
I calling this function from onUpdate in widget and running in AsyncTask
package com.example.oobe.widget.widgetexample;
public class ExampleAppWidgetProvider extends AppWidgetProvider
{
    (...)

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[]  appWidgetIds)
    {
        (...)
        if (notFromAsyncTask)
            new MyAsyncTask().execute(context);
        (...)
    }
    (...)
}

In method onPostExecute I want to call onUpdate widget and putExtra strings.
How can I do this?
package com.example.oobe.widget.widgetexample;
public class MyAsyncTask extends AsyncTask<Object, Void, BGZ>
{
    Context context;

    @Override
    protected BGZ doInBackground(Object... params)
    {
        this.context = (Context)params[0];
        return GetSomething();
    }

    protected void onPostExecute(BGZ page)
    {
        Intent intent = new Intent(context, ExampleAppWidgetProvider.class);
        intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        intent.putExtra("result", result);
        intent.putExtra("webpage", webPage);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
    (...)
}

If I doing like above I'm getting error:
.. Unable to find explicit activity class..
Can I do this from AsyncTask?
Can I call widget_update (onUpdate) with params to recognize that is from my AsyncTask?
Please give me little sample code (what to add to manifest if it must be broadcastreceiver and so on).
I have updated widget in onPostExecute but I think better method is to do that in ExampleAppWidgetProvider class?

A: If you are getting this error

Unable to find explicit activity class..

It may be due to this line
Intent intent = new Intent(context, ExampleAppWidgetProvider.class);

make sure ExampleAppWidgetProvider.class exist and
Context context = Activity.this;

or
Intent intent = new Intent(Activity.this, ExampleAppWidgetProvider.class);

UPDATE
public class ExampleAppWidgetProvider extends AppWidgetProvider
{

   //your code .......
//asynctask as an inner class
   public class MyAsyncTask extends AsyncTask<Object, Void, BGZ>
{
  doInBackground(){}
onPreExecute(){}
onPostExecute(){

//save result
// or call your methods you need to run after your async call
}
}

}


text:
Q: Is there a way to get my Tkinter GUI to run simultaneously with my code? I am unable to get my GUI and code to run and update together
I had made a D&D combat sim game. I had written it originally as text based, but then, introduced Tkinter to create a GUI and visuals. Within this I created a dialogue/text box. However when I added text to my combat section, I noticed that when my GUI would open, my script would not run until the window was closed. when I switched it, the window would only open when the combat ended.
Disclaimer: GUI is not completely represented here to save space
Blank = tk.Tk()
Canvas = tk.Canvas(Blank, height=720, width=1280)
Canvas.pack()
Frame = tk.Frame(Canvas, bg='#D0B36F')
Frame.place(relwidth=1, relheight=1)
Textbox = tk.Frame(Frame, bg='white')
Textbox.place(relx=0.3, rely=0.6, relwidth=0.4, relheight=0.25)
Log = tk.Text(Textbox)
Log.pack()
Blank.mainloop()
Combat()

I have not received any errors.


text:
Q: Swift Update Constraint I added the constraint to the buttons created in my UIView
func CreateButtonWithIndex(index:Int) {

    newButton.setTranslatesAutoresizingMaskIntoConstraints(false)

    self.view.addSubview(newButton)

    let newButtonConstraintL = NSLayoutConstraint(item: newButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
    let newButtonConstraintH = NSLayoutConstraint(item: newButton, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
    var newButtonConstraintX = NSLayoutConstraint(item: newButton, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: CGFloat(riga))
    var newButtonConstraintY = NSLayoutConstraint(item: newButton, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: CGFloat(colonna))

    view.addConstraints([newButtonConstraintX,newButtonConstraintY,newButtonConstraintH,newButtonConstraintL])

    var pan = UIPanGestureRecognizer(target:self, action:"pan:")
    pan.maximumNumberOfTouches = 2
    pan.minimumNumberOfTouches = 1
    newButton.addGestureRecognizer(pan)
}

func pan(rec:UIPanGestureRecognizer) {
  case .Ended:
        if let subview = selectedView {
            if let button = rec.view as? UIButton {
                if let title = button.titleForState(.Normal){
                    button.setTranslatesAutoresizingMaskIntoConstraints(false)
                    let line = Float(p.x % snapX)
                    let column = Float(p.x % snapY)
                    let constraintL = NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
                    let constraintH = NSLayoutConstraint(item: button, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)
                    var constraint2 = NSLayoutConstraint(item: button, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: CGFloat(line))
                    var constraint3 = NSLayoutConstraint(item: button, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: CGFloat(column))

                    view.addConstraints([constraint2,constraint3,constraintL.constraintH])
                }
            }
        }
}

In My Project my users can move these buttons and then I tried to add more constraints to the buttons recognized but I just get an endless error constraint
  "<NSLayoutConstraint:0x7f8e5a4e9450 UIButton:0x7f8e5a644f60'Button6'.centerX == UIView:0x7f8e5a648bc0.centerX - 120>",
  "<NSLayoutConstraint:0x7f8e5a5be040 'UIView-Encapsulated-Layout-Width' H:[UIView:0x7f8e5a648bc0(736)]>",
  "<NSAutoresizingMaskLayoutConstraint:0x7f8e5a5be1f0 h=-&- v=-&- 'UIView-Encapsulated-Layout-Left' H:|-(0)-[UIView:0x7f8e5a648bc0]   (Names: '|':UITransitionView:0x7f8e5a5a8190 )>",
  "<NSAutoresizingMaskLayoutConstraint:0x7f8e5a5b53b0 h=--& v=--& UIButton:0x7f8e5a644f60'Button6'.midX == + 200>"

Will attempt to recover by breaking constraint
"<NSLayoutConstraint:0x7f8e5a4e9450 UIButton:0x7f8e5a644f60'Button6'.centerX == UIView:0x7f8e5a648bc0.centerX - 120>"

"<NSLayoutConstraint:0x7f8e5a4e9510 UIButton:0x7f8e5a644f60'Button6'.centerY == UIView:0x7f8e5a648bc0.centerY - 40>",
"<NSLayoutConstraint:0x7f8e5a5be1a0 'UIView-Encapsulated-Layout-Height' V:[UIView:0x7f8e5a648bc0(414)]>",
"<NSAutoresizingMaskLayoutConstraint:0x7f8e5a5be240 h=-&- v=-&- 'UIView-Encapsulated-Layout-Top' V:|-(0)-[UIView:0x7f8e5a648bc0]   (Names: '|':UITransitionView:0x7f8e5a5a8190 )>",
"<NSAutoresizingMaskLayoutConstraint:0x7f8e5a5b82d0 h=--& v=--& UIButton:0x7f8e5a644f60'Button6'.midY == + 189>"

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7f8e5a4e9510 UIButton:0x7f8e5a644f60'Button6'.centerY == UIView:0x7f8e5a648bc0.centerY - 40>

... should I update newButtonConstraintX / Y but I'm not understanding how I can do this ?

A: The issue is that you're adding a new constraint that conflicts with the existing constraint.
You have a few options:

*

*Effective in iOS 8, you can set the active property to false for a constraint before you add a new constraint.

*In iOS versions prior to 8, you would want to remove the old constraints before adding new constraints.

*Ideally, it's best to not have to activate/deactivate (or, worse, add and remove) constraints, but rather just modify the constant property of a single constraint. For example in Swift 3/4:
class ViewController: UIViewController {

    private var xConstraint: NSLayoutConstraint!
    private var yConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()

        let label = UILabel()
        label.text = "x"
        label.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(label)

        // I don't really need to save references to these, so these are local variables

        let widthConstraint = label.widthAnchor.constraint(equalToConstant: 50)
        let heightConstraint = label.heightAnchor.constraint(equalToConstant: 50)

        // but since I'll be modifying these later, these are class properties

        xConstraint = label.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        yConstraint = label.centerYAnchor.constraint(equalTo: view.centerYAnchor)

        NSLayoutConstraint.activate([widthConstraint, heightConstraint, xConstraint, yConstraint])

        let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        view.addGestureRecognizer(pan)
    }

    private var originalCenter: CGPoint!

    @objc func handlePan(_ gesture: UIPanGestureRecognizer) {
        if gesture.state == .began {
            originalCenter = CGPoint(x: xConstraint.constant, y: yConstraint.constant)
        }

        let translation = gesture.translation(in: gesture.view!)

        xConstraint.constant = originalCenter.x + translation.x
        yConstraint.constant = originalCenter.y + translation.y
    }

}

When the desired effect can be achieved by modifying the constant of the constraint, that's generally best.
For Swift 2 syntax, see previous revision of this answer.

A: Looks like you are just adding more and more constraint. You can't do that because they obviously conflict with each other. You are basically saying "put the view at position x = 1, x = 2, x = 3, x = 4 and x = 5".
You have to remove the old constraints. You have two options to do that.

*

*Save the constraints in an array, and remove these constraints from the view before adding new ones.

*Or you keep a reference to the constraints that change and adjust their properties.
Since your constraints just differ in the constant value you should go for option 2.
Make newButtonConstraintX and newButtonConstraintY a variable of the viewController.
e.g.
class ViewController: UIViewController {
    var newButtonConstraintX: NSLayoutConstraint!
    var newButtonConstraintY: NSLayoutConstraint!

    func CreateButtonWithIndex(index:Int) {

        newButtonConstraintX = NSLayoutConstraint(item: newButton, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: CGFloat(riga))

        newButtonConstraintY = NSLayoutConstraint(item: newButton, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: CGFloat(colonna))

        /* ... */
    }

    func pan(rec:UIPanGestureRecognizer) {
        /* ... */
        newButtonConstraintX.constant = line
        newButtonConstraintY.constant = column
        button.layoutIfNeeded()
    }

A: Update Rob's Answer to Swift 3:
class ViewController: UIViewController {

    private var xConstraint: NSLayoutConstraint!
    private var yConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
    super.viewDidLoad()

    let label = UILabel()
    label.text = "x"
    label.setTranslatesAutoresizingMaskIntoConstraints(false)
    view.addSubview(label)

    // I don't really need to save references to these, so these are local variables

    let widthConstraint = NSLayoutConstraint(item: drugToDrugView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)
    let heightConstraint = NSLayoutConstraint(item: drugToDrugView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 50)

    // but since I'll be modifying these later, these are class properties

    xConstraint = NSLayoutConstraint(item: drugToDrugView, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0)
    yConstraint = NSLayoutConstraint(item: drugToDrugView, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0)

    drugToDrugView.addConstraints([widthConstraint, heightConstraint, xConstraint, yConstraint])

    let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
    view.addGestureRecognizer(pan)

 }

 private var originalCenter: CGPoint!

 func handlePan(gesture: UIPanGestureRecognizer) {
    if gesture.state == .began {
        originalCenter = CGPoint(x: xConstraint.constant, y: yConstraint.constant)
    }

    let translation = gesture.translation(in: gesture.view!)

    xConstraint.constant = originalCenter.x + translation.x
    yConstraint.constant = originalCenter.y + translation.y
    view.setNeedsLayout()
}


text:
Q: Giving SSH users read-only access to a directory I'm running Fedora 17 and I want to give several users access to files on my secondary hard drives on /run/media/haukur/. This is what I initially did:
chmod -R 755 /run/media/

But every time I turn the computer off these permissions are reset to:
ls -l /run/media/
drwxr-x---+ 4 root root 80 Jul  5 17:42 haukur

The same applies to /run/media/haukur/. I made a symbolic link in every user's home directory pointing to /run/media/haukur/ but they stop working (permission errors) all the time.
What can I do to make these changes permanent?
Edit: I solved the problem by adding the devices to /etc/fstab:
/dev/sdc1   /media/a                               ext4    defaults        0 0
/dev/sdb1   /media/b                               ext4    defaults        0 0

A: For a Fedora system, the file /etc/rc.local contains commands to run after the system has booted and started all services in the runlevel.
If you are looking to fix the permissions when the system boots up, drop chmod -R 755 /run/media in the /etc/rc.local file.
/etc/rc.local is treated like a shell script.


text:
Q: Divisibility of $a^x - 1$ I'm currently working through a number theory script, and it's being taken as obvious that $x | y$ implies $a^x - 1 | a^y - 1$
I must be overlooking something, because I don't see how this is obvious. Could anyone please show me a short proof or nudge me into a direction where I'd be able to find one?

A: Hint:

$$a^k-1=(a-1)\sum_{i=0}^{k-1}a^i\tag{1}$$
  What happens if you replace $a$ with $a^x$?

Also, don't feel sad about the "obvious" part. When a huge result is proven in physics it's a revolution. When the same thing happens in mathematics the result is obvious.

Edit: As this question has been closed, I'll supply some details. Replacing $a$ with $a^x$ in $(1)$ yields $$a^{xk}-1=(a^x-1)\sum_{i=0}^{k-1}a^{xi}\tag{2}$$ Letting $y=xk$ we have $$a^x-1\mid a^y-1$$


text:
Q: An exercise in the Kaplansky's book I saw the following exercise in the Kaplansky's book that is due to D. Lizard.  Where can i find the main text for the proof of this exercise?
Let $P$ be a prime ideal of $R$, $I$ the ideal generated by all the idempotent in $P$. Prove that $R/I$ has no non trivial idempotent.(page 8 of kaplansky'book, exercise 6, commutative ring theory)

A: I think this is a proof if $R$ has $1$. Suppose $e + I$ is an idempotent in $R/I$. This means $e^2 \equiv e \pmod{I}$, so $e(1-e) \in I \subseteq P$. Since $P$ is prime, this implies that either $e \in P$ or $1 - e \in P$. Let's say $e \in P$. Since $e(1-e) \in I$, we may write $e(1-e) = \sum_{i=1}^n r_i e_i$, where each $e_i$ is an idempotent that is in $P$. Now, let $f = e \cdot \prod_{i=1}^n (1 - e_i)$. Then, since each $1 - e_i$ is an idempotent, we have $$f^2 = e^2 \cdot \prod_{i=1}^n (1 - e_i) = \left( e - \sum_{i=1}^n r_i e_i\right)\cdot \prod_{i=1}^n (1 - e_i) = e\cdot \prod_{i=1}^n (1 - e_i)= f, $$ so $f$ is an idempotent (and $f \in P$, because $e \in P$), so $f \in I$. Since $f \equiv e \pmod{I}$, this implies $e \in I$. So $e + I$ is zero in $R/I$.


text:
Q: A type error of "MediaStream" occurs when using "addTrack" in React's useRef A type error occurs in myStreamRef.current inside addTrack.
const myStreamRef = useRef<MediaStream>();
...
if (myStreamRef.current) {
  myStreamRef.current.getTracks().forEach((track) => {
    peerRef.current?.addTrack(track, myStreamRef.current);
  });
}

Argument of type 'MediaStream | undefined' is not assignable to parameter of type 'MediaStream'.
Type 'undefined' is not assignable to type 'MediaStream'.

As shown below, if you eliminate the possibility of being undefined once more with the if statement, the error will no longer occur.
But I've already removed the possibility of being undefined with the outermost if statement, so I don't know why I have to regroup it.
If you know the answer or know of a cleaner way to solve this, please let me know.
const myStreamRef = useRef<MediaStream>();
...
if (myStreamRef.current) {
  myStreamRef.current.getTracks().forEach((track) => {
    if (myStreamRef.current) {
      peerRef.current?.addTrack(track, myStreamRef.current);
    }
  });
}

A: This problem arose because the internal methods had to operate independently.


text:
Q: how to parse integer from a long string I want to parse two values from a string in android studio.
I cannot change the data type from web so I need to parse an Intt.The string that I receive from web is
5am-10am.
How can I get these values i.e. 5 and 10 from the string "5am-10am".
Thanks in advance for help.

A: its work only this kind of format "Xam-Yam".
String value="5am-10am";
value.replace("am","");
value.replace("pm","");//if your string have pm means add this line
String[] splited = value.split("-");

  //splited[0]=5
  //splited[1]=10

A: Here is the trick you should use:-
String timeValue="5am-10am";
String[] timeArray = value.split("-");
// timeArray [0] == "5am";
// timeArray [1] == "10am";

timeArray [0].replace("am","");
// timeArray [0] == "5";// what u needed

timeArray [1].replace("am","");
// timeArray [1] == "10"; // what u needed

A: So, the code below shows step by step how to parse the format you are given. I also added in the steps to use the newly parsed Strings as ints so you can perform arithmetic on them. Hope this helps.
        `/*Get the input*/
        String input = "5am-10am"; //Get the input

        /*Separate the first number from the second number*/
        String[] values = input.split("-"); //Returns 'values[5am, 10am]'

        /*Not the best code -- but clearly shows what to do*/
        values[0] = values[0].replaceAll("am", "");
        values[0] = values[0].replaceAll("pm", "");
        values[1] = values[1].replaceAll("am", "");
        values[1] = values[1].replaceAll("pm", "");

        /*Allows you to now use the string as an integer*/
        int value1 = Integer.parseInt(values[0]);
        int value2 = Integer.parseInt(values[1]);

        /*To show it works*/
        int answer = value1 + value2;
        System.out.println(answer); //Outputs: '15'`

A: I will use some regex to remove the other String and leave only the numeric data. sample code below:
public static void main(String args[]) {
    String sampleStr = "5am-10pm";
    String[] strArr = sampleStr.split("-"); // I will split first the two by '-' symbol.

    for(String strTemp : strArr) {
        strTemp = strTemp.replaceAll("\\D+",""); // I will use this regex to remove all the string leaving only numbers.
        int number = Integer.parseInt(strTemp);
        System.out.println(number);
    }

}

The advantages of this is you don't need to specifically remove "am" or "pm" because all of the other character will be remove and the numbers will only be left.

A: I think that this way can be the faster. Please consider that the regex doesn't validates so it will parse values as "30am-30pm" for example. Validation comes apart.
final String[] result = "5am-10pm".replaceAll("(\\d)[pa]m", "$1").split("-");
System.out.println(result[0]); // -- 5
System.out.println(result[1]); // -- 10


text:
Q: local storage on blackberry that is not accessible from file explorer I have some html file that are downloaded post app startup. I would use the browserfield to display these html pages.
The assistance i need is to know;
Is there an internal writable directory where i can store my html files and access from browserfield, at the same time it should not be accessible from file explorer.
How do i read files from here using fileconnection
What should i write in browserField.requestContent("????????");
The html files need to be not accesible as they have certain logic which i would not like to expose to the end user.
Many Thanks in advance,
Godwin

A: Question has been answered on the BB forum here:
http://supportforums.blackberry.com/t5/Java-Development/local-storage-writable-that-is-not-accessible-from-file-explorer/td-p/2806751
In summary, the answer given (and accepted) was that the downloaded files needed to be stored on the local file system (SD Card, internal storage).  Securing these files could be done with encryption.


text:
Q: Typo3 7.6.22 Bootstrap Package / RTE / unable to use font colors in my current configuration (TYPO3 CMS 7.6.22 Bootstrap Package) the font color picker in RTE does not work. can you help?
I added this TypoScript to PageTSConfig

now it is possible to select colors in RTE

but after saving the page - the color disappiered in RTE and is not displayed in the frontend

here is my template configuration.

A: Thanks to Thomas Löffler!
after changing the pageTSConfig, the format functions are working!


text:
Q: How to use jquery ui slider in react js I'm trying to build a ui range slider component in react js using jQuery UI slider, specifically for time range. From the documentation I can apply it to a regular javascript page. I'm finding it difficult to implement it in React.
I already installed jQuery ui to my application, but the classNames and id's are not applied. How can I implement the slider in React?
import React, { useState } from 'react'
import $ from 'jquery'
import slider from 'jquery-ui/ui/widgets/slider'

export default function TimeSlider() {

    return (

                Time range:
                <input type="text" id="amount" readonly style={{ border: 0, color:
                '#f6931f', fontWeight: 'bold' }} />

    )
}


text:
Q: Can a Byte[] Array be written to a file in C#? I'm trying to write out a  Byte[] array representing a complete file to a file.
The original file from the client is sent via TCP and then received by a server. The received stream is read to a byte array and then sent to be processed by this class.
This is mainly to ensure that the receiving TCPClient is ready for the next stream and separate the receiving end from the processing end.
The FileStream class does not take a byte array as an argument or another Stream object ( which does allow you to write bytes to it).
I'm aiming to get the processing done by a different thread from the original ( the one with the TCPClient).
I don't know how to implement this, what should I try?

A: You can use the FileStream.Write(byte[] array, int offset, int count) method to write it out.
If your array name is "myArray" the code would be.
myStream.Write(myArray, 0, myArray.count);

A: Based on the first sentence of the question: "I'm trying to write out a Byte[] array representing a complete file to a file."
The path of least resistance would be:
File.WriteAllBytes(string path, byte[] bytes)

Documented here:

System.IO.File.WriteAllBytes - MSDN

A: Yep, why not?
fs.Write(myByteArray, 0, myByteArray.Length);

A: You can use a BinaryWriter object.
protected bool SaveData(string FileName, byte[] Data)
{
    BinaryWriter Writer = null;
    string Name = @"C:\temp\yourfile.name";

    try
    {
        // Create a new stream to write to the file
        Writer = new BinaryWriter(File.OpenWrite(Name));

        // Writer raw data
        Writer.Write(Data);
        Writer.Flush();
        Writer.Close();
    }
    catch
    {
        //...
        return false;
    }

    return true;
}

Edit: Oops, forgot the finally part... lets say it is left as an exercise for the reader ;-)

A: There is a static method System.IO.File.WriteAllBytes

A: Try BinaryReader:
/// <summary>
/// Convert the Binary AnyFile to Byte[] format
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static byte[] ConvertANYFileToBytes(HttpPostedFileBase image)
{
    byte[] imageBytes = null;
    BinaryReader reader = new BinaryReader(image.InputStream);
    imageBytes = reader.ReadBytes((int)image.ContentLength);
    return imageBytes;
}

A: You can do this using System.IO.BinaryWriter which takes a Stream so:
var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);

A: Asp.net (c#)
// This is server path, where application is hosted.
var path = @"C:\Websites\mywebsite\profiles\";

//file in bytes array
var imageBytes = client.DownloadData(imagePath);

//file extension
var fileExtension = System.IO.Path.GetExtension(imagePath);

//writing(saving) the files on given path. Appending employee id as file name and file extension.
File.WriteAllBytes(path + dataTable.Rows[0]["empid"].ToString() + fileExtension, imageBytes);

Next Step:
You may need to Provide access to profile folder for iis user.

*

*right click on profile folder

*go to security tab

*click "Edit",

*give full control to "IIS_IUSRS" (IF THIS USER NOT EXISTS THEN CLICK ON ADD AND TYPE "IIS_IUSRS" AND CLICK ON "Check Names".


text:
Q: What is a good, simple way to model wave amplitudes with transmission through different media? I want a simple model to describe the electric field that we detect at a receiver position when some object is close to the optical axis. To make the model more simple, we treat our waves as rays to first order.
The set-up is as follows. We have a transmitter and a receiver antenna which are placed opposite of each other. Somewhere in between, but close enough to the optical axis to play some role, there is an object. For simplicity, we will assume this object to be a circle of homogenous properties (importantly, attenuation coefficient and refraction index, also we assume no reflection) and we restrict ourselves to a 2D description. The transmitter sends out a radial electric wave and we know the free-space solution to be
\begin{equation}
E(r) = \frac{A_0}{r} \times \exp(-ikr),
\end{equation}
where $A_0$ is a constant, $r$ is the distance between transmitter and receiver antenna and $k$ is the wavenumber, which we can also express as $\omega/c * n$, with $\omega$ the circular frequency of the wave, $c$ the speed of light in a vacuum and $n$ the refractive index of the medium.
I assume that this describes the first arrival signal at my receiver. (The object is close to, but not on the optical axis, therefore it does not obstruct this ray.) However, we should also pick up a second signal of waves that enter the object and arrive with some delay (due to their longer physical travel length and their lowered speed in the object). Currently, I model this as a ray bundle sent from the transmitter to the circle, which then gets refracted according to Snellius' law upon entering the circle. Then I determine their exit positions. These exit positions I treat as basically point sources which emit radial waves. Then I sum up all of these new radial waves at the receiver position. In other words, the model for a refracted ray with index $j$ is:
\begin{equation}
E^{\text{refr}}_j = \frac{A_0}{r_{1,j} + r_{2,j} + r_{3,j}} \times \exp(-i k r_{1,j} - i k r_{3,j} - i k_m r_{2,j} - \mu r_{2,j})
\end{equation}
$r_1$ describes the distance from transmitter to the point of entry into the circle, $r_2$ the distance between the points of entry and exit into and from the circle and $r_3$ the distance from the exit point to the receiver. $k_m$ is the wave number inside of the material and $\mu$ is the attenuation coefficient of the material. Therefore, the total refracted field is the sum over the individual contributions, i.e.
\begin{equation}
E^{\text{refr}} = \sum_j E^{\text{refr}}_j
\end{equation}
And the final field would then be the sum of direct and refracted field:
\begin{equation}
E^{\text{total}} = E^{\text{refr}} + E(r)
\end{equation}
However, it is easy to see that this description absolutely overstates the importance of the refracted field. Simply due to the fact that we sum over hundreds to thousands of vectors for the refracted field while we only have one contribution for the direct ray, this completely dominates the signal. I thought about weighting the refracted field by dividing through the number of vectors we used for the modelling, but even then we would end up with roughly a 50-50 contribution (if $r \approx r_1 + r_2 + r_3$), which intuitively seems wrong to me.
How can I properly model the amplitude?


text:
Q: Do Any Existing Languages Allow Function Arguments In Arbitrary Places In A Function Name? When we write (in some language or another):
   lengthOf(n)

We think of it as short for an english 'fill in the blanks' construction, like:
  length of __

But when we write things like these:
  isAnInteger(n)
  appendTo(n,m)

We think of sentences like:
  __ is an integer
  append ___  to  ___

So, it would seem more natural to allow function invocation expressions like:
  (n)isAnInteger
  append(n)to(m)

Where the 'function names' are something like:
  _isAnInteger
  append_to_

Can anyone name existing programming languages which allow this?  I know object-oriented languages let the object be one argument at the front, but I am wondering about more flexible syntaxes.

A: Mixfix is the most general form of what is presented above as a Smalltalk syntax feature via Objective-C. Maude's "bubble" parsing is the most clearly documented implementation of this. More generally, google for "mixfix parsing".

A: As Brian Rice pointed out, mixfix notation in Maude handles this exactly. You've even got the correct syntax.
Your examples
_isAnInteger
append_to_

Would be declared in Maude as
op _IsAnInteger : Int -> Bool
op append_to_ : Int List -> List

And would be called as
5 IsAnInteger
append 5 to L

A: Yes, such a thing does exist, but not in the exact syntax presented in the question.
In JavaScript it's called chaining and is commonly found in frameworks like jQuery to make it easy to create and modify DOM elements on the fly:
$('<div/>')
 .css('background', '#f00')
 .css('width', '100px')
 .css('height', '100px')
 .hide()
 .appendTo('BODY')
 .fadeIn();

The preceding jQuery snippet creates an DIV element, sets the width, height and background color, hides the DIV, appends it to the document and applies a fade-in effect.
Syntax is important. Given the following example:
(n)isAnInteger
append(n)to(m)

The parentheses obviously are mean to be function argument delimiters. But you also need function name delimiters and object/thing delimiters. A better syntax would be:
n.isAnInteger().append(n).to(m)

Which is very similar the jQuery syntax:
 $('DIV')
  .filter(':visible')
  .appendTo('#new_element');

Which will find DIV elements that are visible and copy them to the element with an id of new_element.

A: Smalltalk is pretty close. (it is the same syntax as Objective-C, mentioned in another answer)
Message sends in Smalltalk do no use braces, but follow the form doSomething:with:
So you can write:
5 isInteger
aList appendTo: anotherList
aList at: aPosition ifAbsent: anAction

All messages are sent to an object (the receiver) that must be on the left, so you can not write:
append: aList to: anotherList   "illegal syntax"

The syntax doSomething:with: is more natural than using braces. You are less easily confused about which parameter is what. Consider for instance:
   aList.sublist( i, j )
   aList sublistFrom: i to: j

With proper naming of the methods, it's clear the the first argument is the lower index, and the second the upper index, unlike with braces.

A: Grace is a new educational language (still in development), which supports an almost arbitrary order of arguments:
class MyObject {
    method choseBetween (a : Block<None>) and (b : Block<None>) -> None {
        if (Random.nextBoolean)
            then { a.apply } else { b.apply } }
}

which could get called as:
MyObject.new.chooseBetween { print("Yes") } and { print("No") }

A: Objective-C probably comes closest. Example:
- (void)setRangeStart:(int)start end:(int)end;

- (void)importDocumentWithName:(NSString *)name withSpecifiedPreferences:
(Preferences *)prefs beforePage:(int)insertPage;

Called like:
[obj setRangeStart:1 end:42];
[obj importDocumentWithName:@"foo" withSpecifiedPreferences:prefs beforePage:1];

It doesn't allow [obj 5:isAnInteger] though.

A: Two languages with mixfix operators support come to my mind: Agda and BitC.


text:
Q: When to use the generic parameter clause I'm new to generics in swift, and while reading some books, I came across something I don't understand.  In generic functions, when is it appropriate to use the type parameter (the  right after the function name)? and when is it inappropriate?
Here an example where it is not used (signature only; from standard library):
func sorted(isOrderedBefore: (T, T) -> Bool) -> Array<T>

Here's an example of where it is used (taken from a book I'm reading):
func emphasize<T>(inout array:[T], modification:(T) -> T) {
        for i in 0 ..< array.count {
            array[i] = modification(array[i])
        }
}

I read Apple's swift language reference, section: Generic Parameters and Arguments.  But it is still not clear to me.  Thanks in advance for any insight.

A: In the first example, the generic parameter is coming from the type it is defined within. I believe it is declared within Array which already has the generic type T.
In the second example, the function itself is declaring the generic parameter. If I am not mistaken, this function is a global function. It is not already within a scope that defines a generic T.
It is only inappropriate to declare a new generic parameter in a function that obscures or tries to replace the one already declared in it's scope. For example, when extending an array, this would be inappropriate:
extension Array {
    func myFunc<T>() {
    }
}

Here we are defining a new T that is obscuring the original T that is already declared in the declaration of Array.
In all other circumstances where you want a generic type, you should be declaring it yourself.


text:
Q: Retrieve URL of shared object after Like or Share event I've got a Like button (using XFBML, but can also use HTML5 version if necessary) on key static pages on my site. I can tell when someone clicked the Like button and record that event, but I'm wondering if there's a way to see the actual Like post including any comment that the person added. I know each object should have its own URL, but is it possible to capture this? The idea would be to have the permalink of the Like and comment recorded in our database.
Been through the developer docs and can't seem to find something that does this, but I'm pretty sure I've seen it done. Thanks.


text:
Q: Evaluating a matlab function in C# that requires a matrix input I made a function for a neural network I created inside matlab. I can successfully load the function in c#, but I don't know how I enter a matrix as the input as arrays don't work.
Original Matlab function
function energy = simCW(x)
%x is a 4xQ matrix (I always sim 4x1 though)
S = load('CW100', 'CB_CW100');
CB_CW100 = S.CB_CW100;
energy = sim(CB_CW100,x')';
end

Matlab line for generation function for C#
genFunction(CB_CW100, 'cbcw.m', 'MatrixOnly','yes', 'ShowLinks','no')

Generated Function
function [y1] = cbcw(x1)
%CBCW neural network simulation function.
% [y1] = cbcw(x1) takes these arguments:
%   x = 4xQ matrix, input #1
% and returns:
%   y = 1xQ matrix, output #1
% where Q is the number of samples.

C# Code - Source
    static void Main(string[] args)
    {
        MLApp.MLApp matlab = new MLApp.MLApp();
        double[] current = new double[4];
        current[0]= 71;
        current[1] = 74;
        current[2] = 8;
        current[3] = 105;
        matlab.Execute("cbcw");
        object result = null;
        matlab.Feval("cbcw", 1, out result, current);
        object[] res = result as object[];
        Console.WriteLine(res[0]);
        Console.ReadLine();

    }

The running the program is opening a matlab command line and writing the following to the console:
System.Double[,]

I want a number written to the console, without opening matlab as this eventually will be a stand alone process for computers without matlab.

A: try to consider each element of your matrix as an input, and inside your matlab function you can organize these inputs argument to construct your matrix.
for example
matlab :
function [y1] = cbcw(x1,x2,x3,x4)
x=[x1 X2;x3 x4];

c# :
static void Main(string[] args)
    {
        MLApp.MLApp matlab = new MLApp.MLApp();
        double[] current = new double[4];
        current[0]= 71;
        current[1] = 74;
        current[2] = 8;
        current[3] = 105;
        matlab.Execute("cbcw");
        object result = null;
        matlab.Feval("cbcw", 1, out result, current[0],current[1],current[2],current[3]);
        object[] res = result as object[];
        Console.WriteLine(res[0]);
        Console.ReadLine();

    }


text:
Q: How to create a background task which runs forever -Python FlaskSQLAlchemy I want to create a simple background task that runs forever. I will figure out a method of starting it at the same time as my web application written in Flask.
What I have so far is this:
import threading
from app.models import SkillTracker, UserAttributes
from flask_sqlalchemy import SQLAlchemy
from app import db
import time, math

class SkillTimer(threading.Thread, SkillTracker):
    def __init__(self, SkillTracker=SkillTracker):
        threading.Thread.__init__(self)
        self.skillcheck = SkillTracker.query.filter_by(isactive=1).all()
    def run(self):
            # for x in range(1, 1+1):
            #     if x%1 == 0:
            #         print(x)
            # #print(x)
            time.sleep(1)
            self.skillcheck = SkillTracker.query.filter_by(isactive=1).all()

            if self.skillcheck != []:
                print(self.skillcheck)
                for record in self.skillcheck:
                    if record.isactive == 1:
                        if record.timesubmit + record.timetowait <= time.time():
                            user = UserAttributes.query.filter_by(user_id=record.userid).first()
                            if record.targetskill == 'int':
                                record.isactive = 0
                                user.intelligence += 1
                                db.session.commit()
                                print('User {} upgraded {}, level = {} -- {}'.format(user.user_id, record.targetskill,
                                                                                user.intelligence, time.time()))
                            if record.targetskill == 'end':
                                record.isactive = 0
                                user.endurance += 1
                                db.session.commit()
                                print('User {} upgraded {}, level = {} -- {}'.format(user.user_id, record.targetskill,
                                                                                user.endurance, time.time()))
                            if record.targetskill == 'str':
                                record.isactive = 0
                                user.strength += 1
                                db.session.commit()
                                print('User {} upgraded {}, level = {} -- {}'.format(user.user_id, record.targetskill,
                                                                                user.strength, time.time()))
            else:
                pass
            self.skillcheck = None
            skilltime = SkillTimer()
            skilltime.run()

#while True:
skilltime = SkillTimer()
skilltime.run()
#skilltimer.run()

And this works perfectly as you would expect it to, however, I run into problems after it has runs more than ~950 times. I get a recursion error as follows:
Traceback (most recent call last):
  File "D:\Anaconda3\lib\runpy.py", line 183, in _run_module_as_main
    mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
  File "D:\Anaconda3\lib\runpy.py", line 109, in _get_module_details
    __import__(pkg_name)
  File "D:\Anaconda3\feuadal_kingdom\app\Skilltimer.py", line 52, in <module>
    skilltime.run()
  File "D:\Anaconda3\feuadal_kingdom\app\Skilltimer.py", line 47, in run
    skilltime.run()
  File "D:\Anaconda3\feuadal_kingdom\app\Skilltimer.py", line 47, in run
    skilltime.run()
  File "D:\Anaconda3\feuadal_kingdom\app\Skilltimer.py", line 47, in run
    skilltime.run()
  [Previous line repeated 923 more times]
  File "D:\Anaconda3\feuadal_kingdom\app\Skilltimer.py", line 46, in run
    skilltime = SkillTimer()
  File "<string>", line 4, in __init__
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\orm\state.py", line 414, in _initialize_instance
    manager.dispatch.init_failure(self, args, kwargs)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\util\langhelpers.py", line 60, in __exit__
    compat.reraise(exc_type, exc_value, exc_tb)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\util\compat.py", line 187, in reraise
    raise value
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\orm\state.py", line 411, in _initialize_instance
    return manager.original_init(*mixed[1:], **kwargs)
  File "D:\Anaconda3\feuadal_kingdom\app\Skilltimer.py", line 10, in __init__
    self.skillcheck = SkillTracker.query.filter_by(isactive=1).all()
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 2638, in all
    return list(self)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 2790, in __iter__
    return self._execute_and_instances(context)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\orm\query.py", line 2813, in _execute_and_instances
    result = conn.execute(querycontext.statement, self._params)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 945, in execute
    return meth(self, multiparams, params)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\elements.py", line 263, in _execute_on_connection
    return connection._execute_clauseelement(self, multiparams, params)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1046, in _execute_clauseelement
    if not self.schema_for_object.is_default else None)
  File "<string>", line 1, in <lambda>
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\elements.py", line 436, in compile
    return self._compiler(dialect, bind=bind, **kw)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\elements.py", line 442, in _compiler
    return dialect.statement_compiler(dialect, self, **kw)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 435, in __init__
    Compiled.__init__(self, dialect, statement, **kwargs)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 216, in __init__
    self.string = self.process(self.statement, **compile_kwargs)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 242, in process
    return obj._compiler_dispatch(self, **kwargs)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch
    return meth(self, **kw)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 1738, in visit_select
    text, select, inner_columns, froms, byfrom, kwargs)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 1822, in _compose_select_body
    t = select._whereclause._compiler_dispatch(self, **kwargs)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch
    return meth(self, **kw)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 1025, in visit_binary
    return self._generate_generic_binary(binary, opstring, **kw)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 1050, in _generate_generic_binary
    self, eager_grouping=eager_grouping, **kw)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\visitors.py", line 81, in _compiler_dispatch
    return meth(self, **kw)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 1183, in visit_bindparam
    name = self._truncate_bindparam(bindparam)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 1239, in _truncate_bindparam
    bind_name = self._truncated_identifier("bindparam", bind_name)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 1250, in _truncated_identifier
    anonname = name.apply_map(self.anon_map)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\elements.py", line 4079, in apply_map
    return self % map_
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\util\_collections.py", line 729, in __missing__
    self[key] = val = self.creator(key)
  File "D:\Anaconda3\lib\site-packages\sqlalchemy\sql\compiler.py", line 1269, in _process_anon
    return derived + "_" + str(anonymous_counter)
RecursionError: maximum recursion depth exceeded while getting the str of an object

Which kills the process, and I wouldn't dare pass the exception as it's there for a reason.
My question is this, is there a way I can adapt this threaded class so that it can be run for infinite number of times?
I feel like this could be resolved by re-initiating the class thread each time, but again, I'm not entirely sure how to create these kind of infinite loops.
The only caveat is that at this time I'm only testing so any solutions should be interruptable by the keyboard please.
Please let me know if you need further clarity, there is not any errors in database models or flask routes, everything works perfectly as I want it to except this errors after it reaches the recursion limit. E.g. increasing the recursion limit will only delay the error, not resolve it.

A: I would change it like this:
import threading
from app.models import SkillTracker, UserAttributes
from flask_sqlalchemy import SQLAlchemy
from app import db
import time, math

class SkillTimer(threading.Thread, SkillTracker):
    def __init__(self, SkillTracker=SkillTracker):
        threading.Thread.__init__(self)
        self.skillcheck = SkillTracker.query.filter_by(isactive=1).all()
    def run(self):
        while True:
            time.sleep(1)
            self.skillcheck = SkillTracker.query.filter_by(isactive=1).all()

            if self.skillcheck != []:
                print(self.skillcheck)
                for record in self.skillcheck:
                    if record.isactive == 1:
                        if record.timesubmit + record.timetowait <= time.time():
                            user = UserAttributes.query.filter_by(user_id=record.userid).first()
                            if record.targetskill == 'int':
                                record.isactive = 0
                                user.intelligence += 1
                                db.session.commit()
                                print('User {} upgraded {}, level = {} -- {}'.format(user.user_id, record.targetskill,
                                                                                user.intelligence, time.time()))
                            if record.targetskill == 'end':
                                record.isactive = 0
                                user.endurance += 1
                                db.session.commit()
                                print('User {} upgraded {}, level = {} -- {}'.format(user.user_id, record.targetskill,
                                                                                user.endurance, time.time()))
                            if record.targetskill == 'str':
                                record.isactive = 0
                                user.strength += 1
                                db.session.commit()
                                print('User {} upgraded {}, level = {} -- {}'.format(user.user_id, record.targetskill,
                                                                                user.strength, time.time()))
            else:
                pass
            self.skillcheck = None

skilltime = SkillTimer()
skilltime.run()


text:
Q: EFI won't load linux kernel in LFS Lately, I've been building an LFS [Linux From Scratch] system for my Raspberry Pi Single Board Computer, and I'm currently on the very last step. I'm attempting to compile Linux 5.15 from the Raspberry Pi official Repository, but every time I install the kernel and reboot, the following happens:

*

*Rainbow splash screen appears [READING FAT32 PARTITION]

*Raspberry Pi Logo appears [UEFI FIRMWARE LOADED]

*GRUB2 Boot menu appears

*This appears:

EFI stub: Booting Linux Kernel...
EFI stub: Using DTB from configuration table
EFI stub: Exiting boot services...

And that's it. The boot process stops and remains stuck there forever. The most likely problem I can think of is invalid kernel configuration. Any help is greatly appreaciated.

A: This doesn't exactly solve my problem, but here's what I did to get past that screen:

*

*Download the .deb file for the Raspberry Pi Linux Kernel

*Extract the contents of it using ar

*Untar data.tar.xz

*Copy and paste vmlinuz-5.10.0-19-arm64 and System.map-5.10.0-19-arm64 into /boot of my LFS system

*Reboot

Copying-and-pasting a kernel is gernerally a HORRIBLE idea, but unbelievably, it actually got me past that screen. I still have a kernel panic, but that deserves another question.


text: Q: Среда разработки GUI приложений в среде Linux язык C# Хотелось бы выбрать оптимальную среду разработки GUI приложений в среде Linux язык C#. Я видел, что тема уже поднималась 9 лет назад и говорилось о  MonoDevelop, QT Creator, KDevelop, Eclipse. Но может, что-то еще новое появилось? И возможно ли установить их в Astra Linux CE / SE ?


text:
Q: How to update state value to textarea using onChange? Currently following a slightly older tutorial, but learning using React 18 -- trying to update the text area in a notes app
It looks like when I type, a character appears and then immediately is deleted automatically
Can anyone confirm if I might be missing a detail here?
for reference if familiar with the project at time 1:37:03 : https://www.youtube.com/watch?v=6fM3ueN9nYM&t=377s
import React, {useState, useEffect} from 'react'

import notes from '../assets/data'
import { useParams } from 'react-router-dom';
import { Link } from 'react-router-dom'
import { ReactComponent as ArrowLeft } from '../assets/arrow-left.svg'

const NotePage = ( history ) => {
    const {id} = useParams();
    // let note = notes.find(note => note.id===Number(id))
    // console.log(id)
    let [note, setNote] = useState(null)

    useEffect(() => {
        getNote()
    }, [{id}])

    let getNote = async () => {
        let response = await fetch(`http://localhost:8000/notes/${id}`)
        let data = await response.json()
        setNote(data)
    }

    // let updateNote = async () => {
    //     await fetch(`http://localhost:8000/notes/${id}`, {
    //         method: 'PUT',
    //         headers: {
    //             'Content-Type': 'application/json'
    //         },
    //         body: JSON.stringify({...note, 'updated':new Date()})
    //     })
    // }

    // let handleSubmit = () => {
    //     updateNote()
    //     history.push('/')
    // }

  return (

                <Link to="/">
                    <ArrowLeft /*onClick={handleSubmit}*/ />
                </Link>

        <textarea onChange={(e) => {
            setNote({...note, 'body': e.target.value}) }}
            value={note?.body}>
        </textarea>

  )
}

export default NotePage

A: Your value in the useEffect dependency array is incorrect and causing getNote to be called every time you make changes in the textArea. Every time getNote is called, it's resetting the note state back to whataver is being received by getNote. Which in your case is probably a blank note
Change this :
useEffect(() => {
  getNote();
}, [{ id }]);

To this:
useEffect(() => {
  getNote();
}, [id]);


text:
Q: Server asking terminal type prevents me from auto-running commands I wish to ssh into a server in my department, cd to a directory automatically, and hopefully be able to auto-run other commands if I want. I have tried several ways that have worked for lots of people on stack-overflow, but they did not work for me.
I have tried the methods from the following threads:

*

*Can I ssh somewhere, run some commands, and then leave myself a prompt?

*Run ssh and immediately execute command
In particular, I have tried:
1. ssh one-liner
ssh -t user@domain.com 'cd /some/path; bash -l'

and
2. using the expect script
#!/usr/bin/expect -f
spawn ssh $argv
send "cd /some/path\n"
interact

Both codes look fine, and have worked for people in the threads. However, they did not work for me.
The problem, I expect, lies in the fact that the department server asks me automatically about my terminal type as I login, preventing my auto-commands to be run properly.
$ ssh -t user@domain.com 'cd /some/path; bash -l'
Terminal type? [xterm-256color]

After hitting , it takes me into the home directory as if I haven't cd yet.
The second way gives a similar result.
How can I get over this? Thank you very much in advance!


text:
Q: Using C++11 in a production environment with GCC C++11 provides us with a lot of new great and immensly useful tools. GCC support of C++11 has already made good progress. So I have thought about when to switch to C++11. This question relates to gcc only, I do not expect to compile my (our) code with any other compiler.
Would you (did you) switch to C++11 before gcc supports the entire C++11 standard to benefit from the features already implemented? Would you still do this in a production environment where stability and correctness is very important? Do you think it would be a reasonable approach to allow developers only to use certain C++11 features?
How would you (do you) go about deciding when GCCs C++11 support is ready for a production environment?
(Note: I'm aware of this question, but it specifically relates to gcc 4.4 and is somewhat outdated)

A: It depends.
If it were to power my blog or something like this ? Definitely.
If it were to power a critical service ? Of course not.
I believe that the support of C++11 is too immature as it is now, to be called production ready.
You may settle on a version of gcc, but the truth is that because the successive drafts evolved as new problems were discovered and tackled, the code you write now may well be rejected by a later version, or the behavior may change lightly.
Therefore, I think this judgement truly depends on what you intend to be doing. There is a reason the space shuttle is powered by an old and proven technology: it's a matter of trade-off between ease of development and confidence in the tools.
It's your judgment, you know your situation better than we do.

A: The GCC C++ developers still think their C++03 support is not up to par, and therefore aren't even setting the __cplusplus version correctly (citation needed, I can look up the bug+discussion). They marked the support as experimental because they started implementing the basics before there was a final draft/standard. By now (ie GCC 4.6), most major flaws have been removed, although some details remain inconsistent with the exact standard wording.
If possible, you should also test with Clang, which IMHO strives and succeeds at better adhering to the puny details in most places where GCC lacks the necessary enforcement. Production use is something that's personal. Me, I think that every compiler has bugs, and although the chance of a bug in the "new stuff" is statistically more probably, chances are you'll also encounter an older bug messing with your  perfectly compliant code. That's why I suggest using at least two compilers to prevent any incompatibilities (or at least reduce them as much as possible).
As for the Standard library, libstdc++ is functional for the most part, but lacking in some large and useful parts like <regex>, which is sad. If you're feeling lucky, you should be able to get LLVM's libc++ working on at least Linux and Mac, this is a feature complete c++11 library minus <atomic>), but also the "new kid on the block".
To summarize: the more compilers and Standard libraries you run your code against the better (although you should check which ones are correct, and which are buggy). This inevitably reduces the amount of C++11 features available to you, although if you go with GCC/Clang, only lambda's, uniform initializers and <atomic> fall outside your scope. MSVC is a different story...