text:
Q: Forward emails from domain to another email at different domain? I run a small Debian server at home, and it's hosting two websites. I would also like to have emails received on this domain, to this server, but sent on to our real email addresses. Essentially, if they email anything@domain.com, it forwards to canadianluke@otherdomain.com, on a different domain. Can this be done, or do I need a FULL Email server program on my server to do so?
My registrar is Canspace.ca, and I do not see any Mail options, except to specify my MX Record, which I would point to my server. Currently, there is no email being hosted on my server, but the goal is that any emails destined for my domain name go to my regular email address.
I emailed the Registrar, and they stated that unless I buy their hosting package for the website and everything else, there are no mail services offered, other than pointing the MX record somewhere. So, back to the original question, what is the smallest thing I can do to my Debian-based server to get mail that is sent to it, automatically forwarded to my main account, without storing it on my server?

A: There are a number of ways to do this.
First, let me preface this with the following: while it is assumed that you have an email service installed, you didn't indicate that it is the case.  All examples here assume that you have the service installed.  There are other methods that do not require a full email server, but they are special cases and you typically have immediate delivery with no mail queue.
Debian typically comes with a mail transfer agent already installed, which is some version of Exim (dependent on your version of Debian).  You have the option of using other MTAs, such as Sendmail, Qmail, or Postfix, by installing them.  I am most familiar with Postfix out of that list, so my answers will have a slant towards using/configuring Postfix.
.forward files
The first / easiest / cheesy way to do this is to place a .forward file in the home directory of the account receiving the email.  The .forward file consists of a single line, like so:
someuser@someserver.net

When email is delivered, the .forward file is checked, and if found, the contents used to forward the email on to the address indicated.  This is originally meant to forward email temporarily to a new address, back in Ye Olde Days when real users were hosted on real *nix-style systems.  In your case, it most likely won't work because (a) I doubt you really have a user account set up that corresponds to the address, (b) the "standard" is supposed to be supported by all MTAs, but there is no guarantee, and (b) the website server's address mismatches the email server's address to begin with, so there are other disconnects that prevent this from being a smooth transition.
Of course, it goes without mention, that anything@somedomain.net will not be forwarded; it wants a full, resolvable address.  So, this won't work for you.
Using an MDA
M ail D elivery A gents are specifically meant to make deliveries to local mailboxes.  Based on the limited wording you have provided, I can only assume that you require delivery of the email to a different server.  So this isn't for you, either.
Using an MTA
The second option is to install a M ail T ransport A gent, what people typically call "email service".  Most of these typically come with the ability to re-route messages based on a series of lookups.  In the case of Postfix, you can route all messages for a given domain to another address.  Any message that matches this rule is re-injected into Postfix's pipeline, resulting in a delivery to the new address.  You can do this by creating a mapping for the address to your destination address, and then informing Postfix of the change.
Another advantage to using an MTA is that the message will be queued for delivery; if there is some issue (such as loss of connectivity to the Internet) the MTA will continue to attempt delivery until either the message is delivered, or a specified time-out has been reached, at which point the message will bounce.
I recommend this approach.  It not only provides a little robustness (using queues), it also provides flexibility (you can have several domains mapped this way).

A: So I have this semi-solved. Let me go through what I did.
First off, I had to install a service to receive the emails; I chose postfix, as per the suggestion of Avery Payne. I followed the directions on Debian's website to getting it installed and working locally inside my network. I was able to send mail and receive mail, but not using the FQDN. I figured this was a DNS issue or a port forwarding issue.
For setting up postfix:
apt-get install postfix
cat /var/log/mail.log
postconf -e "myorigin = example.com"
postconf -e "myhostname=server1.example.com"
postconf -e "relay_domains = example.com, example2.com, example3.com"
postfix reload

Then, I tested it locally:
$ telnet localhost 25
>Trying 127.0.0.1...
>Connected to localhost.localdomain.
>Escape character is '^]'.
>220 server1.example.com ESMTP Postfix (Debian/GNU)
mail from:<you@youremail.com>
rcpt to:<user@example.com>
data
To: user@example.com
From: you@youremail.com
Subject: Hey my first email
This is my first email on debian postfix after installing configuring it.
It was easy.

I ended the message and sent it by pressing Enter, ., Enter.
I then exited, and checked my mail on my account:
mail
>You have 1 new mail!

I read it and deleted it. I then tried the instructions above to forward the messages, but it would not send out. Fine, maybe something was blocked. I tried to telnet mail.example.com 25, and I could connect from my cell (not on the Wifi). So, I'm guessing Shaw (my ISP) isn't blocking it. I sent an email to my address, but the server would not receive it. I came back onto the Wifi, and it sent the mail! So there is something blocking it, but that's going to need to be another question.


text:
Q: Redirect to action with Authorization Header I have simple "gate" method which determines whether user's jwt token is valid and then redirects him to some action
I have two end points that require being authorized,

*

*One of them is used just to determine whether token is ok (returns 401 if not, or OK if it is)

*Second one is protected area that requires valid token
My problem is that first end point returns that token is OK, but second returns 401
Because of "Workaround" which is: returning View instead of action
I realized that I forgot about Authorization header, but

how to add headers to redirect to action?

It's kind of important to return redirect to action instead of View, because with View browser shows old url which's in this case localhost/Gate instead of localhost/Authorized
public async Task<IActionResult> Gate()
{
    var token = ExtractToken();

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
    var get = client.GetAsync($"https://localhost:12345/TokenValidator").Result;

    switch (get.StatusCode)
    {
        case HttpStatusCode.Unauthorized:
            return RedirectToAction("Unauthorized");
        case HttpStatusCode.OK:
            return RedirectToAction("Authorized"); // it enters this case
        default:
            return RedirectToAction("Index");
    }
}

[Route("TokenValidator")]
[Authorize]
public IActionResult TokenValidator()
{
    return new OkObjectResult("OK");
}

[Route("Authorized")]
[Authorize]
public IActionResult Authorized()
{
    return View();
}

A: Thanks to Jean-François Fabre for removing my comment.
Sometimes an old comment in an unresolved post helps to revive the debate.
For those interested, follow the answer.
In Startup.cs (Configure)
Add the code:
    app.UseSession();
    app.Use(async (context, next) =>
    {
        var JWToken = context.Session.GetString("JWToken");
        if (!string.IsNullOrEmpty(JWToken))
        {
            context.Request.Headers.Add("Authorization", "Bearer " + JWToken);
        }
        await next();
    });

And in View, after token validation:
HttpContext.Session.SetString("JWToken", post.AccessToken);

Then you can proceed with the process normally.
I use RedirectToAction:
return RedirectToAction(actionName: "Default", controllerName: "Usuario");

Hugs

redpajama_set_name: RedPajamaStackExchange


text:
Q: FinalBuilder 7 - Where are log files? i did found a file named XXX.fbl7 which is type is named "FinalBuilder Log File".
if this is the file how can i open it?
once i click it from windows explorer i get "The project file specified on the command line was not found or invalid"

A: In the desktop application, Tools->Options->Logging section there is tab that allows you to export the logs to text, xml and HTML.
In a Final Builder Project, you can also use a Final Builder Action to create a separate log file in the format you want.
Personally I just use the Final Builder Server Notification options to let me know when things have failed, then go to the web server and review the full log in the web page.

A: Final Builder log files are binary files. You can't open them without having the product installed. As far as I remember, there was an option to export them as text files. But I haven't used FB for years, so I might be wrong.


text:
Q: Load html page content(require jquery scripting support) into a div using ajax/jquery I am a new user here, I want to inform you all that i had thoroughly searched regarding my problem but the solution i found doesn't work perfectly.
Here is my code
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org  /TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>R A</title>
  <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css"
  />

R F I

XYZ

Home

    Products

            Agarbatti

Raw

Scented

Flora

            Dhoop

Soft / Wet

Sticks

Cone

Sambrani

            Loban

Powder

Hard

Candles

Rose Candles

Decorative Candles

Royal Candles

Heart Candles

Orchid Candles

Floating Candles

Ball Candles

Christmas Candles

Pillar Candles

Gourmet Candles

Stands

Agarbatti / Incense

Loban Stands

Dhoops Stands

Candle Stands

Puja Items

Camphor

Cow's Ghee

Rumal/Chundari

Mukut

Mala

Hawan Samagri

Cotton

Janva

Gau Mutr

Mehndi

Napthelene Balls

Perfumes & Attars

Testimonials

    About

    Contact

    Trade Enquiry

Home

Incense Sticks

Raw

Scented

Flora

Dhoop

Soft / Wet

Sticks

Cone

Sambrani

Loban

Powder

Hard

Candles

Rose Candles

Decorative Candles

Royal Candles

Heart Candles

Orchid Candles

Floating Candles

Ball Candles

Christmas Candles

Pillar Candles

Gourmet Candles

Stands

Agarbatti / Incense

Loban Stands

Dhoops Stands

Candle Stands

Puja Items

Camphor

Cow's Ghee

Rumal/Chundari

Mukut

Mala

Hawan Samagri

Cotton

Janva

Gau Mutr

Mehndi

Napthelene Balls

Air Freshner

Perfumes & Attars

 Copyright ©2013

Now what I want to do here is that when i click my menu for home with id "#link1" the div of my main page i.e "#main" should load with en external html file home.html
home.html

        New Project  Some description
        here.

        Image 3  Some description
       here.

I had used following code but it takes me to new page instead of loading the page in the "#main" div.
   jQuery(document).ready(function(){
   $('#link1').on('click', 'a', function(e){ //step 1
   e.preventDefault(); //prevent default action, step2
   var url = url("content/home.html"); //get the url, step 2

   $.ajax({ //step 3
   type: 'GET',
     url: url,
  //your other options
   success: function(data){ //on success
    $('#main').html(data); //update your div, step 4
     }
     });
    });
  });

Previously I had tried following code, which works but the Jquery script doesn't work with it
    $(document).ready(function () {
      $(document).on('click', '#link1', function (e) {
      $('#main').load("content/home.html");
      e.preventDefault();
     });
    });

Here is what I am getting
http://i40.tinypic.com/2nsncs4.jpg
Here is what I Want
http://i42.tinypic.com/tapoaa.jpg
Please help me out i am struck ed.
Thank you.

A: Things where you are wrong:

*

*The way you are Binding event on #link1, this should be $(container).on(event, target, function)

*url should be string, I don't understand what is url("url.html")
Try this:
$(document).ready(function () {
    $(document).on('click', '#link1', function (e) {
        var url = "content/home.html";

        e.preventDefault();

        $.ajax({
            type : 'GET',
            url : url,
            //your other options
            success : function (data) {
                $('#main').html(data);
            }
        });
    });
});

