text:
Q: Forecasting time series using ARMA-GARCH in R I'm using rugarch package to estimate and forecast my time series. First, I estimate an ARMA model:
y <- readRDS("y.rds")
y.test <- readRDS("y-test.rds")
m1.mean.model <- auto.arima(y, allowmean=F )
ar.comp <- arimaorder(m1.mean.model)[1]
ma.comp <- arimaorder(m1.mean.model)[3]

But usually the error terms show typical characteristics of a GARCH process. Subsequently, I fit an ARMA-GARCH(1,1) process, and preform one-step ahead forecasting on test data:
library(rugarch)
model.garch = ugarchspec(mean.model=list(armaOrder=c(ar.comp,ma.comp)),
                         variance.model=list(garchOrder=c(1,1)),
                         distribution.model = "std")
model.garch.fit = ugarchfit(data=c(y,y.test), spec=model.garch, out.sample = length(y.test),  solver = 'hybrid' )

modelfor=ugarchforecast(model.garch.fit, data = NULL, n.ahead = 1, n.roll
                        = length(y.test), out.sample = length(y.test))

results1 <- modelfor@forecast$seriesFor[1,] + modelfor@forecast$sigmaFor[1,]
results2 <- modelfor@forecast$seriesFor[1,] - modelfor@forecast$sigmaFor[1,]

ylim <- c(min(y.test), max(y.test))
plot.ts(y.test , col="blue", ylim=ylim)
par(new=TRUE)
modelfor@forecast$seriesFor[1,]  %>% plot.ts(ylim=ylim)
par(new=TRUE)
plot.ts(results1, col="red", ylim=ylim)
par(new=TRUE)
plot.ts(results2, col="red", ylim=ylim)

This is where I get confused. Looking at the predictions for the mean (modelfor@forecast$seriesFor, black), they barely move from zero. However, if I add sigma to it, it comes very close. In fact, forecasts of sigma (second plot) show that it is capturing the changing variance. My question is, given that we know forecasts of the variance enter in the equation for mean prediction (for example p.204 of this book), why is it that my forecasts are so poor?
data: y-test.rds, y.rds

A: Obtaining accurate point forecasts for financial time series is notoriously hard. That has to do with the nature of the financial markets; actors look for opportunities to exploit any predictability, and they remove it while they are doing it (change in expected profitability of an asset $\rightarrow$ change in supply/demand $\rightarrow$ change in asset price). This happens very quickly in active markets, so that the predictability does not persist long enough for models to capture it. Thus financial time series often behave like random walks with some heteroskedasticity.
Meanwhile, volatility of financial time series is easier to predict as apparently there is no market mechanism to remove the predictability. That is why your GARCH forecasts of volatility seem to work rather well.
But you should note that graphs of fitted volatility vs. realized squared returns can be somewhat misleading. Leaving aside the fact that squared returns are only a noisy proxy of realized volatility, there is another thing: our eyes are easily tricked by graphs like the first one in your post. When it comes to goodness of fit, our eyes pay attention not only to to the vertical distance between fitted and realized values, which is what matters, but also to horizontal distance. So instead of graphing fitted. vs. realized values (two lines), it is helpful to graph just the difference between the two (one line). You might be surprised to discover that differences which appear small from the first type of graph are not that small when depicted in the second type of graph. This is because the fitted volatility from GARCH typically lags the realized volatility by one period. If a time series has many data points, this lag (the horizontal difference) is visually small and can hardly be noticed, so the fit looks better than it actually is.


text:
Q: fling and pinchzoom for an imageview in one activity I have an Imageview(like a Magazine page).When i swype in to that image then i want the next image(page).Also want Zoom in and out option  for this image.How i can achieve this?
Thanks

A: Assuming you already researched separately on pinch-to-zoom and swipe gestures, you may want to impose limitations on useability. When the image is zoomed (occupying an area greater than the screen size), you should disable swipe detection, and enable it again once the image size is less than the screen size.

A: I implemented such a library. There are still minor issues but it's functional and can be extended.
Here's the fork on github: https://github.com/kilaka/ImageViewZoom
Enjoy.

A: Found this post on a a gallery (swipe between photos) with pinch-to-zoom.

A: I recently implemented it and it works great
https://github.com/chrisbanes/PhotoView

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# to C++ function equivelent - .tostring("X4") Is there a functional equivalent for the C# function .tostring("X4"), to C++?
I've been scratching my head for a few days wondering why my sensor is reporting a different serial number to what the manufacturer software (written in C#) and what my C++ code reports. The serial number is also written on the sensor, which ties in with what the manufacturer C# code reports. On inspection of their source code, they're using the .tostring("X4") function to convert it to "human readable", which makes sense (from a "oh thats why it's different", not a "why on earth would you do that" point of view).
For further info - https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings
A similar question but C# to Java - C# .ToString("X4") equivalent in Java

A: There's is no readily available equivalent function in C++, but you could create one that works in a similar way:
#include <iostream>
#include <sstream>
#include <string>

template<class T>
std::string tostringX(unsigned len, T v) {
    std::ostringstream os;
    os << std::hex << v;
    auto rv = os.str();
    if(rv.size() < len) rv = std::string(len - rv.size(), '0') + rv;
    return rv;
}

int main() {
    std::cout << tostringX(4, 0xFEDC) << '\n'; // outputs "fedc"
}

A:  #include <iostream>
    #include<sstream>
    #include <iomanip>

    int main() {
        int x = 12;
        std::stringstream stream;
        stream << std::setfill('0') << std::setw(4)<< std::hex << x;
        std::cout << stream.str();
    }

Output : 000c
I guess that's the answer you're looking for.


text:
Q: How to write on Manifest file for Add-on I have a script that extracts the questions and answers of a quiz created in Google Forms. However, I am having difficulty creating the add-on.
The following is the function:
function myFunction() {
  // TODO: try to get another form by ID
  //var form1 = FormApp.getActiveForm();
  var form1 = FormApp.openById('1OLu1xIL6qThi44Y9NJddE-TdBxIA4_Txj7M9z_oxKlU');
  //var form1 = FormApp.openByUrl('https://docs.google.com/forms/d/e/1OLu1xIL6qThi44Y9NJddE-TdBxIA4_Txj7M9z_oxKlU');
  var items = form1.getItems();
  console.log("total questions: " + items.length);
  for (var i = 0; i < items.length; i++) {
    var item = items[i];
    //console.log(item.getType() === FormApp.ItemType.MULTIPLE_CHOICE);
    //console.log(item.getType());
    var x = 0;
    console.log('***** New Question *****');
    switch(item.getType()) {
      case FormApp.ItemType.MULTIPLE_CHOICE:
        this.extractMultipleChoice(item);
        break;
      case FormApp.ItemType.CHECKBOX:
        this.extractCheckbox(item);
        break;
      case FormApp.ItemType.PARAGRAPH_TEXT:
        this.extractParagraphText(item);
        break;
      case FormApp.ItemType.TEXT:
        this.extractText(item);
        break;
    }
  }
}
function extractMultipleChoice(item) {
  var question = item.asMultipleChoiceItem();
  console.log("Question: " + question.getTitle());
  console.log("Number of answers: " + question.getChoices().length);
  var answers = question.getChoices();
  for (var j = 0; j < answers.length; j++) {
    var answer = answers[j];
    console.log(answer.getValue());
    console.log("Is correct answer? " + answer.isCorrectAnswer());
  }
}
function extractCheckbox(item) {
  var question = item.asCheckboxItem();
  console.log("Question: " + question.getTitle());
  console.log("Number of answers: " + question.getChoices().length);
  var answers = question.getChoices();
  for (var k = 0; k < answers.length; k++) {
    var answer = answers[k];
    console.log(answer.getValue());
    console.log("Is correct answer? " + answer.isCorrectAnswer());
  }
}
function extractParagraphText(item) {
  var question = item.asParagraphTextItem();
  console.log("Question: " + question.getTitle());
}
function extractText(item) {
  var question = item.asTextItem();
  console.log("Question: " + question.getTitle());
}