Or instead on $.ajax(), you can simply do $.load() like:
$(document).ready(function () {
    $(document).on('click', '#link1', function (e) {
        $('#main').load("content/home.html");
        e.preventDefault();
    });
});

A: You don't need the whole $.ajax request stuff you can use straight the .load method from query
$( "#main" ).load( "our external url" );

jqyery documentation
However if you have a complete html page in your external url, the whole page will be loaded inside your #main element. This means duplicate html, body and etc. tags. I guess this is not the result you expect.
If you like to load only a particular part of the remote / external page, use a content selector inside the .load method
$( "#main" ).load( "ajax/test.html #container" );

So you will load only the content of the element with container id from the external page into your #main element.


text:
Q: MFC: Floating toolbar window not visible (WS_EX_TOOLWINDOW) In a typical MFC C++ dialog, I want to dynamically create a floating ListBox (or other standard control) over the dialog, possible extending past the dialog's boundaries - so it can't be a simple child or it'll be clipped.
Looking at something similar that works, I tried to achieve it but the window never appears when shown.
In my .h file I have:
CListBox m_ListBox;

Then in my OnInitDialog method (based on Serge's post):
BOOL CYourDlg::OnInitDialog()
{
 CDialog::OnInitDialog();

 m_ListBox.CreateEx(WS_EX_STATICEDGE | WS_EX_TOOLWINDOW, _T("LISTBOX"), NULL,
  WS_CHILD | WS_CAPTION | LBS_STANDARD | WS_HSCROLL | WS_SYSMENU | WS_VISIBLE,
  CRect(50, 100, 200, 200), this, 1);

 m_ListBox.AddString(L"one");
 m_ListBox.AddString(L"two");
 m_ListBox.AddString(L"three");

 return true;
}

The problem is the list-box is rendered beneath other controls in the dialog. I tried calling BringWindowToTop but it doesn't help.
Also, the new control can't extend beyond the edge of the dialog... since it's being used similar to the drop-list in a combo-box, that would be nice.

A: It looks like you can't see the window created due to using GetDesktopWindow to set its parent. Check if following changes to your code would work fine for you, it should create a listbox with 3 items and you should be able to close it ot move it around the dialog.
BOOL CYourDlg::OnInitDialog()
{
 CDialog::OnInitDialog();

 m_ListBox.CreateEx(WS_EX_STATICEDGE | WS_EX_TOOLWINDOW, _T("LISTBOX"), NULL,
  WS_CHILD | WS_CAPTION | LBS_STANDARD | WS_HSCROLL | WS_SYSMENU | WS_VISIBLE,
  CRect(50, 100, 200, 200), this, 1);

 m_ListBox.AddString(L"one");
 m_ListBox.AddString(L"two");
 m_ListBox.AddString(L"three");

 return true;
}

Also I believe you would want to consider using control bars to implement docking\floating functinality for your window.
update0 popup window with listbox
class CPopUpTest : public CFrameWnd
{
private:
    CListBox* m_ListBox;
public:
    CPopUpTest();
protected:
    DECLARE_MESSAGE_MAP()
    afx_msg void OnSize(UINT nType, int cx, int cy);
};

CPopUpTest::CPopUpTest()
{
    m_ListBox = NULL;
    Create(NULL, L"Pop up listbox test", WS_POPUPWINDOW | WS_CAPTION | WS_SIZEBOX,
        CRect(400, 280, 580, 520), NULL, NULL, WS_EX_TOOLWINDOW);

    CRect rect;
    GetClientRect(&rect);

    m_ListBox = new CListBox();
    m_ListBox->Create(WS_CHILD | WS_VISIBLE | LBS_NOTIFY  | LBS_NOINTEGRALHEIGHT | LBS_SORT | WS_VSCROLL, rect, this, 1);

    m_ListBox->AddString(L"one");
    m_ListBox->AddString(L"two");
    m_ListBox->AddString(L"three");
    m_ListBox->AddString(L"four");
}

BEGIN_MESSAGE_MAP(CPopUpTest, CFrameWnd)
   //{{AFX_MSG_MAP(CMainFrame)
   ON_WM_SIZE()
   //}}AFX_MSG_MAP
END_MESSAGE_MAP()

void CPopUpTest::OnSize(UINT nType, int cx, int cy)
{
    CFrameWnd::OnSize(nType, cx, cy);
    if (m_ListBox!=NULL) m_ListBox->MoveWindow(0, 0, cx, cy);
}

then whenever you want to show this window do:
CPopUpTest* popUpList = new CPopUpTest();
popUpList->ShowWindow(SW_NORMAL);
popUpList->BringToTop(SW_NORMAL);

hope this helps, regards


text:
Q: Link a python script to javascript on raspberry pi with webiopi Hi im trying to control some solenoid valves via a raspberry pi, relays and external power supply. I have written a script in python below that works fine, for changing the value of the physical buttons but want to be able to also control it from a web browser. Ive been using webiopi and have got that working as i can now turn the relay on and off. My problem is that when i start the python script the buttons i have set as outputs work fine, but when i press the on/off button on the javascript the physical buttons no longer work. I presume the problem is that i need to get the python script to "talk" to the javascript? to update the value of the output when pressed? however im not sure how to do this? below are my two seperate codes.
Python.
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(10, GPIO.IN) ## Setup GPIO Pin 10 to IN
GPIO.setup(22, GPIO.IN) ## Setup GPIO Pin 22 to IN
GPIO.setup(13, GPIO.OUT) ## Setup GPIO Pin 13 to OUT

#############################################

# All buttons wired to provide High input when pressed.

#############################################
# Cleanroom = 0 #sets a variable that will never be meet so while loop will continue       for ever or if power is interupted.

Cleanroom = 0
while True:

#########################################################################
# below is code for opening cryo, it includes button debouncing
    cryo_open = 0
    while True:
    #take a reading
    on = GPIO.input(22)
    GPIO.output(13, False)
    #if the last reading was low and this one high, print
    if ((not cryo_open) and on):
        print("Cryo Open")
        #update previous input
        cryo_open = on
        #slight pause to debounce
        time.sleep(0.05)
        break

#########################################################################
# below is code for closing cryo, it includes button debouce
    cryo_close = 0
    while True:
        #take a reading
        on = GPIO.input(10)
        GPIO.output(13, True)
        #if the last reading was low and this one high, print
        if ((not cryo_close) and on):
            print("Cryo Close")
            #update previous input
            cryo_close = on
            #slight pause to debounce
            time.sleep(0.05)
            break

GPIO.cleanup(13)
GPIO.cleanup(22)
GPIO.cleanup(10)

Java script
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"              <"http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content = "height = device-height, width = 420, user-scalable =  no" />
    <title>WebIOPi | Demo</title>

Clean Room Pneumatic Valve Control


text:
Q: Elasticsearch: Using of field analyser in query_string I just want to do a query_string using the analyzer of each field and not one for all fields
Do i have to specify all fields like
GET /_search
{
    "query": {
        "query_string" : {
            "fields" : ["content", "name", ...],
            "query" : "this AND that"
        }
    }
}

Is there a solution ?
Thanks

A: First of all, _all is deprecated as of 6.0. Source: https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-all-field.html
Article suggests to create a custom field which can be analyzed in a way you want and searched against. Sample
PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "first_name": {
          "type": "text",
          "copy_to": "fake_all"
        },
        "last_name": {
          "type": "text",
          "copy_to": "fake_all"
        },
        "fake_all": {
          // Here you can define analyzer you want
          // And use this field four your query_string query
          "type": "text"
        }
      }
    }
  }
}


text:
Q: XGBoost Regression on a normal distribution variable produces a one sided distribution (only positive values) I'm running a scikit-learn XGBoostRegressor with an RMSE loss function, on a variable with a distribution that is close to symmetric around 0 (think normal distribution, with a positive mean that generates more positive than negative values, apprx. 2:1).
The model consistently predicts mostly positive values. Only 1-3% of the predictions are negative, and with negligible values.
For the life of me, I'm stumped on why this might happen - it feels like there's some parameter in XGBoost telling it not to predict negative values or something.

A: Without more details, it's hard to guess what's going on. However, one possibility is that the model fails to do very well at predicting (or there's a lot of unexplained - by the model - variability), so it minimizes RMSE by predicting something close to the mean of the outcome variable. E.g. if the predictors you have contain absolutely no information for predicting the outcome you want to predict, then the best (=minimizes RMSE) prediction is to predict the mean of the training data.
This could happen, because the predictors you use don't contain much information on the outcome, or because your hyperparameters are chosen so that the model is underfit/over-regularized.
How can you tell whether this is happening? If you look at the distribution of predicted values for data not used in the training, the distribution should be a good bit narrower than the true labels, but centered approximately around the mean of the training data.


text:
Q: How to avoid implicit conversion from char to int when using arithmetic operators I have templated some code which I want to specialize for both int and char. In this code, I use the arithmetic operator operator+. When I compile using g++ (conversion warnings, warnings treated as errors) the compiler complains that my chars are implicitly converted to ints and every further assignment triggers a narrowing conversion warning.
Here is some basic code to reproduce this issue:
template<typename T>
T add(const T a, const T b)
{
    return a + b;
}

int main()
{
    const char a = 1;
    const char b = 2;

    const char c = add<char>(a, b); // a and b implicitely converted to int.
                                    // Assignement to c fails (narrowing)

    (void)c;

    return 0;
}

which you can compile (it should fail) using:
g++ -Wconversion -Werror main.cpp

I know that this is because the smallest built-in type for which operator+ is defined is int, so when you use smaller types, they silently get converted to fit the arguments.
I am looking for a way to avoid this and minimize casting. I know for example that I could cast the result the addition of a and b to char, but for additions with many terms, it soon becomes a mess to read.
How could I do this?

The error I get:
main.cpp:4:16: error: conversion to 'char' from 'int' may alter its value [-Werror=conversion]
     return a + b;
                ^
cc1plus: all warnings being treated as errors

A: So yeah, formally this is the case:

... arithmetic operators do not accept types smaller than int as
  arguments, and integral promotions are automatically applied after
  lvalue-to-rvalue conversion [...]

But why would you want to change or avoid this behavior? If you do something like you suggested, and maybe cast the return value like this:
template<typename T>
T add(const T a, const T b)
{
    return static_cast<T>(a + b);
}

than you're getting pretty quickly to the risk of integer overflow in the returned char due to its small size to begin with. Is there any reason for you to avoid the promotion in your scenario?


text:
Q: Sending mail in JAVA by getting mail structure from database I've to send a mail using Java in ADF but the mail Structure is coming from the database but I don't know how to use that structure and assign the dynamic value to it.
Following is the Structure :
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/">

                <title>Email Notification</title>

LC Details

LC Number

Facility Number

LC Amount Created

Expiry Date

Project number

Cost Center

Bank Account

    </xsl:template>
</xsl:stylesheet>

And following is the Class from where I'm Sending mail

import java.time.LocalDate;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class Mail {
    public static void main(String[] args) {

        String host = "smtp.gmail.com";
        final String user = "test.";// change accordingly
        final String password = "Wel";// change accordingly

        String to = "shwetangr@gmail.com";// change accordingly
        StringBuilder msg = new StringBuilder();

        // Get the session object
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "587");

        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });

        // Compose the message
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(user));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("Dummy Email");
            message.setContent(text, "text/html");

            // send the message
            Transport.send(message);

            System.out.println("message sent successfully...");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Please tell me how to set value to those empty text boxes at runtime by getting that structure from database using JAVA