If I run this, I am able to extract the questions and answers from the quiz.
Per my understanding, to deploy the add-on, I would need to update the manifest file that includes details of the function that has been created. However, when attempting to update the manifest file, I get the following error: "appsscript.json" has errors: Invalid manifest: unknown fields: [form]
I have read the documentation but I am not getting it.
Here is what I have done so far:
  {
  "timeZone": "America/Los_Angeles",
  "dependencies": {
    "enabledAdvancedServices": [
      {
        "userSymbol": "AdSense",
        "version": "v2",
        "serviceId": "adsense"
      }
    ]
  },
  "form": {
    "name": "Extract Q&A",
    "logoUrl": "g",
    "primaryColor": "#4285F4",
    "secondaryColor": "#00BCD4",
    "authorizationCheckFunction": "get3PAuthorizationUrls",
    "contextualTriggers": [
      {
        "unconditional": {},
        "onTriggerFunction": "buildAddOn"
      }
    ]
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"
}


text:
Q: Do I understand not using getters and setters correctly After reading this piece by Yegor about not using getters and setters, it sounds like something that makes sense to me.
Please note this question is not about whether doing it is better/worst, only if I am implementing it correctly
I was wondering in the following two examples in VBA, if I understand the concept correctly, and if I am applying it correctly.
The standard way would be:
Private userName As String

Public Property Get Name() As String
    Name = userName
End Property
Public Property Let Name(rData As String)
    userName = rData
End Property

It looks to me his way would be something like this:
Private userName As String

Public Function returnName() As String
    returnName = userName
End Function

Public Function giveNewName(newName As String) As String
    userName = newName
End Function

From what I understand from the two examples above is that if I wanted to change the format of userName (lets say return it in all-caps), then I can do this with the second method without changing the name of the method that gives the name through - I can just let returnName point to a userNameCaps property. The rest of my code in my program can still stay the same and point to the method userName.
But if I want to do this with the first example, I can make a new property, but then have to change my code everywhere in the program as well to point to the new property... is that correct?
In other words, in the first example the API gets info from a property, and in the second example the API gets info from a method.

A: Your 2nd snippet is neither idiomatic nor equivalent. That article you link to, is about Java, a language which has no concept whatsoever of object properties - getFoo/setFoo is a mere convention in Java.
In VBA this:

Private userName As String

Public Property Get Name() As String
    Name = userName
End Property
Public Property Let Name(rData As String)
    userName = rData
End Property

Is ultimately equivalent to this:
Public UserName As String

Not convinced? Add such a public field to a class module, say, Class1. Then add a new class module and add this:
Implements Class1

The compiler will force you to implement a Property Get and a Property Let member, so that the Class1 interface  contract can be fulfilled.
So why bother with properties then? Properties are a tool, to help with encapsulation.
Option Explicit
Private Type TSomething
    Foo As Long
End Type
Private this As TSomething

Public Property Get Foo() As Long
    Foo = this.Foo
End Property

Public Property Let Foo(ByVal value As Long)
    If value <= 0 Then Err.Raise 5
    this.Foo = value
End Property

Now if you try to assign Foo with a negative value, you'll get a runtime error: the property is encapsulating an internal state that only the class knows and is able to mutate: calling code doesn't see or know about the encapsulated value - all it knows is that Foo is a read/write property. The validation logic in the "setter" ensures the object is in a consistent state at all times.
If you want to break down a property into methods, then you need a Function for the getter, and assignment would be a Sub not a Function. In fact, Rubberduck would tell you that there's a problem with the return value of giveNewName being never assigned: that's a much worse code smell than "OMG you're using properties!".
Functions return a value. Subs/methods do something - in the case of an object/class, that something might imply mutating internal state.
But by avoiding Property Let just because some Java guy said getters & setters are evil, you're just making your VBA API more cluttered than it needs to be - because VBA understands properties, and Java does not. C# and VB.NET do however, so if anything the principles of these languages would be much more readily applicable to VBA than Java's, at least with regards to properties. See Property vs Method.
FWIW public member names in VB would be PascalCase by convention. camelCase public member names are a Java thing. Notice how everything in the standard libraries starts with a Capital first letter?

A: It seems to me that you've just given the property accessors new names. They are functionally identical.
I think the idea of not using getters/setters implies that you don't try to externally modify an object's state - because if you do, the object is not much more than a user-defined type, a simple collection of data. Objects/Classes should be defined by their behavior. The data they contain should only be there to enable/support that behavior.
That means you don't tell the object how it has to be or what data you want it to hold. You tell it what you want it to do or what is happening to it. The object itself then decides how to modify its state.
To me it seems your example class is a little too simple to work as an example. It's not clear what the intended purpose is: Currently you'd probably better off just using a variable UserName instead.
Have a look at this answer to a related question - I think it provides a good example.

Regarding your edit:

From what I understand from the two examples above is that if I wanted
  to change the format of userName (lets say return it in all-caps),
  then I can do this with the second method without changing the name of
  the method that gives the name through - I can just let returnName
  point to a userNameCaps property. The rest of my code in my program
  can still stay the same and point to the method iserName.
But if I want to do this with the first example, I can make a new
  property, but then have to change my code everywhere in the program as
  well to point to the new property... is that correct?

Actually, what you're describing here, is possible in both approaches. You can have a property
Public Property Get Name() As String
    ' possibly more code here...
    Name = UCase(UserName)
End Property

or an equivalent function
Public Function Name() As String
    ' possibly more code here...
    Name = UCase(UserName)
End Function

As long as you only change the property/function body, no external code needs to be adapted. Keep the property's/function's signature (the first line, including the Public statement, its name, its type and the order and type of its parameters) unchanged and you should not need to change anything outside the class to accommodate.

A: The Java article is making some sort of philosophic design stance that is not limited to Java: The general advise is to severely limit any details on how a class is implemented to avoid making one's code harder to maintain. Putting such advice into VBA terms isn't irrelevant.
Microsoft popularized the idea of a Property that is in fact a method (or two) which masquerade as a field (i.e. any garden-variety variable). It is a neat-and-tidy way to package up a getter and setter together. Beyond that, really, behind the scenes it's still just a set of functions or subroutines that perform as accessors for your class.
Understand that VBA does not do classes, but it does do interfaces. That's what a "Class Module" is: An interface to an (anonymous) class. When you say Dim o As New MyClassModule, VBA calls some factory function which returns an instance of the class that goes with MyClassModule. From that point, o references the interface (which in turn is wired into the instance). As @Mathieu Guindon has demonstrated, Public UserName As String inside a class module really becomes a Property behind the scenes anyway. Why? Because a Class Module is an interface, and an interface is a set of (pointers to) functions and subroutines.
As for the philosophic design stance, the really big idea here is not to make too many promises. If UserName is a String, it must always remain a String. Furthermore, it must always be available - you cannot remove it from future versions of your class! UserName might not be the best example here (afterall, why wouldn't a String cover all needs? for what reason might UserName become superfluous?). But it does happen that what seemed like a good idea at the time the class was being made turns into a big goof. Imagine a Public TwiddlePuff As Integer (or instead getTwiddlePuff() As Integer and setTwiddlePuff(value As Integer)) only to find out (much later on!) that Integer isn't sufficient anymore, maybe it should have been Long. Or maybe a Double. If you try to change TwiddlePuff now, anything compiled back when it was Integer will likely break. So maybe people making new code will be fine, and maybe it's mostly the folks who still need to use some of the old code who are now stuck with a problem.
And what if TwiddlePuff turned out to be a really big design mistake, that it should not have been there in the first place? Well, removing it brings its own set of headaches. If TwiddlePuff was used at all elsewhere, that means some folks may have a big refactoring job on their hands. And that might not be the worst of it - if your code compiles to native binaries especially, that makes for a really big mess, since an interface is about a set of function pointers layed out and ordered in a very specific way.
Too reiterate, do not make too many promises. Think through on what you will share with others. Properties-getters-setters-accessors are okay, but must be used thoughtfully and sparingly. All of that above is important if what you are making is code that you are going to share with others, and others will take it and use it as part of a larger system of code, and it may be that these others intend to share their larger systems of code with yet even more people who will use that in their even larger systems of code.
That right there is probably why hiding implementation details to the greatest extent possible is regarded as fundamental to object oriented programming.


text:
Q: Get a new string based upon a existing string with a specific length I'm having problems figuring out how to produce a new string based upon an existing one. The newly created string is supposed to have a specific length. It would be much easier if a could only repeat the provided string using the build-in repeat function, but that would not produce the expected result in regard to its length.
I have the following string:
const str = 'abc';

I need to repeat it n number of times:
const desiredLength = 10; // e.g.

So, I tried something like this:
const string = "abc";
const len = 10;

// I took the string and made it into a array of characters
const strArr = string.split('');
// I created a new (empty) arry
const newArr = [];

// I used a for-in loop
for(let i in strArr){
// Implemented a simple condition
  while(newArr.length < len) {
// And finally uushed items to my new array
    newArr.push(strArr[i]);
  }
}

But when I log it to the console I get [a,a,a,a,a,a,a,a,a,a]

The desired result would be the following:
[a,b,c,a,b,c,a,b,c,a]
My idea was to push elements to a new array, one by one until the desired length is achieved, so I would be able to manipulate the array afterward or/ and turn it into a desired string again using the join function. What am I doing wrong here and is there a better (totally) different way of achieving this?

A: A short approach uses String#padEnd.
The supplied string is being repeated or truncated until the wanted length.

var string = 'abc',
    length = 10,
    result = ''.padEnd(length, string);

console.log(result);
console.log(result.length);

A: The issue with your code is it will only consider the first i. After that, while loop will be populating the same strArr[i] until reaches len. After the first item in strArr, it never enters the while loop because it will not satisfy the condition
You could use Array.from() to get an array of specified length. The value at each index will be decided based on the index % str.length

function repeat(str, length) {
  return Array.from({ length }, (_, i) => str[i % str.length])
}

console.log(JSON.stringify(repeat("abc", 10)))
console.log(JSON.stringify(repeat("javascript", 15)))


text:
Q: How to use SupportFragmentManager on a Fragment I'm trying to use support fragment manager in a fragment but it says SupportFragmentManager doesn't exist in the current context.
Here's my code
        private void Adapter_RateItemClick(object sender, DriversAdapterClickEventArgs e)
        {
                RatingFragment editAluminiFragment = new RatingFragment();
                var trans = SupportFragmentManager.BeginTransaction();
                editAluminiFragment.Show(trans, "Rate");
        }

I used

using FragmentManager = Android.Support.V4.App.FragmentManager;
  ?
  what should I do next

A: Firstly, there is documentation AndroidX Fragment class (it is similar for support v4, but you definitely should switch to AndroidX if you can). And as you can see there, there are two methods for working with fragments: getChildFragmentManager and getParentFragmentManager. I suppose you want to use child fragment manager to show some dialog, so in your case it will be
private void Adapter_RateItemClick(Object sender, DriversAdapterClickEventArgs e)
    {
            RatingFragment editAluminiFragment = new RatingFragment();
            editAluminiFragment.Show(getChildFragmentManager(), "Rate");
    }


text:
Q: Vue Router Guards are not Blocking Guarded Routes When Typed in Address Bar I have a simple vue app that I am trying to protect some routes, Ie.: if user is logged in show the dashboard page and block the member-login page. If the user is NOT logged in show the member-login page but block the dashboard page.
It is working on the navigation... so if I am not logged in and click "dashboard" I get redirected to the member-login page. And if I am logged in and click "login" I get redirected to the dashboard page. Cool.
Except if I type the path in the address bar, meaning, if I am logged in and click "login" I get redirected to the dashboard, but if I type /member-login in the address bar it still takes me to the member-login page, and it shouldn't. Same in reverse with the dashboard page if I am not logged in.
I am using the beforeEach() method to perform the guards, and here is what I have:
router.beforeEach((to, from, next) => {
   let ls = JSON.parse(localStorage.getItem('loggedInMember'));
   if(ls === null && to.name === 'dashboard'){
      next('/member-login');
   } else if ( ls !== null && to.name === 'login') {
      next('/dashboard');
   } else {
      next();
   }
});

I should mention that this is a global guard, and it lives in the main.js file of my project.
What am I missing?
Thanks so much!

A: So, the issue was a stupid mistake on my part...
I had the router.beforeEach method below the new Vue({}) method and it didn't like that. So moving the beforeEach method above the new Vue method fixed this issue.
Buggy:
new Vue({
   el: '#app',
   router,
   store,
   components: { App },
   template: '<App/>'
});

router.beforeEach((to, from, next) => {
   let ls = JSON.parse(localStorage.getItem('loggedInMember'));

   if(ls === null && to.name === 'dashboard'){
      next('/member-login');
   } else if ( ls !== null && to.name === 'login') {
      next('/dashboard');
   } else {
      next();
   }
});

Fixed:
router.beforeEach((to, from, next) => {
   let ls = JSON.parse(localStorage.getItem('loggedInMember'));

   if(ls === null && to.name === 'dashboard'){
      next('/member-login');
   } else if ( ls !== null && to.name === 'login') {
      next('/dashboard');
   } else {
      next();
   }
});

/* eslint-disable no-new */
new Vue({
   el: '#app',
   router,
   store,
   components: { App },
   template: '<App/>'
});

A: You mean you input the /member-login and it takes you to the login page ? It seems to me that it's the right action , or there's some misunderstanding I get?
Can you provide more details ?


text:
Q: Django 1.6.1 : Transaction error. You can't execute queries until the end of the atomic block in unitest Django 1.6.1 on Windows with Postgres
I m using unittest to test a view that upload a .cfg file to server. I am facing 2 error called
(1) TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the atomic block.
(2) OSError: [Errno 22] Invalid argument
I am writing down my view and test below.
Views.py
def upload(request, device_id):

    owner=account.objects.get(user=request.user)
    dev = get_object_or_404(device, pk=device_id, owner=owner)

    state = 0

    # Handle file upload
    if request.method == 'POST':

        form = UploadConfigForm(request.POST, request.FILES)
        if form.is_valid():
            new_file = form.save(commit=False)

            #now ask the device to download the config file
            sess, action, action_opt = add_device_action(device=dev, action=Action.AC_CONFIG_FILE_SET)

            #get the action related to this file
            if action_opt:
                new_file.act = action_opt
            else:
                new_file.act = action

            new_file.save()
            form.save_m2m()

            #add the payload to the action
            if action_opt:
                action_opt.payload = new_file.payload()
                action_opt.save ()
            else:
                action.payload = new_file.payload()
                action.save ()

            if settings.RENDER_JSON_INSTEAD_OF_HTML:
                # Render as an json response
                resp = action.descriptor()
                return HttpResponse(json.dumps(resp), content_type="application/json")

            else:
                # Redirect to the document list after POST
                # return HttpResponseRedirect('..')
                state = 1

    else:
        form = UploadConfigForm() # A empty, unbound form

tests.py
class DevAPISimulDevTests(TestCase):
    """
    Class that test the device API
    """
    fixtures = ['test_auth.json', 'test_users.json', 'test_device.json']

    def setUp(self):
        """

        """
        ret = self.client.login(username='cws', password='cws123')
        self.assertEqual(ret, True)

    def test_api_sim_usr_upload_config_file(self):
        """
        simulate the upload of the config file ba the user. submit with a file that is ok
        """

        logger.debug('test_upload_config_file')

        dev_id = 1
        dev = device.objects.get(pk=dev_id)

        url = reverse('device-upload', kwargs={'device_id':dev_id})
        myfile = open('device/fixtures/cfg_ok.csr','r')

            # with transaction.atomic():
        response = self.client.post(url, {'config_file':myfile})
        logger.debug('POST[%s]:[%s]', url, response.status_code)

        self.assertEqual(response.status_code, 200)
        ad = json.loads(response.content)

        # Check the ad we think we should receive.
        self.assertEqual(ad[Action.AD_EP_URL_BASE], settings.API_BASE_URL)
        self.assertEqual(ad[Action.AD_EP_ACTION], settings.API_EP_ACK)
        self.assertEqual(ad[Action.AD_EP_ERROR], settings.API_EP_ERR)
        self.assertEqual(ad[Action.AD_DEVICE_CODE], dev.access_code)
        self.assertEqual(ad[Action.AD_ACTION_CODE], Action.AC_ACKNOWLEDGE)
        self.assertIsNone(ad.get(Action.AD_ACTION_PAYLOAD))
        self.assertIsNone(ad.get(Action.AD_ACTION_WAIT))

        # Check the DB
        # We should have 1 session
        self.assertEqual(dev.session_set.count(), 1)
        sess = Session.objects.first()
        self.assertEqual(sess.state, Session.STATE_SMS_SENT)

        # We should have 2 actions more
        self.assertEqual(sess.action_set.count(), 2)

        # The first action should have the same token as in the SMS and the status should be in progress
        first_act = sess.action_set.first()
        self.assertEqual(first_act.next_token, ad[Action.AD_EP_TOKEN])
        self.assertEqual(first_act.status, Action.STATUS_IN_PROGRESS)

        # The second action should have the same token as in the SMS and the status should be queued
        next_act = sess.action_set.last()
        self.assertEqual(next_act.current_token, ad[Action.AD_EP_TOKEN])
        self.assertEqual(next_act.status, Action.STATUS_QUEUED)

        # test the status
        status_should_be = {u'0': {u'state': u'in progress', u'state_label': u'processing', u'label': u'contacting device'},
                            u'1': {u'state': u'queued', u'state_label': u'not started', u'label': u'uploading config file to device'}}

        self.test_sessionstatus(status_should_be)
        return ad

        # except IntegrityError:
        #     pass

    def test_api_sim_dev_init_session (self):
        """
        API : simulate the device receiving the first AD trhough SMS and initiating the session
        """
        # try:

        logger.debug('test_api_sim_dev_init_session')
            # with transaction.atomic():
        ad = self.test_api_sim_usr_upload_config_file()

        # validate that the url is correct
        url = reverse('device-api_ack', kwargs={'token':ad [Action.AD_EP_TOKEN]})

        url2 = ''.join (['/device/', ad [Action.AD_EP_TOKEN], '/', ad[Action.AD_EP_ACTION]])
        self.assertEqual(url, url2)

        # Simulate the device processing the first ad of the session
        # retrieve the next command from the server
        response = self.client.get(url)
        logger.debug('GET[%s]:[%s]', url, response.status_code)

        # check the answer
        self.assertEqual(response.status_code, 200)
        ad2 = json.loads(response.content)
        self.assertTrue(type(ad2) is dict)

        # Check the ad we think we should receive.
        self.assertEqual(ad2[Action.AD_ACTION_CODE], Action.AC_CONFIG_FILE_SET)
        self.assertEqual(ad2[Action.AD_EP_ACTION], settings.API_EP_CFG)
        self.assertTrue(type(ad2[Action.AD_ACTION_PAYLOAD]) is dict)
            #TODO: will need on time to understand why this asssrt fail.
        # self.assertContains(ad2[Action.AD_ACTION_PAYLOAD]['url'], '.csr')
        self.assertIsNone(ad2.get(Action.AD_DEVICE_CODE))
        self.assertIsNone(ad2.get(Action.AD_EP_URL_BASE))
        self.assertIsNone(ad2.get(Action.AD_EP_ERROR))

        # Check the DB
        # We should have 1 session in STATE_WAIT_DEV_REQ
        dev_id = 1
        dev = device.objects.get(pk=dev_id)

        self.assertEqual(dev.session_set.count(), 1)
        sess = Session.objects.first()
        self.assertEqual(sess.state, Session.STATE_WAIT_DEV_REQ)

        # We should still have 2 actions
        self.assertEqual(sess.action_set.count(), 2)

        # The first action should have a status done
        first_act = sess.action_set.first()
        self.assertEqual(first_act.status, Action.STATUS_DONE)
        self.assertEqual(first_act.next_token, ad[Action.AD_EP_TOKEN])

        # The second action should have the same token as in the SMS and the status should be queued
        next_act = sess.action_set.last()
        self.assertEqual(next_act.current_token, ad[Action.AD_EP_TOKEN])
        self.assertEqual(next_act.next_token, ad2[Action.AD_EP_TOKEN])
        self.assertEqual(next_act.status, Action.STATUS_IN_PROGRESS)

        # test the status
        status_should_be = {u'0': {u'state': u'done', u'state_label': u'done', u'label': u'contacting device'},
                                    u'1': {u'state': u'in progress', u'state_label': u'processing', u'label': u'uploading config file to device'}}
        self.test_sessionstatus(status_should_be)

        return ad2

Please suggest what I am doing wrong here, If code being pasted here does not concern errors, please suggest what code causes this error , as I cant figure out the origin of this errors..

A: might want to add:
'ATOMIC_REQUESTS': True,

under
DATABASES = {
 'default': {
     'ENGINE':whatever,
     'ATOMIC_REQUESTS': True,
  }
}


text:
Q: How to adapt flatbuffers `table` to be used with `Cow` in `Rust`? I have some hierarchy of traits and i need to adapt both structs and flatbuffers table to be used via the trait as follows:
// trait
pub trait TFilter : Clone {
    fn get_text(&self) -> &str;
}

// structure

#[derive(Clone)]
pub struct FilterStruct {
    pub text: String
}

impl TFilter for FilterStruct {
    fn get_text(&self) -> &str {
        &self.text
    }
}

impl TFilter for FilterTable<'_> {
    fn get_text(&self) -> &str {
        self.text()
    }
}

flatbuffers schema (IDL):
table FilterTable {
    text: string (required);
}

It works fine with the following usage:
pub fn accept_filter(filter: &dyn TFilter) {
    println!("{}", filter.get_text());
}

    accept_filter(&FilterStruct {
        text: "hello".to_owned()
    });

The problem happens when i inheritance is introduced:
a new trait that extends the base trait:
pub trait TActiveFilter {
    fn get_filter(&self) -> Cow<dyn TFilter>;
    fn get_title(&self) -> &str;
}

a new structure that extends the base struct ("extend by containing"):
#[derive(Clone)]
pub struct ActiveFilterStruct {
    pub filter: FilterStruct,
    pub title: String
}

impl TActiveFilter for ActiveFilterStruct {
    fn get_filter(&self) -> Cow<dyn TFilter> {
        Cow::Borrowed(&self.filter)
    }
    fn get_title(&self) -> &str {
        &self.title
    }
}

and a new flatbuffers table that extends the base table:
table ActiveFilterTable {
    filter: FilterTable (required);
    title: string (required);
}

impl TActiveFilter for ActiveFilterTable<'_> {
    fn get_filter(&self) -> Cow<dyn TFilter> {
        Cow::Owned(self.filter())
    }

    fn get_title(&self) -> &str {
        self.title()
    }
}

The actual problem is that flatbuffer's generated Rust file returns instances (not references) and one has to own it, so using the Cow (struct already own and returns the reference but flatbuffer's impl has to own the result).
However with Cow i get the following:
error[E0038]: the trait `TFilter` cannot be made into an object
  --> src/wrapper.rs:76:30
   |
76 | pub fn accept_filter(filter: Cow<dyn TFilter>) {
   |                              ^^^^^^^^^^^^^^^^ `TFilter` cannot be made into an object
   |
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
  --> src/wrapper.rs:5:21
   |
5  | pub trait TFilter : Clone {
   |           -------   ^^^^^ ...because it requires `Self: Sized`
   |           |
   |           this trait cannot be made into an object...

What exactly must be made?

A: Trait objects can not be cloned since their size is unknown. If you take a look at Clone and fn clone(&self) -> Self you will see that it returns Self, in this case dyn TFilter. Cow<T> requires the Clone bound on T, otherwise it wouldn't be possible to get an owned instance of T.
It's the same error that you will get when trying to pass a raw trait object to a function, e.g.:
trait Foo {}
fn foo(_ :dyn Foo) {

}

You might be able to work around this by returning Box<dyn TFilter> from your get_filter method, rather than the Cow. Following another approach, you could try to stick to static dispatch rather than trait objects in the Cow.


text:
Q: How to read image from URL (urllib.error.HTTPError: HTTP Error 403: Forbidden) I have a code that returns an image (API) :
url1 = "https://api.twilio.com/2010-04-01/Accounts/AC9567862a70d7b000488e8ba80bc19787/Messages/MMebd9e089637c2c740608199af762fc19/Media/ME49a13b9e0732d78b84fe81d6c3c5a3f2"
Manually open the image on broswer automatically converts the https address to below:
url2 = "https://s3-external-1.amazonaws.com/media.twiliocdn.com/AC9567862a70d7b000488e8ba80bc19787/f28ad1174d0871048be68207a88d5cea"
from skimage import io
img = io.imread(url1) # < ---- error here
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
text = pytesseract.image_to_string(img)

I'm trying to read the image from the url1 and perform OCR on the image.
(That is to read the image directly from (url1) without the need to open it on broswer and use the alternate address)
However, io.imread(url1) gives the error "urllib.error.HTTPError: HTTP Error 403: Forbidden".
io.imread(url2) does not return any error.
Is there any way to read the image directly from url1 ?

A: You can use this code in the second line as skimage.io.imread() takes URL as a string input.
img = io.imread(String(URL))

Also you can use cv2 module instead.
# importing OpenCV(cv2) module
import cv2

img = cv2.imread(URL)

# Output img with window name as 'image'
cv2.imshow('image', img)


text:
Q: Bulk loading JSON object as document into elasticsearch Is there a way to bulk load the data below into elasticsearch without modifying the original content? I POST each object to be a single document. At the moment I'm using Python to parse through individual objects and POST them one at a time.
{
   {"name": "A"},
   {"name": "B"},
   {"name": "C"},
   {"name": "D"},
}

Doing this type of processing in production from REST servers into elasticsearch is taking a lot of time.
Is there a single POST/curl command that can upload the file above at once and elasticsearch parses it and makes each object into its own document?
We're using elasticsearch 1.3.2

A: Yes, you can do bulk api via curl by using the _bulk endpoint. But not custom parsing. Whatever process that creates the file can format it to ES specification if that is an option. See here:
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html
There is also bulk support in python via helper. See here:
http://elasticsearch-py.readthedocs.org/en/master/helpers.html


text:
Q: Need sum of column while selecting other value I have a table like this:
   empID      name       amt      Date
   ------------------------------------
     1        mark        20     22-10
     1        mark        30     22-10
     2        kane        50     22-12
     2        kane        60     22-12
     3        mike        60     22-10

and I want to get an output like that
 empID   name      amt      Date    TOTAL
 -----------------------------------------
     1     mark    20      22-10    220
     1     mark    30      22-10    220
     2     kane    50      22-12    220
     2     kane    60      22-12    220
     3     mike     60     22-10    220

I have used sum(amt) but it is returning only 1 row; I want other rows as well.

A: You can use the window function sum() over() without any partition or order by
Example
Select *
      ,[Total] = sum(amt) over()
 From  YourTable

A: You need a windowing function
SELECT
     empid
    ,name
    ,amt
    ,[date]
    ,SUM(amt) OVER(PARTITION BY '') AS Total -- as you show it
    ,SUM(amt) OVER(PARTITION BY empID) AS Total -- as I think you want it
FROM t

Documentation: https://learn.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql?view=sql-server-ver15

A: Since you need to display the grand total value for each row you don't need to partition or group by. Therefore, you can use SUM(amt) OVER () .
 SELECT  *,
 SUM(amt) OVER () AS [Total]
 FROM tabe_c


text:
Q: Верстка flexbox. Возможно ли изменять ширину блоков и перемещать их внутри контейнера? Здравствуйте, такой вопрос. Сейчас в контейнере три элемента друг за другом, равной ширины. Возможно ли только третий div увеличить в ширину и расположить под вторым div-ом?

.pricing {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
  -webkit-justify-content: flex-start;
  justify-content: flex-start;
  width: 100%;
  margin: 0 auto 3em;
}
.pricing__item,
.pricing__feature-list {
  position: relative;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: column;
  flex-direction: column;
  -webkit-align-items: flex-start;
  align-items: flex-start;
  text-align: center;
}

заголовок

текст

список

список

список

заголовок

текст

список

список

список

заголовок

текст

список

список

список

A: Для увеличение ширины блока относительно других можно использовать свойство flex-grow,к элементу,а если нужно изменить порядок его следования,то можно использовать order,order: -1; делает его первым,order: 1; последним.

A: Вот подробный код + ссылка на jsfiddle

.my-flex-container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 70px;
  width: 100%;
  background: gray;
}
.gallery0 {
  display: flex;
  background: #33D1FF;
  width: 20%;
  margin: 1%;
  height: 70%;
  border-radius: 10px;
}
.gallery1 {
  display: flex;
  background: #33D1FF;
  width: 20%;
  margin: 1%;
  height: 70%;
  border-radius: 10px;
}
.gallery2 {
  display: flex;
  background: #33D1FF;
  width: 50%;
  margin: 1%;
  height: 70%;
  border-radius: 10px;
}
.galtext {
  font-size: 25px;
  font-style: normal;
  font-family: 'Lato', sans-serif;
  color: white;
  margin: auto;
}

    Div

    Div2

    Div3


text:
Q: Creating simple c++.net wrapper. Step-by-step I've a c++ project. I admit that I'm a complete ZERO in c++. But still I need to write a c++.net wrapper so I could work with an unmanaged c++ library using it. So what I have:
1) unmanaged project's header files.
2) unmanaged project's libraries (.dll's and .lib's)
3) an empty C++.NET project which I plan to use as a wrapper for my c# application
How can I start? I don't even know how to set a reference to an unmanaged library.
S.O.S.