A: getDataFromDataBase() {

        logger.info("---Début: récupération de données depuis la BD ---");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            WriteTxtFile.setExitCode(1);
            logger.error("Oracle Driver Class Not found Exception: ",e.toString());
            return null;
        }
        DriverManager.setLoginTimeout(60);

        try {
            String url = url of your database;
            conn = DriverManager.getConnection(url, user,
                    password);
        } catch (SQLException e) {

            return null;
        }

        // Creates a Statement object for sending SQL statements to the database
        try {
            statement = conn.createStatement();
            String sql = your query;

            rs = statement.executeQuery(sql);
            String content="";
            while (rs.next()) {
                content=content+rs.getString("your column name"),
                content=content+rs.getString("your column name2"),
            }

            statement.close();
        } catch (SQLException e) {
            logger.error(e.toString());
        }
        logger.info("---Fin: récupération de données depuis la BD ---");
        return lines;
    }


text:
Q: How to share single SQLite connection in multi-threaded Python application I am trying to write a multi-threaded Python application in which a single SQlite connection is shared among threads.  I am unable to get this to work.  The real application is a cherrypy web server, but the following simple code demonstrates my problem.
What change or changes to I need to make to run the sample code, below, successfully?
When I run this program with THREAD_COUNT set to 1 it works fine and my database is updated as I expect (that is, letter "X" is added to the text value in the SectorGroup column).
When I run it with THREAD_COUNT set to anything higher than 1, all threads but 1 terminate prematurely with SQLite related exceptions.  Different threads throw different exceptions (with no discernible pattern) including:
OperationalError: cannot start a transaction within a transaction

(occurs on the UPDATE statement)
OperationalError: cannot commit - no transaction is active

(occurs on the .commit() call)
InterfaceError: Error binding parameter 0 - probably unsupported type.

(occurs on the UPDATE and the SELECT statements)
IndexError: tuple index out of range

(this one has me completely puzzled, it occurs on the statement group = rows[0][0] or '', but only when multiple threads are running)
Here is the code:
CONNECTION = sqlite3.connect('./database/mydb', detect_types=sqlite3.PARSE_DECLTYPES, check_same_thread = False)
CONNECTION.row_factory = sqlite3.Row

def commands(start_id):

    # loop over 100 records, read the SectorGroup column, and write it back with "X" appended.
    for inv_id in range(start_id, start_id + 100):

        rows = CONNECTION.execute('SELECT SectorGroup FROM Investment WHERE InvestmentID = ?;', [inv_id]).fetchall()
        if rows:
            group = rows[0][0] or ''
            msg = '{} inv {} = {}'.format(current_thread().name, inv_id, group)
            print msg
            CONNECTION.execute('UPDATE Investment SET SectorGroup = ? WHERE InvestmentID = ?;', [group + 'X', inv_id])

        CONNECTION.commit()

if __name__ == '__main__':

    THREAD_COUNT = 10

    for i in range(THREAD_COUNT):
        t = Thread(target=commands, args=(i*100,))
        t.start()

A: I ran into the SqLite threading problem when writing a simple WSGI server for fun and learning.
WSGI is multi-threaded by nature when running under Apache.
The following code seems to work for me:
import sqlite3
import threading

class LockableCursor:
    def __init__ (self, cursor):
        self.cursor = cursor
        self.lock = threading.Lock ()

    def execute (self, arg0, arg1 = None):
        self.lock.acquire ()

        try:
            self.cursor.execute (arg1 if arg1 else arg0)

            if arg1:
                if arg0 == 'all':
                    result = self.cursor.fetchall ()
                elif arg0 == 'one':
                    result = self.cursor.fetchone ()
        except Exception as exception:
            raise exception

        finally:
            self.lock.release ()
            if arg1:
                return result

def dictFactory (cursor, row):
    aDict = {}
    for iField, field in enumerate (cursor.description):
        aDict [field [0]] = row [iField]
    return aDict

class Db:
    def __init__ (self, app):
        self.app = app

    def connect (self):
        self.connection = sqlite3.connect (self.app.dbFileName, check_same_thread = False, isolation_level = None)  # Will create db if nonexistent
        self.connection.row_factory = dictFactory
        self.cs = LockableCursor (self.connection.cursor ())

Example of use:
if not ok and self.user:    # Not logged out
    # Get role data for any later use
    userIdsRoleIds = self.cs.execute ('all', 'SELECT role_id FROM users_roles WHERE user_id == {}'.format (self.user ['id']))

    for userIdRoleId in userIdsRoleIds:
        self.userRoles.append (self.cs.execute ('one', 'SELECT name FROM roles WHERE id == {}'.format (userIdRoleId ['role_id'])))

Another example:
self.cs.execute ('CREATE TABLE users (id INTEGER PRIMARY KEY, email_address, password, token)')
self.cs.execute ('INSERT INTO users (email_address, password) VALUES ("{}", "{}")'.format (self.app.defaultUserEmailAddress, self.app.defaultUserPassword))

# Create roles table and insert default role
self.cs.execute ('CREATE TABLE roles (id INTEGER PRIMARY KEY, name)')
self.cs.execute ('INSERT INTO roles (name) VALUES ("{}")'.format (self.app.defaultRoleName))

# Create users_roles table and assign default role to default user
self.cs.execute ('CREATE TABLE users_roles (id INTEGER PRIMARY KEY, user_id, role_id)')

defaultUserId = self.cs.execute ('one', 'SELECT id FROM users WHERE email_address = "{}"'.format (self.app.defaultUserEmailAddress)) ['id']
defaultRoleId = self.cs.execute ('one', 'SELECT id FROM roles WHERE name = "{}"'.format (self.app.defaultRoleName)) ['id']

self.cs.execute ('INSERT INTO users_roles (user_id, role_id) VALUES ({}, {})'.format (defaultUserId, defaultRoleId))

Complete program using this construction downloadable at:
http://www.josmith.org/
N.B. The code above is experimental, there may be (fundamental) issues when using this with (many) concurrent requests (e.g. as part of a WSGI server). Performance is not critical for my application. The simplest thing probably would have been to just use MySql, but I like to experiment a little, and the zero installation thing about SqLite appealed to me. If anyone thinks the code above is fundamentally flawed, please react, as my purpose is to learn. If not, I hope this is useful for others.

A: It's not safe to share a connection between threads; at the very least you need to use a lock to serialize access. Do also read http://docs.python.org/2/library/sqlite3.html#multithreading as older SQLite versions have more issues still.
The check_same_thread option appears deliberately under-documented in that respect, see http://bugs.python.org/issue16509.
You could use a connection per thread instead, or look to SQLAlchemy for a connection pool (and a very efficient statement-of-work and queuing system to boot).

A: I'm guessing here, but it looks like the reason why you are doing this is a performance concern.
Python threads aren't performant in any meaningful way for this use case.   Instead, use sqlite transactions, which are super fast.
If you do all your updates in a transaction, you'll find an order of magnitude speedup.


text:
Q: Jersey: "Broken pipe" instead of HTTP 401 Unauthorized I have a POST request code that uploads a file. It uploads files correctly but fails with "Broken pipe" instead of 401 Unauthorized that I expect when I provide an incorrect  API key.
I have used Postman to verify that our server sends 401 Unauthorized when a wrong API key is provided.
I am under the impression that my client code still tries to send something to the stream even though the server has already closed the connection after it had sent the 401 Unauthorized.
This is the code I am using:
try {
    return target
        .path("storage")
        .path("upload")
        .request()
        .header("Authorization", apiKeyHeader)
        .header("App-Type", type)
        .post(Entity.entity(Files.newInputStream(file.toPath()), APPLICATION_OCTET_STREAM), String.class);

} catch (IOException e) {
    e.printStackTrace(); // <-- exception comes here
}

I have also tried upgrading Jersey to the latest version available: 2.27 but that didn't change anything.

javax.ws.rs.ProcessingException: java.net.SocketException: Broken pipe (Write failed)
at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:496)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:278)
at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:767)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:765)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:456)
at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:357)
at org.comcom.rest.api.resource.v2.AppStorageResource.uploadFile(AppStorageResource.java:70)

This is my pom.xml config:
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
    <version>2.23.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.connectors</groupId>
    <artifactId>jersey-apache-connector</artifactId>
    <version>2.23.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-multipart</artifactId>
    <version>2.23.1</version>
</dependency>


text:
Q: Why does converting an integer to a string, slicing it, and then converting it back to an integer give me this TypeError? So I'm trying to solve a challenge here, and I have a basic algorithm written to solve this problem.  One of the functions of this algorithm is that it will convert the input of the function, n, to a string, slice every character but the first, and convert it back to an integer using this: o = int(str(n[:1])).  When I do this however, it gives me this error: TypeError: 'int' object is not subscriptable.  I have found another case here, but it does not seem to solve my problem.  What does this error mean and how can I rid my code of it?
Full function:
def utopianTree(n):
    o = int(str(n[:1]))
    n = int(str(n[1:]))

    for i in range(1, n):
        if n == 0:
            o += 1
        elif i % 2 == 0:
            o *= 2
        elif i % 2 != 0:
            o += 1
        i += 1
    return o

A: You are applying the [:1] slice to n, which is an integer. You can't slice integers, because they are not sequences.
Your title states you want convert to a string, then slice, then convert back to an integer, but you are not actually doing that. Put the slice operation on the str() outcome instead:
o = int(str(n)[:1])
n = int(str(n)[1:])

The first number assigned to o is the highest digit, so you could just repeatedly divide by 10 until the number is smaller than 10:
o = n
while o > 10:
    o //= 10

or you could take the log10 of the value so you know by how many powers of 10 to shift the value; you can get the remaining digits of n by using the same magnitude value:
import math

magnitude = int(math.log10(n))
o = n // (10 ** magnitude)
n -= o * (10 ** magnitude)

Demo:
>>> import math
>>> n = 4213
>>> magnitude = int(math.log10(n))
>>> o = n // (10 ** magnitude)
>>> n -= o * (10 ** magnitude)
>>> o, n
(4, 213)

Take into account that any zeros in the value are not going to be preserved; 1024 becomes 1 and 24, with the fact that there was a zero between these two pairs is lost. That applies to both the int-string-slice-int and the arithmetic approach. Only keeping n as a series of string digits would keep that information.

A: It's as simple as just changing it to o = int(str(n)[:1])
Hope this helps!


text:
Q: Setting child routes in react I have a profile component that further gets divided into profile-form and profile-roles. I already made routes of these subcomponents but they didn't work. Here are the sample codes of this component.
Profile.js
render();
{
  const profile = {
    padding: '30px',
  };
  return (

Profile

      <Router>
        <Switch>
          <Route exact path="/" component={ProfileForm} />
          <Route path="/profile-form" component={ProfileForm} />
          <Route path="/profile-roles" component={ProfileRoles} />
        </Switch>
      </Router>

  );
}

Profile Roles
render();
{
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={RoleLists} />
        <Route path="/list" component={RoleLists} />
        <Route path="/create" component={CreateRole} />
      </Switch>
    </Router>
  );
}

Right now I only able to see the 'h3' tag of starting profile.js. None of the routing (profile and roles) seems to be working.

A: After defining path from the props in your "Profile Roles" component make sure not to re declare Router and just add Routes.Otherwise you may face redirect issues.

A: something like that.
Profile Roles
render()
    {
        const { match: { path } } = this.props;
        return(
            <Router>
                <Switch>
                    <Route exact path={path} component={RoleLists} />
                    <Route path={`${path}/list`} component={RoleLists} />
                    <Route path={`${path}/create`} component={CreateRole} />
                </Switch>
            </Router>
        )
    }

A: I miss a small concept. after searching a lot on google and reading lots of tutorials I found that I didn't need to re-declare Router in my profile component. Routing works well if I use only Route inside of Switch.
Here is my code.
Profile.js

render()
    {
        const profile={
            padding:"30px"
        }
        return(

Profile

                <Switch>
                    <Route path="/dashboard/profile" exact component={ProfileForm} />
                    <Route path="/dashboard/profile/view" component={ProfileForm} />
                    <Route path="/dashboard/profile/roles" component={ProfileRoles} />
                </Switch>

        )
    }

Profile Roles

render()
    {
        return(
                <Switch>
                <Route exact path="/dashboard/profile/roles" component={RoleLists} />
                    <Route path="/dashboard/profile/roles/list" component={RoleLists} />
                    <Route path="/dashboard/profile/roles/create" component={CreateRole} />
                </Switch>
        )
    }


text:
Q: Fallout 4 - The Molecular Level - Change Faction So I asked the Railroad first to help me build the relay, thinking I was going to be able to ask for help from all three factions. I would've chosen the Minutemen had I known there was only one faction I could ask for help. My question is this: I haven't gone through the relay yet (in an hours-old save), but have built it with the Railroad's help. Can I reject their assistance and change who I want to help me? The answer is likely, "no," as I've already built the relay, but I'd really prefer the Minutemen over the Railroad as they are the most noble of the factions in my estimation.

A: I can confirm what Unknown Zombie stated in his comment. It does not matter in terms of who you want to ally with for the end of the game.
I can confirm this because I chose the Brotherhood to assist me, and sided with the Institute to get their ending for my first playthrough. And did the opposite on my second playthrough. Neither side really so much as mentioned the fact that I chose their enemy to assist the relay build. It serves no function after that mission anyway.


text:
Q: A question on function analysis and limits. The question provides me with $f(1)=1$ and $f'(1)=2$. I'm required to find the value of the following limit:
$$\lim_{x\to 1} \frac{\sqrt{f(x)} - 1}{\sqrt{x} - 1}$$
I cannot figure out how to apply the first principle of differentiation. The answer should be 2.

A: Note that
$$\lim_{x\to 1} \frac{\sqrt{f(x)} - 1}{\sqrt{x} - 1}=\lim_{x\to 1} \frac{\sqrt{f(x)} - 1}{x - 1}(\sqrt x+1)=\lim_{x\to 1} \frac{\sqrt{f(x)} - 1}{x - 1}\cdot\lim_{x\to 1}(\sqrt x+1)=2\left(\sqrt{f(x)}\right)'_{x=1}.$$
Then use the chain rule:
$$\left(\sqrt{f(x)}\right)'=\color{red}{\frac{f'(x)}{2\sqrt{f(x)}}}.$$

A: Assuming you meant $\;f'(1)=2\;$ and with l'Hospital:
$$\lim_{x\to1}\frac{\sqrt{f(x)}-1}{\sqrt x-1}\stackrel{l'H}=\lim_{x\to1}\frac{\frac{f'(x)}{2\sqrt{f(x)}}}{\frac1{2\sqrt x}}=\lim_{x\to1}\frac{\sqrt x\,f'(x)}{\sqrt{f(x)}}=\frac{\sqrt1f'(1)}{\sqrt{f(1)}}=\frac21=2$$


text:
Q: COALESCE() for blank (but not null) fields I have two fields that I'm comparing with MySQL's function COALESCE(). For example, COALESCE(Field1, Field2). The problem is, Field1 is sometimes blank but not null; since it's not null COALESCE() selects Field1, even though its blank. In that case, I need it to select Field2.
I know I can write a if-then-else (CASE) statement in the query to check for this, but is there a nice simple function like COALESCE() for blank-but-not-null fields?

A: You can  use a CASE expression:
CASE WHEN Field1 <> '' THEN Field1 ELSE Field2 END

A: SELECT IFNULL(NULLIF(Field1,''),Field2)

NULLIF returns a NULL if Field1 is blank, while IFNULL returns Field1 if it's not blank or NULL and Field2 otherwise.

A: I know I'm late to the party here, but there is a way to do this while still using COALESCE().  This would then work if your value was NULL or ''.
Select COALESCE(NULLIF(Field1,''), Field2)

A: Use CASE, for comparing both NULL and Blank.
SELECT CASE
        WHEN Field1 IS NULL
            OR LEN(LTRIM(RTRIM(Field1))) < 1
            THEN Field2
        ELSE Field1
        END;

For comparing blank, do not use '', use LEN, LTRIM, RTRIM. Sometimes, blank may be with more than one spaces.


text:
Q: Qt/C - QWebView - Loading Flash Lite plugin I have problem loading Flash Lite plugin on N8
I have simple QWidget with QWebView inside, whole page (for example Youtube video) is loaded, but instead of video I see "Upgrade your flash player to newer version" (not literally translated)
In code (using Qt 4.7.3):
(_webView is Ui instance of QWebView)
ui->_webView->settings()->setAttribute(QWebSettings::PluginsEnabled, true);
ui->_webView->settings()->setAttribute(QWebSettings::AutoLoadImages, true);
ui->_webView->load(_url);

Request more details, if I haven't provided
Best regards
Marek Sebera

A: you need to do that for global settings.
 QNetworkProxyFactory::setUseSystemConfiguration (true);
QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);
QWebSettings::globalSettings()->setAttribute(QWebSettings::AutoLoadImages, true);

Then use webview to load the youtube video.

A: See divanov's post #9 here -- the "Product Specialist" says

Webkit doesn't support Flash Lite, it just normal Flash

Although that was in 2009, so I guess this could have changed. Are your libraries up-to-date?
This is an unresolved bug (in two parts) on the other hand this bug seems to imply that Flash Lite does have some support on Symbian.


text:
Q: Android listview with checkedtextview I have a listview with CheckedTextView. I want when select the item add its value to a list and when deselect remove the value from list. I don't know why i couldn't get accurate value. Thanks in advance........
Here is my code
      listview.setOnItemClickListener(new OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> parent,
                                    View view, int position, long id) {

                                CheckedTextView ctv=(CheckedTextView)view.findViewById(R.id.addonsItem);

                            if (ctv.isChecked()) {

                                Temp.addonsIdList.add(addonsiDList.get(position));
                                Temp.addonsNameList.add(addonsList.get(position));
                                Temp.addonsPriceList.add(addonsPriceList.get(position));
                                ctv.setChecked(false);

                            }else{

                                Temp.addonsIdList.remove(addonsiDList.get(position));
                                Temp.addonsNameList.remove(addonsList.get(position));
                                Temp.addonsPriceList.remove(addonsPriceList.get(position));
                                ctv.setChecked(true);

                            }

adapter getView code
   @Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(
                R.layout.addons_text, parent, false);
        CheckedTextView checkTV=(CheckedTextView)convertView.findViewById(R.id.addonsItem);

        checkTV.setText(Temp.addonsName.get(position));
    }
    return convertView;
}

A: Try this
You need to implement else part first like the following
ViewHolder holder;

     if (convertView == null) {
    holder = new ViewHolder();
            convertView = LayoutInflater.from(getContext()).inflate(
                    R.layout.addons_text, parent, false);
            holder.checkTV=(CheckedTextView)convertView.findViewById(R.id.addonsItem);

    convertView.setTag(holder);
        }else{
    holder = (ViewHolder) convertView.getTag();
    }
     holder.checkTV.setText(Temp.addonsName.get(position));

And then create class
class ViewHolder {
            CheckedTextView checkTV;
}

Edit 1:
For your scrolling issue you need to follow the steps.
Step 1. Add your selected row value in a ArrayList
Step 2. in your getView add one condition
if(yourArrayList.contains(selected_value)){
holder.checkTV.setChecked(true);
}else{
holder.checkTV.setChecked(false);
}


text:
Q: How do I wrap a javascript function with dynamic arguments? I'd like to wrap some dynamically created javascript functions, similar to Daniel's accepted answer here:
How do I store javascript functions in a queue for them to be executed eventually
// Function wrapping code.
// fn - reference to function.
// context - what you want "this" to be.
// params - array of parameters to pass to function.
var wrapFunction = function(fn, context, params) {
    return function() {
        fn.apply(context, params);
    };
}

The difference is I'd like the argument values to be dynamic at time of execution - is it possible to pass a reference to a variable in the arguments, which could be updated after it is wrapped?
Here's what I'd like to do:
// I have a function to be wrapped
var sayStuff = function(a,b) {
    console.log(a);
    console.log(b);
}

// Variables I'd like to pass
var randomNumberA = 0;
var randomNumberB = 0;

// Wrap the function
var fun = wrapFunction(sayStuff, this, [*reference randomNumberA*,*reference randomNumberB*]);

// variables get changed
randomNumberA = Math.random()*100;
randomNumberB = Math.random()*100;

// Execute the function using current values of randomNumberA & randomNumberB
fun();