A: You need to use p/invoke from .NET to talk to your unmanaged DLL.
Essentially you create a function header for each function you want to call in your unmanaged DLL, and tell .NET which DLL the function lives in, then just call that function like any other in your .NET wrapper.
You shouldn't even need any C++ knowledge - as long as you know the function definition of the functions in your unmanaged DLL, and the correct datatypes.

A: http://www.codeproject.com/KB/mcpp/quickcppcli.aspx#A8
This is general direction. You need to create C++/CLI Class Library project, add .NET class to it (StudentWrapper in this sample), create unmanaged class instance as managed class member, and wrap every unmanaged class function. Unmanaged library is added to C++/CLI project using linker dependencies list, and not as reference. In the Project - Properties - Linker open Additional Dependencies and add .lib name there.
Note: since we are talking about C++/CLI wrapper, no PInvoke! PInvoke is used to call exported functions (API), and not classes.


text:
Q: Spree - how to add a custom field in admin panel, and show the value in stores product page? I want to add a custom field in Spree admin panel and display that value in my products show page.
For example I want to add discount price field in products admin page along with the price field for each product and display that price value in products page along with the striked out original price.
Can someone please give me the necessary steps to achieve this? Thanks in advance.
Environment,
Rails : 3.2.13
Spree : 2.0.3