If possible I'd like to do this without changing sayStuff, I have a lot of existing functions like this I'm hoping to wrap, which also get used outside of the wrapping, so ideally I'd like to not replace the arguments with an object.
Hope that makes sense, Thanks!

A: If the function and the variable will be created in the same scope you can just use that:
var randomNumber = 0;
var fun = function(){ alert(randomNumber); }

randomNumber = 10;

// Now this will alert 10, because when fun is executed
// JS looks in his scope to find what randomNumber is.
fun();

This happens because functions in javascript works as Closures, they carry their environment with them. See: https://en.wikipedia.org/wiki/Closure_(computer_programming)
So if randomNumber will be changed out of the scope where you bind that function, you need to use an object, this is because in javascript we don't have "pointers" or references to pass by. One way is using a object.
function giveMeAFunction(){
  var params = { randomNumber: 0 }
  var fun = function(){ alert(scope.randomNumber); }
  return {fun: fun, scope: scope};
}

var paramsAndFun = giveMeAFunction()
// Now you can change the variables in the scope and call the function
paramsAndFun.params.randomNumber = 10;
paramsAndFun.fun(); // Will alert 10

// Now if you replace the entire params object it will not work
// This is because you will replacing it with a new object while
// The one that is referenced in the scope where fun was created is
// the old one.
paramsAndFun.params = { randomNumber: 15 };
paramsAndFun.fun(); // will still alert 10

Now let's get to binding part of the problem.
There is already Function.prototype.bind function to help you with that.
For example:
var sayStuff = function(opts) {
    alert(otions.randomNumber);
}

var options = { randomNumber: 0 };
var fun = sayStuff.bind(this, options);

options.randomNumber = 10;

fun(); // Will print 10

There is a lot going on here. Sorry if I made everything confuse.

A: If the dynamic arguments are defined in the context argument, a solution can be based passing the name of the variables and then, at execution time, calculate its current value:

var wrapFunction = function(fn, context) {
  var xArg = arguments;
  return function() {
    var argsArray = [];
    for (var i = 2; i < xArg.length; i++) {
      argsArray.push(context[xArg[i]]);
    }
    fn.apply(context, argsArray);
  };
}

var sayStuff = function() {
  for (var i = 0; i < arguments.length; i++) {
    console.log('sayStuff func: ' + arguments[i]);
  }
}

var randomNumber1 = 0;
var randomNumber2 = 0;

var fun = wrapFunction(sayStuff, this, 'randomNumber1', 'randomNumber2');

randomNumber1 = Math.random()*100;
randomNumber2 = Math.random()*100;

console.log('randomNumber1: ' + randomNumber1);
console.log('randomNumber2: ' + randomNumber2);

fun();


text:
Q: Using Hibernate's Criteria API, can I use concat with ilike restrictions? Intuitively, what I want to do is something like this:
Restrictions.ilike("concat(user.firstName, ' ', user.lastName)",
    text.toLowerCase() + "%")

However, I know that this won't work, because concat(user.firstName, ' ', user.lastName) is not a property that Hibernate understands, even though this is what I would have typed in a regular SQL statement as part of the where clause.
Is there any easy way to make this where restriction with Hibernate Criteria API, or do I have to fall back on good-old HSQL?
Thanks

A: One solution is to define fullName property in your User class.
@Formula(value="first_name || ' ' || last_name")
private String fullName;

And then use that filed in Criteria,
criteria.add(Restrictions.ilike("fullName", text.toLowerCase() + "%"));

A: I'm a little floppy on SQL so the statement may not be 100% accurate.
Obviously, this isn't an ilike but if you want to use SQL, why not use a sqlRestriction instead with a parameter?
Restrictions.sqlRestriction("select * from user where concat(user.firstName, ' ', user.lastName) like ?", text.toLowerCase() + "%", StandardBasicTypes.STRING);

I assume the goal is to be able to make a portable Restriction, in which case, this can sub in for your attempted ilike.


text:
Q: GCP: Health check not working on non-80-port I'm trying to set-up a managed instance group. The instance group is to run an image in which a Node.js server is listening on port 8080.
Setting up the template and the instance group works. I can SSH into the machine. docker ps gives me the expected results. And curl localhost:8080/v1/status results in OK.
Now I tried to add a health check - and that doesn't work. It always results in a TIMEOUT. According to the logs, no request of the health check reaches the Node.js server.
The logs of the health checker are not really helpful.
I triple-checked the settings in the health check. Path and port number are corrected.
I have looked at other projects with a similar setup. The only difference I spotted is the port. Those are using port 80. However, I cannot see why this should be an issue. If the port the server listens to and the port the health checker checks on are equal - then there should be no issue. But maybe I'm missing something here.
How can I debug this further? How can I see why the health check is failing? Can I add some port mapping from 8080 to 80 anywhere?

A: you need to add a firewall rule for this ip ranges and add your port/instance group as a destination
Health check source ranges for gcp

*

*35.191.0.0/16

*130.211.0.0/22

for more information please have a look at this doc
https://cloud.google.com/load-balancing/docs/firewall-rules


text:
Q: How do I set trigger to copy user_id to another table I need a trigger in phpmyadmin for 2 tables.
I have two tables called users and group_has_users. Table group_has_users has 2 values called group_id and user_id.
I'm trying to make a trigger that automatically inserts new data to group_has_users table with user_id when new user is created in users table( with group_id set to 1)
How to do this with phpmyadmin trigger?
insert into group_has_users (user_id) values (new.user_id);

I have no clue to make it group_id to set 1.

A: I think this is what you want:
delimiter $$

create trigger after_insert_users
after insert on users
for each row begin

if new.group_id = 1 then

insert into group_new_users (user_id) values (new.user_id);

end if;

end $$
delimiter ;

Note that you will have to run this in your cli or in mysql workbench

A: Everytime a new record is created in table users, you are looking to automatically create a new record in group_has_users, with a default group_id of 1.
Consider the following trigger:
DELIMITER //
CREATE TRIGGER users_after_insert
AFTER INSERT ON users FOR EACH ROW
BEGIN
    INSERT INTO group_has_users(group_id, user_id) VALUES(1, NEW.user_id);
END;
//

Demo on DB Fiddle:
DELIMITER //

CREATE TABLE users (user_id int)//
CREATE TABLE group_has_users (group_id int, user_id int)//

CREATE TRIGGER users_after_insert
AFTER INSERT ON users FOR EACH ROW
BEGIN
    INSERT INTO group_has_users(group_id, user_id) VALUES(1, NEW.user_id);
END;
//

INSERT INTO users(user_id) values(1);

SELECT * FROM group_has_users;

| group_id | user_id |
| -------- | ------- |
| 1        | 1       |


text:
Q: Ref Request: Geometric Du-Bois Raymond Lemma I've been looking everywhere for a reference for this "geometric" Du Bois-Raymond Lemma:

Here $\frac{DY}{dt}$ denotes the covariant derivative along $y$.

A: I found the second reference you gave in your comment, see [3].
In this paper, the authors refer to

the following "Du Bois-Raymond lemma", a straightforward extension of the classical lemma to a Riemannian manifold

Apart from the misspell, it seems that du Bois-Reymond's classical lemma has its own wikipedia article, which includes bibliographic references. Note that this wikipedia entry is in French, and the English version does not seem to have as much information. Du Bois-Reymond's original papers were published in [1, 2].
[1] P. du Bois-Reymond, Erläuterungen zu den Anfangsgründen der Variationsrechnung », Mathematische Annalen 15, no 2, 1879, p. 283-314
[2] P. du Bois-Reymond, Fortsetzung der Erläuterungen zu den Anfangsgründen der Variationsrechnung, Mathematische Annalen 15, no 2, 1879, p. 564-576
[3] J. Langer, and D.A. Singer, Curve straightening and a minimax argument for closed elastic curves, Topology 24 (1985), no. 1, 75--88.


text:
Q: what is the time complexity of the Array.prototype.length method in javascript? I've searched on MDN and w3schools, they don't provide infos on time complexity
as well as stack overflow
Javascript: Is the length method efficient? &
Is the Javascript String length constant time?
but none stated whether the length the method kept the size of the array every time it got modified, or it has to be calculated every time it's called.


text:
Q: Calculating "distances" from quantiles I am trying to compare the measurements from two different methods, A and B, that have each reported 16%, 50%, and 84% quantiles for a measurement X. How can I capture in a number how far away A and B are?
I would like to make some statement like "A is $3\sigma$ away from B" but I doubt it is possible in this case.

A: 16% and 84% quantiles are typically chosen with a mathematical fact in mind: in a normal or Gaussian distribution those quantiles are (closely, not exactly) 1 standard deviation away from the mean.
Hence you have three rough ways of estimating the SD of any variable reported that way:
84% quantile $-$ 50% quantile
50% quantile $-$ 16% quantile
(84% quantile $-$ 16% quantile) / 2
If these estimates are close, you may be good and Gaussian, although there are no guarantees. If these estimates are very different, then watch out.
Note also that you can use these quantiles to get a handle on asymmetry or skewness: in a symmetrical distribution, 16% and 84% quantiles will be equally distant from the 50% quantile, although equal spacing doesn't guarantee that the entire distribution is symmetric. But unequal spacing implies asymmetry, period, although whether it is important depends on magnitudes.
However, your question pivots on comparing samples, each reported in this way, which is more complicated. At best, the two interquantile ranges (and possibly the SDs) will be similar between datasets and then you can relate any difference between to shared variability.
This is mostly cautious or negative, but note a positive: these quantiles can be transformed by any convenient monotonic transformation, as (e.g.) log of quantile $=$ quantile of log, setting aside small print on exactly how the quantiles were calculated, possibly by interpolation between sample values. Hence you may find that there is a transformed scale on which variability of samples is about the same, which is then a scale on which to think.
Counsel of perfection or otherwise: nothing beats a view of all the data and good graphs of the same. Failing that, plotting three summary points for all samples may help you think about the data.


text:
Q: Writing out text with double double quotes - Python on Linux I'm trying to take the text output of a query to an SSD (pulling a log page, similar to pulling SMART data.  I'm then trying to write this text data out of a log file I update periodically.
My problem happens when the log data for some drives has double double-quotes as a placeholder for a blank field.  Here is a snippet of the input:
VER            0x10200
VID            0x15b7
BoardRev       0x0
BootLoadRev    ""
When this gets written out (appended) to my own log file, the text gets replaced with several null characters and then when I try to open all the text editors tell me it's corrupted.
The "" characters are replaced by something like this on my Linux system:
BootLoadRev "\00\00\00\00"
Some fields are even longer with the \00 characters.  If the "" is not there, things write out OK.
The code is similar to this:
f=open(fileName, 'w')
test_bench.send_command('get_log_page')
identify_data = test_bench.get_data_in()
f.write(identify_data)
f.close()

Is there a way to send this text to a file w/o these nulls causing problems?

A: Assuming that this is Python 2 (and that your content is thus what Python 3 would call a bytestring), and that your intended data format is raw ASCII, the trivial solution is simply to remove the NULs from your content before you write to disk:
f.write(identify_data.replace('\0', ''))


text:
Q: How can I structure jq filters to return video and audio codec information from ffprobe? In the interest of standardizing my video library I'm trying to find a way to quickly create a list of files that need to be converted. After looking at this question and its answer (and much googling) I think I have the basics figured out, but I'm having trouble elaborating on the jq section. For reference, the jq command I'm starting with is as follows:
jq -c '.format.filename as $path |
    .streams[]? |
    select(.codec_type=="video" and .codec_name!="h264") |
    .codec_name as $vcodec |
    {video: $vcodec, path: $path}'

and, for simplicity's sake, let's say this is what's being fed to jq:
{
    "streams": [
        {
            "index": 0,
            "codec_name": "hevc",
            "codec_type": "video"
        },
        {
            "index": 1,
            "codec_name": "aac",
            "codec_type": "audio"
        }
    ],
    "format": {
        "filename": "Video.mkv"
    }
}

which produces the following output:
{"video":"hevc","path":"./Video.mkv"}

This is great, but I want to go one step further - I would also like to include the codec used for any audio streams. So, given the same input, I would like the following output:
{"video":"hevc","audio":"aac","path":"./Video.mkv"}

How do I accomplish this?

A: To select both audio and  video codec types and exclude h264 video:
$ jq '.format.filename as $path |
    [.streams[]? | select(.codec_type=="audio"
                          or (.codec_type=="video"
                              and .codec_name!="h264")) |
     {(.codec_type): .codec_name, $path}] |
    group_by(.path) | map(add) | .[]' input.json
$ jq --version
jq-1.5-1-a5b5cbe

If a shell command becomes complex and it takes more than a few lines;
I switch to more verbose Python to manage the complexity:
result = dict(path=data['format']['filename'])
for stream in data['streams']:
    if (stream['codec_type'] == 'audio'
        or (stream['codec_type'] == 'video'
            and stream['codec_name'] != 'h264')):
        result[stream['codec_type']] = stream['codec_name'] # last value wins

data is the input (data = json.loads(json_text)) and result is the desired output (print(json.dumps(result))).
It should be relatively straightforward to adapt the above code for your particular case if you are more familiar with an imperative programming in Python than with a more functional style in jq.

A: Here is another approach.
$ jq -M '
  def getpath: {path: .format.filename} ;
  def getcodecs: [
        .streams[]?
      | {(.codec_type):.codec_name}
      | if . == {"video":"h264"} then empty else . end
    ] | add
  ;
  getpath + getcodecs
  ' input.json

Output
{
  "path": "Video.mkv",
  "video": "hevc",
  "audio": "aac"
}


text:
Q: Domain Driven Design: where does the workflow logic lie? In my project,i have workflow which operates on multiple entities to accomplish a business transaction. What is the best place to represent the workflow logic? currently i just create a "XXXManager" which is responsible for collaborating with entity objects to conclude a business transaction. Are there other options?

A: I'd say you're doing the right thing having something collaborate with multiple entities to get something done. The important thing is that each entity (and indeed each service) should have a single responsibility.
The overarching workflow you're talking about is something that you can consider as a part of your Application Layer.
According to Paul Gielens (paraphrased) The Application Layer's responsibility is to digest the course-grained requests (messages/commands) to acheive a certain overarching goal. It does this by sending a message to Domain Services for fulfillment. It then also (optionally) decides to send notifications to the Infrastructure Service.
But then what is a 'Service'?! It's an overloaded term but one that's described well (again, by Paul Gielens)
You might also want to read about Onion Architecture for more ideas...

A: Usually there is a domain object that should actually handle the control which is mistaken for an "entity".
Is there an instance of something that gets created as a result of this workflow?  If so, the workflow logic probably belongs in there.  Consider "Order" in the model below.
alt text http://img685.imageshack.us/img685/4383/order.png
Oder is both a noun and a verb.  The "Order" is the object that created as a result of "Ordering".  Like any good class, it has both data and behavior (and I don't mean getters and setters).  The behavior is the dynamic process that goes with the data, i.e., the ordering workflow.  "Order" is the controller.
This is why OO was invented.

A: DDD might not be exactly about this sort of thing,  so I would suggest taking a look at the Service Layer architectural pattern.  Martin Fowler's book Patterns of Enterprise Architecture is a good book that will explain it.  You can find the description of the pattern on Fowler's web site as well.

A: Creating Workflow systems can be a daunting prospect. Have you considered using Workflow engines?
If I understand you correctly, you will need to create a manager which keeps track of the different transactions in the worklflow, related to user. There are probably other ways of doing it - but I've always used engines.

A: To the great answers, I'd like to add "domain events" (link is just to one possible implementation) which is something Evans himself has come to put more focus on ("increased emphasis on events").


text:
Q: Display custom message when asking for facebook permissions Is there any way to display a custom message when asking for permissions with facebook js sdk? For example if I ask for email permissions, I would like to add a message "Your email is needed in order to send your key to your files". Or something like that. Is it possible? What I mean is, of course doing it within the facebook auth dialog, not showing an alert or something like that.

A: Nope.
The OAuth2 Dialog is coming from FB. That's the way it works: You MUST not change that (or even add things!)
But: consider the scope variable in the request, this should give the user a hint what access rights you're requesting already.


text:
Q: неадекватный total при пагинации springboot при различных параметрах size получаю разный total.
при size > количество элементов, total верный
при size <= количество элементов, total неверный
public GenericPage<FilterUserDto> getAllUserIds(@RequestParam(value = "fullTextQuery", required = false) String fullTextQuery,
                                                @ApiIgnore Pageable pageable) {
    Page<FilterUserDto> allUserIds = statisticsService.getAllUserIds(fullTextQuery, pageable);
    return new GenericPage<>(allUserIds.getContent(), allUserIds.getTotalElements());
}

верный тотал:
tasks/background/orgs/allUserIds?size=13
{"id":"JTC_SergeySV2_AdminDBO2","name":"JTC_SergeySV2_AdminDBO2"},{"id":"cf981379-68ed-42b0-b283-c733af367c6a","name":"system"}],"total":12}

неверный тотал:
tasks/background/orgs/allUserIds?size=12
{"id":"JTC_SergeySV2_AdminDBO2","name":"JTC_SergeySV2_AdminDBO2"},{"id":"cf981379-68ed-42b0-b283-c733af367c6a","name":"system"}],"total":2914}

сервис:
public Page<FilterUserDto> getAllUserIds(String fullTextQuery, Pageable pageable) {
    return taskRepository.getTaskUsers(formatFullTextQuery(fullTextQuery), pageable)
            .map(u -> new FilterUserDto(u.getId(), u.getName()));
}

репозиторий:
@Query(" SELECT distinct t.user " +
        " FROM Task t " +
        " WHERE :fullTextQuery is null or UPPER(t.user.name) like :fullTextQuery" +
        " order by t.user.name")
Page<User> getTaskUsers(@Param("fullTextQuery") String fullTextQuery, Pageable pageable);


text:
Q: Why can't TypeScript recognise installed TypeScript node_modules? This problem has long bothered me but I am at a loss as to why. I seem to always be fighting with node_modules. This isn't a @types issue.  I am trying to use TypeScript NPM Libraries which already have types.
A great example of this is font awesome. I follow the guide.
npm install @fortawesome/fontawesome-svg-core --save
It tell me that I should then go ahead and configure it using this syntax.
import { library, dom } from '@fortawesome/fontawesome-svg-core';

To which TypeScript informs me that this isn't a module.
I always have to resort to dirty paths like this:
import { library, dom } from '../node_modules/@fortawesome/fontawesome-svg-core/index';

Why does this work for everyone apart from myself?
Here is my tsconfig
{
    "compileOnSave": true,
    "compilerOptions": {
        "sourceMap": true,
        "allowJs": false,
        "allowUnreachableCode": false,
        "allowUnusedLabels": false,
        "declaration": false,
        "declarationMap": false,
        "diagnostics": true,
        "removeComments": true,
        "module": "es6",
        "target": "es5",
        "strict": false
    },
    "include": [
        "src/**/*"
    ]
}

A: With the "module": "es6" setting you have ES6 module generation. If your module is not node, TypeScript will default to Classic for module resolution. See: https://www.typescriptlang.org/docs/handbook/compiler-options.html
See: https://www.typescriptlang.org/docs/handbook/module-resolution.html -- which explains how Classic and Node module resolution work. You want "moduleResolution": "node" to import from node_modules the way you want.
You actually don't need module since target: ES5 will make module default to es6. You might want to revisit your setting for target.


text:
Q: Is it possible to start editing of input exactly where click happened when input is created after click? Imagine a situation, I've a text, once user clicks this text it is transformed into an input with same text which user clicked as a value.
I'm wondering if it is possible to make cursor appear exactly where click happened in the first place?
http://jsfiddle.net/nmaqa/
In this example, user first clicks to activate editing, and than he needs to click again where he wants cursor to appear.
$(document).on("click", ".click li.editable", function(){
        //
        var item = $(this);
        item.removeClass("editable");
        var word = item.html();
        item.empty();
        item.append('<input class="quick-edit" type="text" name="quick_edit" value="'+ word +'" />');
        $(".quick-edit").focus();
        //
    });

A: Yes it can be possible
html

Text

Text

and javascript
$(document).on("click", ".click li.editable", function(){
    //
    var item = $(this);
    item.removeClass("editable");
    var word = item.html();
    item.empty();
    item.append('<input class="quick-edit" type="text" name="quick_edit" value="'+ word +'" />');
    $(".quick-edit").focus();
    //
});
   $('.editable:first').focus()

Please update code or check ik fiddle  http://jsfiddle.net/nmaqa/1/

A:
I'm wondering if it is possible to make cursor appear exactly where
  click happened in the first place?

We have a property for any html element called contentEditable  take a look at this sample and see that what you want to implement, is a default behavior.

    write the html code  here

It's important to note that you don't need to implement this logic of replacement to enable an edit on a text element.


text:
Q: Rails app deployed at amazon aws and not all migration files get migrated I'm deploying my rails app at amazon aws and all works well, but after a while I have noticed that not all the migration files are being migrated and also some columns are missing from some tables. When I check inside the folder of the current app uploaded via ssh some migration files are missing. Does anybody have any idea why this is happening?
This the database.yml file setup:
production:
  <<: *default
  adapter: postgresql
  encoding: unicode
  database: <%= ENV['RDS_DB_NAME'] %>
  username: <%= ENV['RDS_USERNAME'] %>
  password: <%= ENV['RDS_PASSWORD'] %>
  host: <%= ENV['RDS_HOSTNAME'] %>
  port: <%= ENV['RDS_PORT'] %>