also using spree_fancy theme

A: You will need to create an extension for spree. Follow this guide. In the last step you'll see how you can put that field on view.


text:
Q: Application hangs only when breakpoint is triggered, .NET, C#, Visual Studio I refactored my application a while ago and since then I've been having problems with debugging using Visual Studio 2010.
My application works as expected while not debugging (not stepping through the application. An attached debugger does not cause any issues). However, when a breakpoint is triggered and I start to step through the app, Visual Studio and the app both hang after at most 3-4 steps.
To emphasize this point even more: It works well with my customers and regardless of whether I start it from Visual Studio or stand-alone - as long as no break point is triggered.
It does not matter where in the code I place the break point.
IDE: Visual Studio 2010 x64
Platform: .NET 4.0
The refactoring included a lot of cross-thread calls to BeginInvoke - all channeled through the following method:
public static void BeginInvokeIfRequired(this Control control, Action action)
{
    if (control.InvokeRequired)
    {
        control.BeginInvoke(action);
    }
    else
    {
        action.Invoke();
    }
}

There is not a single call to Control.Invoke() in the project.

*

*Is there something wrong with the above method?

Additionally, I'd appreciate any hints on how you would track down this bug. My current approach is to add output to the console and selectively deactivating parts of the code.

A: I would suspect that in some cases the code you show poses a problem since InvokeRequired lies in case IsHandleCreated is false - it returns false even if you are not on the GUI thread.
For reference see http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx .
The following code throws an exception instead of hanging... the fact that it "works as expected" when no breakpoint is hit might be a result of the debugger freezing all threads on hitting a breakpoint which in turn might lead to a different order of execution etc.
Altogether this means: you might have some "race condition" in your code where BeginInvokeIfRequired is called on a freshly created control before that control has a Handle. This can even be some 3rd-party code you use...
public static void BeginInvokeIfRequired(this Control control, Action action)
{
    if (control.IsHandleCreated)
    {
        if (control.InvokeRequired)
        {
            control.BeginInvoke(action);
        }
        else
        {
            action.Invoke();
        }
    }
    else {
         // in this case InvokeRequired might lie !
         throw new Exception ( "InvokeRequired is possibly wrong in this case" );
         }
}


text:
Q: Is there a jQuery lightbox plugin that has thumbnails inside the box? I'm trying to find a lightbox style plugin in jQuery that displays thumbnails at the bottom of the picture (or video, or whatever).
I found plenty of lightbox plugins, but none that allows navigation by thumbnail inside the box. The plugin must be able to open images, swf and inline content. I realize that jQuery will not be able to generate the thumbnails and that's ok.
Do you have any good ones to suggest?
Thanks

A: Check Galleria. Perfect for your needs. Source code here.

A: The only ones I could find were http://www.openstudio.fr/jquery/index.htm and http://koti.mbnet.fi/mallery/

A: maybe http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/


text:
Q: Getting 'SparseDtype' object has no attribute 'itemsize' when trying to save sparse df to hdf5? I'm trying to save a large sparse dataframe to a hdf5 file but I'm getting a attribution error:
one_hot = pd.get_dummies(my_DF, columns=['cat'], sparse=True)
one_hot.to_hdf('/content/data.h5', 'table', mode='w', append=True, complevel=9, complib='bzip2')

I get error:
AttributeError: 'SparseDtype' object has no attribute 'itemsize'

I have tried different combo's for to_hdf but no success. I have never converted to hdf5 before so I might be missing something. I couldn't find anything about this error on google so I'm wonder what is causing this error? and what can I do to fix it?

A: https://github.com/pandas-dev/pandas/issues/31199 to_hdf does not support sparse data types as yet.
The good news is it's known but the bad news is it is not assigned to anyone and no fixes have been put in.


text:
Q: WCF service doesn't like single quotes I am trying to post some data to a WCF service I don't own. I am using XmlSerializer to format the message, which creates issues with data containing single quotes.
Having a node like this
...
<FirstName>D'Arcy</FirstName>
...

Causes service to throw "400 bad request" exception. If I manually construct request in Fiddler like this
...
<FirstName>D"Arcy</FirstName>
...

then it works just fine.
I am confused as to why would this be needed. Various online XML validators claim my original XML is valid, but WCF doesn't like it? Any way to fix/workaround?

Here is my code just in case:
static XmlSerializer RequestSerializer = new XmlSerializer(typeof(Message));
static XmlSerializer ResponseSerializer = new XmlSerializer(typeof(int), new XmlRootAttribute("int") { Namespace = "http://schemas.microsoft.com/2003/10/Serialization/" });
static XmlWriterSettings WriterSettings = new XmlWriterSettings { OmitXmlDeclaration = true, CloseOutput = false, Encoding = new UTF8Encoding(false) };

private static int PostData(Message msg)
{
    var request = (HttpWebRequest)WebRequest.Create("https://...");
    request.ContentType = "text/xml;charset=UTF-8";
    request.Method = "POST";

    using (var writer = XmlWriter.Create(request.GetRequestStream(), WriterSettings))
        RequestSerializer.Serialize(writer, msg);

    using (var response = (HttpWebResponse)request.GetResponse())
    using (var responseStream = response.GetResponseStream())
    {
        return (int)ResponseSerializer.Deserialize(responseStream);
    }
}

[XmlRoot("Order", Namespace = "http://...")]
public class Message
{
    public string City;
    public string Coupon;
    public DateTime CreateDate;
    public string Email;
    public string FirstName;
    public string Language;
    public string LastName;
    public int OrderID;
    public string PostalCode;
    public string ProductID;
    public string Province;
    public string StreetAddress1;
    public string StreetAddress2;
}