text:
Q: Float-ed outer div is not resizing to accommodate its children Here is code, highly condensed:

I_Would_Like_The_Outer_Div_To_Resize_To_Accomdate_This_Blob_Of_Text

It's floated-ed because I'm using floating to implement a float layout.

And here is the output.  I would like the outer div's width to expand so that the inner div contains the long blob of text.  Here's the output:

EDIT:
Wow.  I meant to say:

The outer div is float-ed because I'm using floating to implement a table-free COLUMN layout.

A: Just add word-wrap:break-word,

I_Would_Like_The_Outer_Div_To_Resize_To_Accomdate_This_Blob_Of_Text

It's floated-ed because I'm using floating to implement a float layout.

A: Try giving both DIVs width: auto and optionally set a min-width.


text:
Q: How to delete Cloud Firestore data automatically based on timers? I have data under certain collections that I want to have deleted automatically based on how long the user chooses the data to be inputted in the database for.
Is there a specific google firebase mechanism / method that I can apply, etc.
How would I go about doing so?

A: You can write a firebase cloud function with httpTrigger, but you will need to use a separate service to trigger it with cron jobs running.
If you are giving the user choice on a certain amounts they can chose, you can run cron jobs at all those intervals and handle which items to be deleted on trigger. If user's choice is arbitrary then you will probably want to run cron jobs at a certain smaller interval and handle which data to be deleted in the trigger function.
For cron jobs you can use something like cron-jobs.org that would trigger your function at certain time intervals. Or you can deploy your own service like https://github.com/firebase/functions-cron/ .


text:
Q: How to create a simple "hello world" Samsung S6 edge app I am wanting to create a simple app which will show some information on the Samsung S6s edge panel, and so I am starting to try to get the samsung exmaple running.
I've developed android application before (some time ago), but looking through the Samsung documentation I am lost, i'm sure i'm not the only one.
What I have tried so far
I have downloaded the samsung look sdk here: http://developer.samsung.com/galaxy#look
I can then import a project into eclipse from the samples called "EdgeScreenSampleApplication", and using android 19 I am able to compile it. However, I cannot run it on any emulator. I assume I need some special emulator to show the 'edge', but I cannot find one. When I run it on a Nexus emulator, I get:
[2015-03-21 21:01:33 - EdgeScreenSampleApplication] Installation error: Unknown failure
[2015-03-21 21:01:33 - EdgeScreenSampleApplication] Please check logcat output for more details.
[2015-03-21 21:01:33 - EdgeScreenSampleApplication] Launch canceled!

Now I am stuck, do I need a particular emulator? How can I get this thing running? I'd like to run it, then I can dig in to look at the code and see how it is working. Of course I do not have a Samsung S6 to test on as they are not yet released.


text:
Q: Auto increment jumps over ids I've created a scraping script which every hour go through different articles and add them to a database. However in this database table i've set unique key on date and title, so it wont add the same articles over and over. This however seem to great a weird effect where the ids on the news auto increment id seem to count up even though the news is not added? How can i fix this?
$insert_news = $con->prepare("INSERT IGNORE INTO news (`title`, `url`, `image_url`, `date`, `news_text`, `website_id`) VALUES (?, ?, ?, ?, ?, 2)");
$insert_news->bind_param("sssss", $hltv_title, $hltv_link, $hltv_img, $hltv_date, $full_text_dont);
$insert_news->execute();

A: Possible duplicate of INSERT IGNORE increases auto increment counter even no record is added? and prevent autoincrement on MYSQL duplicate insert. If you want to prevent gaps in your auto incremented ID's, you should consider changing the logic. For example, first check if the record exists (using a SELECT-query) before attempting to insert it.


text:
Q: operator overloading "+" & "++" in C# public class EncryptVal
{
    private EncryptVal(T value)
        {
        Set( value );
    }
    // Encrypt
public bool Set(T value)
{}

// Decrypt & return (T)value;
public T Get()
    {}

public static implicit operator EncryptVal<T>(T value) {
    //shuffle bits
    return new EncryptVal<T>(value);
}

public static implicit operator T(EncryptVal<T> value) {
    //unshuffle bits
    return value.Get(); ///// error ...
}
}

i couldnt overload the + operator & ++ operator. How can i do this?
usage:
EncryptVal<int> e = 42;
EncryptVal<int> f = 1;
Console.WriteLine("decrypt int count \t= {0:d}", f.Get()); // ok
Console.WriteLine("decrypt int count \t= {0:d}", f); // error
Console.WriteLine("decrypt int count \t= {0:d}", e); //how?

A: To overload + or ++ you simply add the + / ++ operators you want...
public static EncryptVal<T> operator ++(EncryptVal<T> value)
{
    throw new NotImplementedException(); // your implementation here
}
public static EncryptVal<T> operator +(EncryptVal<T> lhs, string rhs)
{
    throw new NotImplementedException(); // your implementation here
}
public static EncryptVal<T> operator +(EncryptVal<T> lhs, EncryptVal<T> rhs)
{
    throw new NotImplementedException(); // your implementation here
}
public static EncryptVal<T> operator +(EncryptVal<T> lhs, int rhs)
{
    throw new NotImplementedException(); // your implementation here
}
public static EncryptVal<T> operator +(bool lhs, EncryptVal<T> rhs)
{
    throw new NotImplementedException(); // your implementation here
}

It is unclear how this relates to the rest of the question, though.
In particular, the Console.WriteLine is probably going to want public override ToString() more than anything else.


text:
Q: Android InApp Purchase issue "Error while retrieving information from server.[RPC:S-7:AEC-0] " Currently i'm working on InApp Purchase for android app, done with the coding and testing it with gmail tester account, after i give all credit/debit card details for purchase of items, and pressed "save" button, there comes an error message Error while retrieving information from server.[RPC:S-7:AEC-0].
      To solve this i cleared all data and cache from playstore and rebooted the device. Still the issue remains the same. If anybody faced this type of issue please do help me...

A: Note that only cards with a US billing address can be added on the Wallet app.
Go to Settings and tap Credit and debit cards.
Tap the + sign, on the top-right corner, and enter your card's information. If you see a camera icon in the "Card number" field, you can take a picture of your card's number instead of entering it manually.
Tap Add credit or debit card.
Reference:
https://support.google.com/wallet/troubleshooter/3222463?hl=en&ref_topic=3209985#ts=2896139,2896157


text:
Q: Client-side form validators on Webforms are causing a postback even on error I'm using standard ASP.NET WebForms validation controls in my app. I've just noticed that at some point, client side validation seems to have stopped working as it should.  The web page correctly shows the errors in red for a short while, but then still causes an unnecessary postback which causes changes to get lost.
This is a .net 4.5 project.
I have the following appSetting:
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
Additionally, causesValidation is set to true on the submit button and the ValidationGroup has been set to the correct value on the button and validators etc.

A: To answer my own question, it was because I'd overridden the render method of the  tag (because I'm using URL rewriting) and as a side effect, it wasn't rendering the onclick attribute which is normally rendered server side.
Instead I changed my custom "ActionlessForm" control to use the following code:
public class Form : System.Web.UI.HtmlControls.HtmlForm
{
    /// <summary>
    /// The RenderAttributes method adds the attributes to the rendered <form> tag.
    /// We override this method so that the action attribute is not emitted.
    /// </summary>
    protected override void RenderAttributes(HtmlTextWriter writer)
    {
        // You cannot simply remove the form action as it seems to get rendered anyway
        // but if you set it to the RawURL it will be the correct value on URL rewritten pages.
        base.Attributes["action"] = HttpContext.Current.Request.RawUrl;
        base.RenderAttributes(writer);
    }
}


text:
Q: Testing if two models have a significant different forecast (error) I have two different models which estimate a continuous variable $X$ depending on N categorial covariates $V_i$.
Is there a way to test if both models produce significantly different results? I could test for differences of their mean, median, variance, and distribution. However, how can I account for the categorial covariates?
If all covariates $V_i$ are regarded there is only one forecast value for each combination of the covariates' values. Hence there is no distribution. What can I test here - MSE/RMSE, MAE? Can I test these measures statistically at all? There is a question on how to compare the accuracy of two different models using statistical significance which is unfortunately unanswered.
In addition the observered value for each combination of the N categorial variables is known. Does it make a difference to test the forecast error instead of the forcast value? A related question on the comparison of two error distributions to determine "goodness of fit" is answered. However, the answer assumes an error estimate $\sigma_i$ for the experimentally measured values which correspond to my observed values. I do not have such an estimation because my observed values are simple countings of how often a covariate combination is observed in the whole population.
To make my problem clear: I can calculate the error $E$ for each of the combination of the covariates' values. Afterwards I could test if $E_1$ and $E_2$ of the models $M_1$ and $M_1$ are different with respect to their mean, median, variance, and distribution. However, what if both models have the same forecast errors, but in very different combinations of the covariates' values?


text:
Q: Is it possible to bound $C_1x^{-2\alpha}+C_2x^{2\beta+1}\le C_3$ from below? Consider the inequality
$$\underbrace{C_1x^{-2\alpha}+C_2x^{2\beta+1}}_{(\ast)}\le C_3$$
where $C_1,C_2,C_3>0$ are positive constants which all depend on $\alpha$ and $\beta$ and $\alpha,\beta>0$ are positive exponents and $x\in\mathbb{R}_{>0}$
Is it possible to bound $(\ast)$ from below? I was also wondering if one could estimate $x$, but I suppose that this is out of the question

A: Yes, it is possible.
$y=C_1x^{-2\alpha}$ is decreasing, and $y=C_2x^{2\beta+1}$ is increasing.
So, there is only one real solution for $C_1x^{-2\alpha}=C_2x^{2\beta+1}$. Let it be $x=\gamma$.
For $0\lt x\le\gamma$,
$$C_1x^{-2\alpha}+C_2x^{2\beta+1}\ge C_1\gamma^{-2\alpha}+0=C_1\gamma^{-2\alpha}$$
For $\gamma\lt x$,
$$C_1x^{-2\alpha}+C_2x^{2\beta+1}\gt 0+C_2\gamma^{2\beta+1}=C_1\gamma^{-2\alpha}$$
It follows from these that, for $x\gt 0$,
$$C_1\gamma^{-2\alpha}\le C_1x^{-2\alpha}+C_2x^{2\beta+1},$$
i.e.
$$C_1\left(\frac{C_1}{C_2}\right)^{\frac{-2\alpha}{2\alpha+2\beta+1}}\le C_1x^{-2\alpha}+C_2x^{2\beta+1}$$


text:
Q: RoutedCommand defaults to cannot execute I am using a custom RoutedCommand in a context menu.  The command is definedlike this:
public static readonly RoutedCommand RoutedAddMainHeading = new RoutedCommand();

And it is accessed like this:
<ContextMenu>
    <MenuItem Header="Add Main Heading" Command="local:JurisdictionVM.RoutedAddMainHeading" />
</ContextMenu>

It works fine, except when my program starts, the command is disabled.  After I click on a text box in the window it becomes enabled.
If I use a custom ICommand implementation (with CanExecute always returning true) this doesn't happen, but the command will not be routed.
I tried to call CommandManager.InvalidateRequerySuggested but this doesn't seem to do anything.
I am using a command sink to define the command binding and link it to my ViewModel, which may be causing the problem.  I am using an implementation I found here: http://www.codeproject.com/KB/WPF/VMCommanding.aspx
UPDATE: It doesn't look like the custom command binding is the problem.  I tried a standard CommandBinding linked to code-behind methods and have the same issue.  THe CommandBinding is defined like:
<CommandBinding Command="local:JurisdictionVM.RoutedAddMainHeading" CanExecute="Foo_CanExecute" Executed="Foo_Executed"/>

It seems that this is a problem unique to ManuItem.  I do not have this issue if I use this command in a button.
Is there another way to force a re-evaluation of CanExecute?
Or a way to get RoutedCommand to default to enabled (or a way to write a custom one)?

A: Try calling CommandManager.InvalidateRequerySuggested().

A: It looks like this is the same problem as here:
Why is this WPF RoutedCommand bound Context MenuItem disabled?
The solution is to set the focus in the window constructor.


text:
Q: MX or A record issues We have a mail server (Mailenable) which we are using to sell email accounts to our clients.
We have one client that could not send email to a specific domain and they receieve this error from the domain's email server:

Reason: The message could not be delivered because the domain name  ourclientcompanyname.com does not have any DNS records.

The company that uses us for email does not have any DNS records for their domain ourclientcompanyname.com
MX records are fine but the domain has no other DNS records. Is that a possible error? What DNS records should the client should add?

A: RFC 5321 section 2.3.5 requires that domain names used in email be resolvable to addresses.
From the relevant parts:

Only resolvable, fully-qualified domain names (FQDNs) are permitted
when domain names are used in SMTP.  In other words, names that can
be resolved to MX RRs or address (i.e., A or AAAA) RRs (as discussed
in Section 5) are permitted, as are CNAME RRs whose targets can be
resolved, in turn, to MX or address RRs.  Local nicknames or
unqualified names MUST NOT be used.  There are two exceptions to the
rule requiring FQDNs:

*

*The domain name given in the EHLO command MUST be either a primary
host name (a domain name that resolves to an address RR) or, if
the host has no name, an address literal, as described in
Section 4.1.3 and discussed further in the EHLO discussion of
Section 4.1.4.

This is not a new requirement; RFC 2821 section 2.3.5 (2001) had similar language.

The domain name, as described in this document and in [22], is the
entire, fully-qualified name (often referred to as an "FQDN").  A
domain name that is not in FQDN form is no more than a local alias.
Local aliases MUST NOT appear in any SMTP transaction.

If your mail server says EHLO company.example and company.example can't be resolved to an address, then it's perfectly valid to reject that connection. The same is true of the domain names used in the sender and recipient addresses (with the exception of postmaster, which doesn't require a domain name at all).
(Prior to RFC 2821, the governing standards were RFC 821 and RFC 974, which date to the 1980s and had to accommodate many non-Internet networks which no longer exist, thus the standards were much less restrictive.)

A:
MX records are fin but the domain has no dns record at all. Is that a
  possible error? What dns record the client should add?

Yes, some mail servers, upon receipt of an email, check to see that the domain for the sending user, not just the sending server, has DNS records. I think it's a bit silly, and not a great check for spam, but it is what it is. Your client most likely needs to simply put an A record in for their ourclientcompanyname.com apex domain. Get them a $5 hosting account and a single page informational website for good measure, just to be nice.
EDIT:
Buried within ye olden RFC 5321, it says in section 2.3.5:

Only resolvable, fully-qualified domain names (FQDNs) are permitted when domain names are used in SMTP.

Noice! I still think it's a silly to think of it as a spam deterrent and is a correlation/causation conflation, but hey at least it's a documented standard and following it has some positive side effects on the spam folder! Who has two thumbs and just got RFC schooled?

A: In order for mail to function properly there are three DNS records that are required.

*

*A Record - Host name to IP address mapping

*MX Record - The MX record is bound to the A Record for the mail server

*Reverse Lookup - The IP address needs to be bound to the A record for reverse lookup (SPAM Prevention)
As well, the PAT address at the firewall needs to be set for the mail server so the public IP (source IP) of the mail server matches the reverse lookup.
You will typically need to get with your ISP and have them create the reverse lookup if they own the IP addresses you are using on the public side.
Note: There is no RFC regarding Forward-Confirmed Reverse DNS.  It is simply a best practice.


text:
Q: Openlayers 3 Cluster Strategy not projecting properly My Openlayers map is not displaying clustered points properly and I'm not sure why. My code is pretty simple and straight forward, here it is:
JSfiddle: http:// jsfiddle.net/1z5zyu4d/13/)
 <!doctype html>

<link rel="stylesheet" href="http://openlayers.org/en/v3.5.0/css/ol.css" type="text/css">

<title>AIS Map</title>

Cluster map of ships broadcasting AIS data

I'm basing this heavily off of the examples here: https:// openlayersbook.github.io/ch05-using-vector-layers/example-02.html and here: http:// openlayers.org/en/v3.2.0/examples/cluster.html. The problem I'm having is that the cluster shows up as one point centered at (0,0) like this. Upon zooming in, the cluster expands, as it should. What's weird though(besides it not mapping it right in the first place) is that when you zoom in the points are projected like this. The points are projected to the same locations they should be as if that one single tile is being treated like the whole world. The real locations of the points looks like this: http:// imgur.com/TLARMra. See how the x/y locations of the ships when overlayed on the whole world are the same as the x/y locations when overlayed on that one tile.  There's a few less points on the one with boat icons but you can see the clusters around China, France/Germany, and the Eastern US coast all translate to the incorrect projection, along with all the others that are on both maps(The cluster data has a few more points than the non cluster data added for testing specific cases). So I'm almost positive that this is an issue with projection EPSG, etc. but I think I've tried every EPSG code in all different combinations(like including the projection in the layer itself caused the layer to not appear) to no avail. Firebug gives me no errors and it says ol.js is loading fine along with the ol.css. So basically I don't know what is causing this and I don't know how to fix it.
I would also like to mention that I'm using OL3 and specifically 3.2

My GeoJSON looks like this:
 {
"type": "FeatureCollection",
"features":[
{
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [
            0.13138,
            49.4756
        ]
    },
    "properties": {
        "MMSI": "227006760",
        "NAVIGATION STATUS": "0"
    }
},//...about 30 of those^
]
}

Working jsfiddle, still the same problem http:// jsfiddle.net/1z5zyu4d/13/

A: Here's an example using OpenLayers version 3.6.0
http://jsfiddle.net/t3n55fzq/
This is the part that allows you to reproject features during read.
var originalSource = new ol.source.Vector({
    features: (
        new ol.format.GeoJSON()).readFeatures(geojsonObject,{
            dataProjection:'EPSG:4326',
            featureProjection:'EPSG:3857'
        }
    )
});

You should also look at defining your projections inside the GeoJSON.  e.g.
'crs': {
    'type': 'name',
    'properties': {
      'name': 'EPSG:4326'
    }
  }

If you're loading in from a external source try:
var originalSource = new ol.source.Vector({
    url: 'test.geojson',
      format: new ol.format.GeoJSON({
         defaultDataProjection :'EPSG:4326',
         projection: 'EPSG:3857'
   })
});


text:
Q: Jquery validate require from group not working Having some trouble with this function of the validation plugin:
http://jqueryvalidation.org/require_from_group-method
Related part of the form:
<input class="org-group" type="checkbox" name="org[1]" id="org[1]" value="on">
<input class="org-group" type="checkbox" name="org[2]" id="org[2]" value="on">
<input class="org-group" type="checkbox" name="org[3]" id="org[3]" value="on">

This list of checkboxes is dynamic. It could have 2 entries, or 50 entries, that's why I am using an array in the form. I want the plugin to ensure that one of the xxx checkboxes in the org-group class is checked.
I use this in the plugin:
$( "#orgform" ).validate({
  rules: {
    org[]: {
      require_from_group: [1, ".org-group"]
    },

However, it's not working. The form just submits regardless the amount of boxes checked. The "submithandler" works fine. I have some other text fields in this form which are required. If these fields are not filled, the validation runs fine.
What am I doing wrong?

A: You need to make sure you've referenced all of the required JQuery libraries. If you're using just the core library, validation won't work.
Make sure you're also referencing additional-methods.min.js
Fiddle Example
Once you have all of the required references, you'll need to modify your html content, so that all of your check boxes have the same name. Validation won't work if all of the names are unique. The ids will obviously have to remain unique.
Updated Html:
<form id="orgform">
  <input class="org-group" type="checkbox" name="org" id="org[1]" value="on">
  <input class="org-group" type="checkbox" name="org" id="org[2]" value="on">
  <input class="org-group" type="checkbox" name="org" id="org[3]" value="on">
  <input class="org-group" type="checkbox" name="org" id="org[4]" value="on">
  <input type="submit" value="Validate">
</form>

Notice that all of the checkboxes have a name of "org".
After you've updated your html, update the call to validate to reference "org" instead of "org[]". If you inspect the console you'll notice the following error:
Uncaught SyntaxError: Unexpected token [

This is because the rules property doesn't accept [ or ]
With the html changes, you'll also need to update your JQuery.
Updated JQuery:
$("#orgform").validate({
  rules: {
    org: {
      require_from_group: [1, ".org-group"]
    }
  }
});

Note: Please see the Fiddle example I've linked above for a working example.


text:
Q: FIRApp.Configure Crashing App I am using Xcode and Swift. My application keeps crashing and saying "The default app has not been configured yet." But I do have it configuring in my appDelegate. Has anyone encountered this issue?

A: I use the override init() method in the AppDelegate to configure Firebase. The Firebase documentation shows the configuration in the didFinishLaunchingWithOptions method but I haven't gotten that approach to work in my apps.
import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    override init() {
        FIRApp.configure()
    }

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        return true
    }
}