A: Turns out this WCF service is inserting data into their DB by using straight up query (non-parametrized) and doesn't escape single quotes. It was really confusing too, since HTTP status 400 to me implies it was an issue with deserialization or something similar in the framework.
Sorry to bother everyone :(


text:
Q: Is it wise to ask about design decisions made on a product during an interview? I've been thinking about interview questions lately and I've been reflecting on bad interview experiences I've had in the past. One of particular note is where I had asked the interviewer why the team chose to use EJB 3 over Spring in their product. The interviewer pretty much tore my face off, yelling "Because Spring is not the be all and end all of Java software development, do you want this job or not?".  In response to this, I told him that this probably wasn't the job for me and I promptly walked out of the interview.
I was informed at the beginning of the interview that the company had high staff turnover, the product they were working was initially created in Modula-3 then ported to Perl and finally to Java. I was handed a 10 page booklet of technical questions covering Java, EJB, SQL and JDBC and I was asked questions about the technology stacks I've worked with. When prompted to ask questions, I felt it was reasonable to ask them about their technology stack and and get reasonable answers back, not to send the interviewer into flames.
Question:
Is it a good idea to probe on architectural choices taken in an interview? If not, why?
From my own point of view, an interview is a two-way process. If the interviewers are testing me on my technical skills, I've got every right to ask them the same questions to:
1) Figure out what their mindset and attitudes towards developing software are.
2) Determine if their approach is in line with how I would approach problems of that kind.
It's possible that the interviewer who got angry had poor interviewing skills and forgot that an interview is a two-way exchange. If I was asked this, I would have given a reasonable answer, but I certainly wouldn't have tried to put an interviewee in a state of meek capitulation where the head just bobs up and down with no conversation.

A: Personally, I find interviewing people almost as exhausting and stressful as being interviewed. But that's because I agree with you that the interview process is a two-way exchange.
I don't care how good you are, I don't want to hire you if you're not going to be happy working there. That's an expensive game to play. So I want to answer any concerns you might have and show you the team and product as they are, so that you can make an informed decision.
When I'm looking for a job, I want to work with someone who shares that attitude. And, even if I suspect I know the answers to questions, I will ask them just to see the reaction. Aggression is never a sign of someone comfortable with a situation.
I don't lie in an interview, on either side of the desk, because then they think they're hiring someone different / going to work somewhere different. And I expect the same in return, from the person on the other side of the interview.
Unfortunately, that means that occasionally I run into interviews like the one you described. Are they horrible experiences? Yes. Do I come out of there knowing exactly where the interview went wrong? Yes.
But am I very sure that every horrible experience would have been considerably worse if I'd got the job or hired the wrong person? Hell yes.

A: I'm of the mindset it's essential.  I've worked at far too many jobs with nonsensical design decisions either because nobody knew any better, didn't care to learn, or there was a mandate from management to use whatever the CEO read about in a magazine/saw online/had someone tell him was the "next big thing" without any consideration of alternatives.  These jobs were all miserable places to work.
You shouldn't necessarily criticize a design decision unless it's something that spits in the face of common sense or just sounds like crazy talk, but it's common to question things that seem "off" to find out if there's a legacy reason or something that came up that facilitated the need for using an unorthodox approach.
Asking questions like this also has the effect of gauging the company's interest in improvement and competency.  As someone else above said, it's one thing if you get an answer like (I don't know Java but use .NET so will use .NET examples) When we wrote the app there were no mature ORMs, so we used stored procedures with a data gateway layer.  We'd like to move to Entity Framework in the future and another thing entirely to get an answer like We just use stored procedures.  Entity Framework looks scary and might require work to refactor, and we can't refactor anything because the CEO has a laundry list of new features he wants us to work on, and if we spend the time looking at Entity Framework he'll fire us for wasting time.  One indicates understanding and a desire to improve, the other indicates a mediocre at best environment where everyone does the bare minimum to scrape by.
A company that takes offense at you questioning their decisions or wanting to discuss why they chose to use Product A instead of Product B is playing their hand and showing that they don't want a free thinker but a drone who won't question, and chances are it's not the kind of company any competent developer wants to work for.

A: answer: It is a good idea to ask about architectural decision making. But you need to be careful how you ask such questions.
Simply put: You should ask "How did you go about choosing technology X over technology Y?".
You want to phrase it in a way to communicate that you are generally interested in the process of decision making within the team. Nobody will want to go over every legacy decision the company has ever made with a candidate.
When you ask "Why did you choose technology X over technology Y?", it may come off that you disagree with their decision (which is ok...but can be taken as hostile) or that you want to boast about how much you know about the technologies in question (which would be annoying for anyone), despite your good intentions.

A: Yes, it's ok to ask if you're genuinely curious and if the answer matters. I think asking shows you understand there's more than one way to do things, and it shows you are interested in how the software was written.
That being said, you've got to be very careful in how you phrase the question, and doubly careful about how you continue the conversation. It is easy to come across as challenging their decisions. The last thing you want is for the interviewer to believe you think you're smarter than them. If you're genuinely curious, ask. If you think they made a poor choice, keep your mouth shut.
If I had been in the situation described in the question, instead of walking out I might have said something like "oh yeah, I agree that spring is definitely not the right solution for everything. Thanks for letting me know a bit about your architecture! I'm always looking for insight into how to choose the right tools". (though, your question is odd -- you ask why they chose spring, and they chose it because it was not the be all end all?)

A: As someone who frequently interviews people, I'd personally welcome a discussion about why particular technology or design choices were made, what we'd do differently now if we either had the luxury of resources or were starting a new project. I'd generally see it as a sign about someone who cares about their craft, and unless their dogmas and ours weren't compatible, I'd probably rate that candidate more highly than someone who just answers technical questions competently.
I'm currently working on a project for a client which has a legacy of some well-meaning but poorly implemented architectural decisions, and candidates who express curiosity about the world as it is, and the path forward as we see it, are usually the types of people we'd like to work with. We want people who are able to do appropriate due diligence and validation on design and implementation decisions on our team. We generally value people who bring something to the table that we don't have, or don't have enough of.
When I've been a candidate in an interview, I take any sign of hostility or defensiveness when these types of discussions happen as a bad sign, as an organization not capable of self-examination is usually also in a technological and process morass that they are incapable of and probably unwilling to work their way out of. If I don't see motivation for continuous improvement on the existing team, there's a good chance I won't be happy there.
If I went in and they said, "Yeah, we've got this legacy app that we're not happy maintaining but it still brings in enough revenue to cover all our paychecks, and we want to make the codebase more maintainable by refactoring the pain points, or migrate component x to technology y" or "we chose technology a over technology b because we had more experience there and technology b was still in its infancy when we started; we're open to change but it's a slow process and we aren't in a position to just throw out our existing codebase", I can believe it's going to be a better experience for me than if I hear "Yeah, we are stuck on Borland C++ Builder version 6 and developers aren't allowed to make technical decisions because they've all already been made by the CEO's brother, who slept with an Oracle salesperson once and decided all future development will be done using Java 1.4 web services, Oracle ERP, and a Borland C++ frontend using mostly discontinued 3rd party GUI components and we'd rather spend $60,000 a month plugging holes to keep customers from jumping ship than revisit any decisions and make permanent improvements that might bring new revenue if we're lucky. Don't rock the boat, what's wrong with you."
Presuming you're in an area with other technology jobs, or you're willing to move, you likely have the luxury of choice. No gig is perfect, but you want to work with people who want to work with you. (I care more about this than the specific technology choices most of the time.) If something smells bad, it probably is.
So yeah, ask away. The more curiosity about our business, our process, and our design, the more seriously I'm likely to take a candidate. But I don't work at a Blub shop, so I can't say whether it'll help you get a Blub job. I can only say that it would work for you if you want to work with other people who care about their craft.

A:
Question: Is it a good idea to probe on architectural choices taken in
  an interview? If not, why?

It absolutely fine, I would view it as a positive.
If your interviewer can not handle that, it says a lot about them - not you.
I would be worried if a junior was NOT interested in design decisions, it would show a lack of curiosity/interest in the subject area, and exhibits no desire to improve themselves.

A: I'm fond of asking an interviewer to tell me about a failed design decision they made, and what was done next.  This gives you some good pieces of information:

*

*If the boss can't admit any form mistake or temporary failure, that's a boss you probably don't want to work for.

*You can tell how the company handles a stressful situation.

It might not be popular, but I always have great respect for the managers with the stones to recognize a project is going to fail and kill it to stop wasting money, or that something is headed in the wrong direction and needs to be killed or rebooted.
Ultimately if you're talking about job satisfaction the technology (language/platform/compiler/whatever) doesn't matter so much as the personalities involved and the work environment.

A: A few years back I was in an interview and had been asked various technical questions about a programming language... which I hadn't done well on (60/40 correct/incorrect). The discussion moved onto the project they had in hand and I started asking questions about the design and then pointed out a couple of problems and limitations they would introduce.
I was offered the job the next day. Unfortunately I was unable to take it up for personal reasons.
Asking questions about design shouldn't be a problem if they are intelligent questions especially if you can then relate them to their business.

A: I've not done much interviewing, but, from your experience, I would conclude:
a) It's OK if you want to make an informed decision about whether you want the job;
b) It's not OK if you already decided you want the job.
People can easily get offended by benign quentions about their choices. That's an awfully bad trait, but a common one.

A: Here's some advice

*

*Asking why they chose some existing solution might be bad question, because probably the development team was not given chance to change or choose it.

*Also the team likely already knows why the technology was not the best choice

*But unfortunately, the last thing any development team needs is people trying change the architecture or questioning choices that were made 10 years ago -- it gives impression that their technology is already old legacy stuff and such messages going around in the team can make developers unhappy about the current situation

*Thus in an interview, the last thing you should do is give impression that you're going to complain all the time about the choices the team has no control over


text:
Q: How do I get compass heading from DeviceOrientation in the Google Glass Browser? The web browser built into Google Glass as of firmware version XE7 provides DeviceOreientation events, but the values don't seem to come from an expected frame of reference. How can one get proper compass headings out of this?  With Glass positioned normally on the head:
DeviceOrientationEvent
beta
     90  upright and level
    -90  inverted and level
      0  looking straight up or down

gamma
     90  right ear towards floor
    180  looking straight up
270/-90  left ear down
      0  looking straight down

alpha
This property is not stable when Glass is horizontal (what should be the most useful orientation for using compass direction, to determine where the wearer is looking). It gives stable readings only when Glass is tilted well above or below the horizon.
above horizontal
     90  North
      0  East
    180  West
    270  South

below horizontal
    270  North
    180  East
      0  West
     90  South

A: May be you can get some idea on how to control the Compass from this newly launched sample


text:
Q: What is the standard deviation of this random variable? (I want to check my calculation) Consider the random variable (orientation angle) $0\le\theta\le 2\pi$ with the following PDF where $\theta_0$ is the mean orientation angle: $(n\in\mathbb Z , n\ge 0)$
$$p(\theta,\theta_0,n)=\frac{\cos^{2n}(\theta-\theta_0)}{\int_0^{2\pi}\cos^{2n}(\theta-\theta_0) \, d\theta}$$
What is the variance of the random variable $\theta$ in terms of $n$
I have taken these steps:
First of all we should calculate $A_n=\int_0^{2\pi}\cos^{2n}(\theta-\theta_0)\,d\theta$
From the Integration by substitution method assuming that $x=\theta-\theta_0$ we have:
$$A_n=\int_{-\theta_0}^{-\theta_0+2\pi}\cos^{2n}x\,dx$$
From page $30$ in Elementary Functions we know:
$$\cos^{2n}x=\frac{1}{2^{2n}}\binom{2n}{n}+\frac{1}{2^{2n-1}}\sum_{k=0}^{n-1}\binom{2n}{k}\cos 2(n-k)x$$
Then
$$A_n=\int_{-\theta_0}^{-\theta_0+2\pi}\frac{1}{2^{2n}}\binom{2n}{n}\,dx+\frac{1}{2^{2n-1}}\sum_{k=0}^{n-1}\binom{2n}{k}\int_{-\theta_0}^{-\theta_0+2\pi}\cos 2(n-k)x\,dx$$
About the second integral in the above expression, we know that the period of the function $\cos 2(n-k)x$ is $\frac{\pi}{n-k}$
So the length of the interval $[-\theta_0,-\theta_0+2\pi]$ is $2(n-k)$ times the period which is an integer coefficient of the period, that means the answer of this integral will be $0$
So $$A_n=\frac{\pi}{2^{2n-1}}\binom{2n}{n}$$
The PDF mentioned at the begining will be converted to:
$$p(\theta,\theta_0,n)=\frac{\cos^{2n}(\theta-\theta_0)}{A_n}$$
So the variance will be:
$$\sigma^2(\theta)=\frac{1}{A_n}\int_0^{2\pi}(\theta-\theta_0)^2\cos^{2n}(\theta-\theta_0)\,d\theta$$
Again from the Integration by substitution method and the aforementioned relation we have:
$$\begin{align}
\int_0^{2\pi}(\theta-\theta_0)^2\cos^{2n}(\theta-\theta_0)\,d\theta
&=\int_{-\theta_0}^{-\theta_0+2\pi}x^2\cos^{2n}x\,dx\\
&=\int_{-\theta_0}^{-\theta_0+2\pi}x^2(\frac{1}{2^{2n}}\binom{2n}{n}+\frac{1}{2^{2n-1}}\sum_{k=0}^{n-1}\binom{2n}{k}\cos 2(n-k)x)\,dx\\
&=\frac{\binom{2n}{n}}{2^{2n}}\underbrace{\int_{-\theta_0}^{-\theta_0+2\pi}x^2\,dx}_1\\
&+\frac{1}{2^{2n-1}}\sum_{k=0}^{n-1}\binom{2n}{k}\underbrace{\int_{-\theta_0}^{-\theta_0+2\pi}x^2\cos 2(n-k)x\,dx}_2
\end{align}$$
About the first integral in the above equation, we have
$$(1):\int_{-\theta_0}^{-\theta_0+2\pi}x^2\,dx=\left[\frac{x^3}{3}\right]_{-\theta_0}^{-\theta_0+2\pi}=\frac{8\pi^3-12\pi^2\theta_0+6\pi\theta_0^2}{3}$$
And about the second integral:
$$(2):\int_{-\theta_0}^{-\theta_0+2\pi}x^2\cos 2(n-k)x\,dx$$
From integration by parts method:
$$
\begin{array}{c|c}
\text{Derivation}&\text{Integration}\\
\hline
{} \oplus x^2 & \cos 2(n-k)x  \\
{} \ominus 2x & \frac{1}{2(n-k)}\sin 2(n-k)x \\
{} \oplus 2 & \frac{-1}{2^2(n-k)^2}\cos 2(n-k)x \\
{} \ominus 0 & \frac{-1}{2^3(n-k)^3}\sin 2(n-k)x
\end{array}
$$
$$\begin{align}
(2):\int_{-\theta_0}^{-\theta_0+2\pi}x^2\cos 2(n-k)x\,dx &=\left[\frac{x^2}{2(n-k)}\sin 2(n-k)x\right]_{-\theta_0}^{-\theta_0+2\pi} \tag 1\\
&+\left[\frac{x}{2(n-k)^2}\cos 2(n-k)x\right]_{-\theta_0}^{-\theta_0+2\pi} \tag 2 \\
&-\left[\frac{1}{2^2(n-k)^3}\sin 2(n-k)x\right]_{-\theta_0}^{-\theta_0+2\pi} \tag 3
\end{align}$$
For $(1)$ regarding the facts $\sin (2n\pi+\theta)=\sin\theta$ and $\sin(-\theta)=-\sin\theta$ after some simplifications, we have $$(1)=\frac{2\pi(\theta_0-\pi)}{n-k}\sin 2(n-k)\theta_0$$
For $(2)$ regarding the facts $\cos (2n\pi+\theta)=\cos\theta$ and $\cos(-\theta)=\cos\theta$ after some simplifications, we have $$(2)=\frac{\pi}{(n-k)^2}\cos 2(n-k)\theta_0$$
Also after some simplifications, we conclude that $(3)=0$
So:$$\int_{-\theta_0}^{-\theta_0+2\pi}x^2\cos 2(n-k)x\,dx=\frac{2\pi(\theta_0-\pi)}{n-k}\sin 2(n-k)\theta_0+\frac{\pi}{(n-k)^2}\cos 2(n-k)\theta_0$$
Then
$$\begin{align}
&\int_0^{2\pi}(\theta-\theta_0)^2\cos^{2n}(\theta-\theta_0)\,d\theta=\frac{\binom{2n}{n}}{2^{2n}}\frac{8\pi^3-12 \pi^2 \theta_0 + 6\pi\theta_0^2}{3}+{}\\
&\frac{1}{2^{2n-1}}\sum_{k=0}^{n-1}\binom{2n}{k}\left(\frac{2\pi(\theta_0-\pi)}{n-k}\sin 2(n-k)\theta_0+\frac{\pi}{(n-k)^2}\cos 2(n-k)\theta_0\right)
\end{align}$$
And the variance will be:
$$\frac{2^{2n-1}}{\binom{2n}{n}\pi}\left(\begin{align}
&\frac{\binom{2n}{n}}{2^{2n}}\frac{8\pi^3-12\pi^2\theta_0+6\pi\theta_0^2}{3}+{}\\
&\frac{1}{2^{2n-1}}\sum_{k=0}^{n-1}\binom{2n}{k}\left(\frac{2\pi(\theta_0-\pi)}{n-k}\sin 2(n-k)\theta_0+\frac{\pi}{(n-k)^2}\cos 2(n-k)\theta_0\right)
\end{align}\right)$$
With the final form:
$$\sigma^2(\theta)=\frac{4\pi^2-6\pi\theta_0+3\theta_0^2}{3}+\sum_{k=0}^{n-1}\frac{n!n!}{k!(2n-k)!}\left(\frac{2(\theta_0-\pi)}{n-k}\sin 2(n-k)\theta_0+\frac{1}{(n-k)^2}\cos 2(n-k)\theta_0\right)$$
So it seems that the variance is dependent to $\theta_0$(mean orientation angle) and even if we assume $\theta_0=0$
$$\sigma(\theta)=\sqrt{\frac{4\pi^2}{3}+\sum_{k=0}^{n-1}\frac{n!n!}{k!(2n-k)!}.\frac{1}{(n-k)^2}}$$
But in the papers that I'm studying:
A General Characterization for Polarimetric Scattering From Vegetation Canopies
Adaptive Model-Based Decomposition of Polarimetric SAR Covariance Matrices
It has been pointed out that:

Also the limit of the expression that I get finally is not $0$ an $n\to +\infty$ which is not consistent with our hypothesis
I'm really confused

A: Too long for a comment: without getting into the details of your calculation, I think there is a more fundamental problem here. On one side, you are treating $\theta$ as a scalar variable that takes values in the real interval $[0,2\pi]$, and then you define a pdf over that interval and compute the mean, variance, etc by integrating over that interval. But that conflicts with your interpretation of $\theta$ as an angle. For example, suppose you had a pdf for $\theta$ that is concentrated (evenly) at $[0,\epsilon]$ and $[2\pi - \epsilon, 2\pi]$, for very small $\epsilon$. Seeing $\theta $ as an angle, we'd say that it's variance is very small (and it's mean is zero). Computing it as pdf, we wouldn't get that result.
Also, you assume that $\theta_0$ is the mean of your density, but that, again, is incompatible with you formulation. Think of $\theta_0 =0$...
Further, take for example $n=1$, $\theta_0=1$. The density function (graph) has period $2\pi$ (as it should), and its integral gives $1$ over the interval $[0,2\pi]$ as well as over (say) $[-\pi,3/2\, \pi ]$  (as it should).

But if we compute the mean and variance by the standard formulas we'd get, integrating over $[0,2\pi]$ : $\mu=2.687$ (already a meaningless result!) and $\sigma^2=2.8750$. If we take $[-\pi,3/2\, \pi ]$ (it should not matter), it gives instead $\mu=2.02545$ and $\sigma^2=2.79192$
All this needs rethinking. That's not the way to deal with circular statistics, I'm afraid. http://www.theanalysisfactor.com/circular-statistics/
https://en.wikipedia.org/wiki/Directional_statistics


text:
Q: CloudSQL JDBC Logstash implementation Question
I need to query CloudSQL from Logstash but can't find any example out there.
Additional Context
I ran the build command for postgres jdbc driver
mvn -P jar-with-dependencies clean package -DskipTests
And provided it as Logstash JDBC driver (tried with dependencies jar too):
input {
    jdbc {
        jdbc_driver_library => "/Users/gustavollermalylarrain/Documents/proyectos/labs/cloud-sql-jdbc-socket-factory/jdbc/postgres/target/postgres-socket-factory-1.6.4-SNAPSHOT.jar"
        jdbc_driver_class => "org.postgresql.Driver"
        jdbc_connection_string => "jdbc:postgresql:///people?cloudSqlInstance=cosmic-keep-148903:us-central1:llermaly&socketFactory=com.google.cloud.sql.postgres.SocketFactory&user=postgres&password=postgres"
        statement => "SELECT * FROM people;"
        jdbc_user => "postgres"
        jdbc_password => "postgres"
    }
}

output {
    stdout {
        codec => rubydebug {
        }
    }
}

I'm having this error:

Error: java.lang.ClassNotFoundException: org.postgresql.Driver. Are you sure you've included the correct jdbc driver in :jdbc_driver_library?

I'm missing something?

A: The steps to query Cloud SQL from Logstash are:

*

*Build the jar driver:

From this repo: https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory. Clone and run mvn -P jar-with-dependencies clean package -DskipTests

*Copy files

Copy the jar files from jdbc/postgres/target/ to logstash-core/lib/jars also download the postgres jdbc driver and copy the jar file to logstash-core/lib/jars as well

*Configure Logstash

The configuration file will not include the jar's path because will look into the default folder logstash-core/lib/jars where you copied the jar files.
input {
    jdbc {
        jdbc_driver_class => "org.postgresql.Driver"
        jdbc_connection_string => "jdbc:postgresql:///people?cloudSqlInstance=cosmic-keep-148903:us-central1:llermaly&socketFactory=com.google.cloud.sql.postgres.SocketFactory&user=postgres&password=postgres"
        statement => "SELECT * FROM people;"
        jdbc_user => "postgres"
        jdbc_password => "postgres"
    }
}

output {
    stdout {
        codec => rubydebug {
        }
    }
}

jdbc user and password are ignored and the ones you provide in the connection string are used instead. For Postgre Cloud SQL connector you can use both Postgre users or IAM accounts.
Note: You need to run this from a Compute Engine to automatically apply the gcp credentials or manually create the env variables


text:
Q: Rails - ajax response handling I am sending data by using ajax call to 3rd party api to see if the card supports installment, then I get a response in the payment#new action, I just do not know how to show response on the view.
ajax call;
                $.ajax({
                 type: "GET",
                 url: "/payments/new",
                 dataType: "json",
                 data: {card_digit},
                 success: function(data) {},
                 error: function(jqXHR) {}
                });

payments#new action
def new
...
...
uri = URI.parse("https://...")
      https = Net::HTTP.new(uri.host,uri.port)
      https.use_ssl = true
      req = Net::HTTP::Post.new(uri.path, @headers)

      req.body = @body.to_json
      res = https.request(req)

      puts "Response #{res.code} #{res.message}: #{res.body}"

end

Then here it returns res.body as json object, I would like to show this on the view I have tried to assign to a variable like @return then use it on the view but no chance, I tried with respond to block but could not manage to do it either.
EDIT
Thank you for the answer!,
But now I get error Encoding::UndefinedConversionError ("\xC4" from ASCII-8BIT to UTF-8)
res.body returns;
{"bankId":"13","bankName":"...","cardFamilyId":"..","cardFamilyName":"...","cardThreeDSecureMandatory":"0","merchantThreeDSecureMandatory":"0","result":"1","serviceProvider":"2","supportsInstallment":"1","type":"1"}

I wrote;
render json: { res_body: res.body }

and
console.log(data) in the success function
why would it happen?
EDIT
I added
render json: { res_body: JSON.parse(res.body) }

A: If you use Ajax then you have to handle it in your JavaScript code to change your view.
Use this in your controller to pass the data to your Ajax call (replace the dummy hash):
render json: { test: "hello" }

In your success function of the ajax the JSON object I just rendered will be accessible in the data parameter of the function. Now I have to manipulate the view using javascript
EDIT:
To answer your edit I guess you have some characters which are more complicated to handle in your JSON like chinese, turkish, .... Maybe this might help you Encoding::UndefinedConversionError


text:
Q: react-boilerplate npm install error I follow work flow from flux official tutorial
and try to build simple template project from react-boilerplate
but when I use npm install, many error occured ..
I select some piece of output below
> node-gyp rebuild

  CXX(target) Release/obj.target/fse/fsevents.o
In file included from ../fsevents.cc:6:
../node_modules/nan/nan.h:339:13: error: no member named 'New' in 'v8::String'
    return  _NAN_ERROR(v8::Exception::Error, errmsg);
            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:319:50: note: expanded from macro '_NAN_ERROR'
# define _NAN_ERROR(fun, errmsg) fun(v8::String::New(errmsg))
                                     ~~~~~~~~~~~~^
../node_modules/nan/nan.h:343:5: error: no member named 'ThrowException' in namespace 'v8'
    _NAN_THROW_ERROR(v8::Exception::Error, errmsg);
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../node_modules/nan/nan.h:324:11: note: expanded from macro '_NAN_THROW_ERROR'
      v8::ThrowException(_NAN_ERROR(fun, errmsg));                             \
      ~~~~^

...
    /Users/mengwenqiaoxindongcom/.node-gyp/4.2.1/include/node/v8.h:2933:3: note: 'New' declared here
  static Local<Object> New(Isolate* isolate);
  ^
fatal error: too many errors emitted, stopping now [-ferror-limit=]
20 errors generated.
make: *** [Release/obj.target/fse/fsevents.o] Error 1
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/mengwenqiaoxindongcom/.nvm/versions/node/v4.2.1/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:270:23)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Darwin 14.5.0
gyp ERR! command "/Users/mengwenqiaoxindongcom/.nvm/versions/node/v4.2.1/bin/node" "/Users/mengwenqiaoxindongcom/.nvm/versions/node/v4.2.1/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /Users/mengwenqiaoxindongcom/pra/javascript/react-full_stack/flux/react-boilerplate/node_modules/jsxc/node_modules/chokidar/node_modules/fsevents
gyp ERR! node -v v4.2.1
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
npm WARN optional dep failed, continuing fsevents@0.2.1
envify@0.2.0 node_modules/envify
├── through@2.3.8
└── falafel@0.2.1 (esprima@1.1.0-dev)

I find some solve that changing node version between v0.12.7 and v4.2.1 but error also exit.
nvm ls
        v0.12.7
->      v4.2.1
        system
node -> stable (-> v4.2.1) (default)
stable -> 4.2 (-> v4.2.1) (default)
iojs -> N/A (default)

finally, I follow this issue and notice that nobody could correctly solve these error.
could somebody help me? thanks ..

A: Stumbled upon your question when searching for a solution to the same problem. Just checked the issue you linked to and finally managed to find a solution. You might have seen it too already, but if not, someone suggested the following which worked for me:

*

*Remove node_modules folder

*npm install jest-cli --save-dev

*npm install
The problem was that jest-cli expected a lower version of Node. So updating jest-cli seemed to resolve the issue.