text:
Q: angular ng-repeat add style on condition i am using ng-repeat on a list of divs and i am manually adding items in the json that it's rendering this divs. I need to position the last div that i add in json and it's automatically rendiring on the screen, where the couse cursor is, and the rest of them remain on same position, but without giving the position in the json that is rendering it.
My approach on this was something like this

but when i do this, all the divs get this position, so i need to make a condition using $last variable to add or remove the style tag with those left and top css.
Thank you in advance, Daniel!

A: Based on you html, you should try this

{{item}}

Here is the fiddle for confirmation http://jsfiddle.net/cmyworld/yFc6J/1/

A: See this fiddle for examples of both approaches (using color as position is harder in jsfiddle)
Option 1: ng-style and a scope function
ng-style will let you do this, and to keep it tidy and testable you should define a scope function such as below (ternary operators are not currently supported in angular expressions for stable 1.0.x versions of angular, although 1.1.5 has added ternary support).
ng-style='myStyleFunction($last)'

In the controller, define:
$scope.myStyleFunction = function($last) {
  return {
    'left': $last ? $scope.lastX + 'px' : '',
    'top': $last ? $scope.lastY + 'px' : ''
  };
}

Option 2: custom directives
Or, you could think even more "angular" and define a directive:
dirModule.directive('positionLast', function() {
    return {
        scope: true,
        link: function (scope, $element, attrs) {
            if (scope.$last) {
              // if jQuery is present use this, else adjust as appropriate
              $element.css("left", $scope.lastX + 'px');
              $element.css("top", $scope.lastY + 'px');
            }
        }
    }
});

and then:

 ...

EDIT This works by using scope: true and declaring the directive on the ng-repeat element. As only one new scope is created for all directives on an element (assuming at least one requests a new scope) then it gets access to the ng-repeat scope values. For the relevant documentation see:

*

*Directives: Directive Definition Object (scope / true)

scope - If set to true a new scope will be created for this directive. If multiple directives on the same element request a new scope, only one new scope is created.


text:
Q: XMLHttpRequest cannot load file://... Origin null is not allowed by Access-Control-Allow-Origin I see that the above question was asked earlier, however even after referring them I wasn't able to figure out a way for me, hence I took the liberty to start a new post for this question.
I have a getjson.html file containing the following code

<button>Get JSON data</button>

The json_data.txt contains the following,
{
  "firstName": "John",
  "lastName": "Doe",
  "age": 25
}

When I open the getjson.html file in the browser, it gives an error:

"XMLHttpRequest cannot load file://.....  Origin null is not allowed by Access-Control-Allow-Origin."

Someone Please suggest a simple solution regarding this about how could I make this thing possible.
P.S: I am writing a web app on go.

A: Are you directly opening an HTML file? The file needs to be placed on a web server then executed. Normally browsers don't allow file:/// protocol for AJAX calls for security reasons.

A: I am reading your problem a bit late (spring 2013) and think I have found a solution to the limitation of CORS XHR cross domain in a file:// context !
I have put this header on my remote php script:
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);

and it seems to work ! More explanation here: Rannpháirtí anaithnid/CORS
It may work on a "phone gap" application instead of using jquery and jsonp?

redpajama_set_name: RedPajamaStackExchange


text:
Q: django-storages - ImproperlyConfigured: Could not load amazon's s3 bindings I feel so dumb now
I am trying to use django-storages
I installed
pip install django-storages

then, added 'storages', into settings.py
then in settings.py
DEFAULT_FILE_STORAGE = 'storages.backends.s3.S3Storage'
AWS_ACCESS_KEY_ID = 'xxx'
AWS_SECRET_ACCESS_KEY = 'yyy'
AWS_STORAGE_BUCKET_NAME = 'mybucketname'

and tried to see if default file storage is changed:
>>> from django.core.files.storage import default_storage
>>> print default_storage.connection
....
ImproperlyConfigured: Could not load amazon's s3 bindings.

what am I missing

A: According to the documentation:

There are two backend APIs for interacting with S3. The first is the
  s3 backend (in storages/backends/s3.py) which is simple and based on
  the Amazon S3 Python library.

and the source code:
try:
    from S3 import AWSAuthConnection, QueryStringAuthGenerator, CallingFormat
except ImportError:
    raise ImproperlyConfigured("Could not load amazon's S3 bindings.\nSee "
        "http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134")

The storages.backends.s3.S3Storage backend requires the Amazon S3 library to be installed.
I might confuse the original library and the fork, but I think the point stays valid.


text:
Q: Instance parameter not being passed in nested inlines form I am implementing nested inlines with my 3-tiered model and currently having it functional. However, I can't limit my relevantindicator drop-down choices even though I am passing the correct instance. Currently relevantindicator displays all values in the table in the drop-down selection. I'd like to limit the values to only those associated with the disease instance. Is there a way to do that?
I'm using Correct way to save nested formsets in Django and http://yergler.net/blog/2009/09/27/nested-formsets-with-django/ as references.
models.py
class Disease(models.Model):
    disease = models.CharField(max_length=255)

class Indicator(models.Model):
    relevantdisease = models.ForeignKey(Disease)
    indicator = models.CharField(max_length=255)

class IndicatorValue(models.Model):
    relevantindicator = models.ForeignKey(Indicator)
    indicator_value = models.CharField(max_length=50)

forms.py
class BaseIndicatorFormSet(BaseInlineFormSet):

     def __init__(self, *args, **kwargs):
        try:
            instance = kwargs.pop('instance')
        except KeyError:
            super(BaseIndicatorFormSet, self).__init__(*args, **kwargs)

     def save_new(self, form, commit=True):
        instance = super(BaseIndicatorFormSet, self).save_new(form, commit=commit)

        form.instance = instance

        for nested in form.nested:
            nested.instance = instance

        for cd in nested.cleaned_data:
            cd[nested.fk.name]=instance

        return instance
...

     def add_fields(self,form,index):
        super(BaseIndicatorFormSet, self).add_fields(form, index)

        try:
            instance = self.get_queryset()[index]
            pk_value = instance.pk

        except IndexError:
            instance=None
            pk_value = hash(form.prefix)

        form.nested = [
            IndicatorValueFormSet(
                disease = instance,
                queryset = IndicatorValue.objects.filter(relevantindicator = pk_value),
                prefix = 'value_%s' % pk_value)]

class BaseIndicatorValueFormSet(BaseModelFormSet):

    def __init__(self, disease, *args, **kwargs):
        super(BaseIndicatorValueFormSet, self).__init__(*args, **kwargs)
        self.disease = disease

    def save_new(self, form, commit=True):
        instance = form.save(commit=False)
        instance.disease = self.disease
        if commit:
           instance.save()
        return instance

    def save_existing(self, form, instance, commit=True):
        return self.save_new(form, commit)

class IndicatorValueForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        try:
            disease_obj = kwargs.pop('disease')
        except KeyError:
            super(IndicatorValueForm, self).__init__(*args, **kwargs)
            return

        super(IndicatorValueForm, self).__init__(*args, **kwargs)
        queryset = Indicator.objects.filter(relevantdisease =disease_obj)
        self.fields['relevantindicator'].queryset = queryset

disease_obj = get_object_or_404(Disease, pk=2) #hard-wired
CurriedForm = formset_factory(IndicatorValueForm, extra=3)
CurriedForm.form = staticmethod(curry(IndicatorValueForm, disease = disease_obj))
IndicatorValueFormSet = inlineformset_factory(Indicator, IndicatorValue,   formset=BaseIndicatorValueFormSet, form = CurriedForm, extra=3)
IndicatorFormSet = inlineformset_factory(Disease, Indicator, formset=BaseIndicatorFormSet, extra=0)

views.py
 disease = get_object_or_404(Disease, pk=disease_id)

 if request.method == "POST":
      formset = IndicatorFormSet(request.POST, instance=disease)

    if formset.is_valid():
       rooms = formset.save_all()
       return HttpResponseRedirect(reverse('option', kwargs={'disease_id':disease_id}))
 else:
       formset = IndicatorFormSet(instance=disease)

context = {'disease': disease, 'indicators': formset, 'hide_breadcrumb':hide_breadcrumb}
   return render_to_response('valdrui.html',context, context_instance=RequestContext(request))

template.html
  {% if relevantindicator.nested %}
  {% for formset in relevantindicator.nested %}
  {{ formset.as_table }}
  {% endfor %}
  {% endif %}

Update
My feeling is that I need to pass the disease instance from form.nested down to BaseIndicatorValueFormSet. But it does not seem to be working.
Screenshots to provide clarity.

relevantindicator provides a drop-down

When there is a indicator_value, the correct relevantindicator is selected. However, when adding a new indicator_value, all relevantindicator for all relevantdiseases are available. I'd like to limit the relevantindicator choices to the relevantdiseases (the disease instance)
Update 2: I had to define an instance in BaseIndicatorFormSet under def __init__. I also needed to define the forms in forms.py since BaseIndicatorFormSet calls IndicatorValueFormSet. The instance is currently hard-wired, just to see if the template will render. Unfortunately, the form in the template does not render but also does not produce any errors. I can't figure out why since there is no error produced.

A: here's a complete forms.py you can base your code on
from django import forms
from django.forms.formsets import DELETION_FIELD_NAME
from django.forms.models import BaseInlineFormSet, BaseModelFormSet, inlineformset_factory

from .models import Disease, Indicator, IndicatorValue

class BaseIndicatorFormSet(BaseInlineFormSet):

    def save_new(self, form, commit=True):
        instance = super(BaseIndicatorFormSet, self).save_new(form, commit=commit)
        form.instance = instance

        for nested in form.nested:
            nested.instance = instance

        for cd in nested.cleaned_data:
            cd[nested.fk.name]=instance

        return instance

    def add_fields(self, form, index):
        super(BaseIndicatorFormSet, self).add_fields(form, index)

        try:
            instance = self.get_queryset()[index]
            pk_value = instance.pk
        except IndexError:
            instance=None
            pk_value = hash(form.prefix)

        form.nested = [
            IndicatorValueFormSet(
                instance=instance,
                disease=instance.relevantdisease,
                prefix='value_%s' % pk_value,
                queryset=IndicatorValue.objects.filter(relevantindicator=pk_value),
            )
        ]

    def should_delete(self, form):
        """
        Convenience method for determining if the form's object will
        be deleted; cribbed from BaseModelFormSet.save_existing_objects.
        """

        if self.can_delete:
            raw_delete_value = form._raw_value(DELETION_FIELD_NAME)
            should_delete = form.fields[DELETION_FIELD_NAME].clean(raw_delete_value)
            return should_delete

        return False

    def save_all(self, commit=True):
        """
        Save all formsets and along with their nested formsets.
        """

        # Save without committing (so self.saved_forms is populated)
        # - We need self.saved_forms so we can go back and access
        #    the nested formsets
        objects = self.save(commit=False)

        # Save each instance if commit=True
        if commit:
            for o in objects:
                o.save()

        # save many to many fields if needed
        if not commit:
            self.save_m2m()

        # save the nested formsets
        for form in set(self.initial_forms + self.saved_forms):
            if self.should_delete(form): continue

            for nested in form.nested:
                nested.save(commit=commit)

class BaseIndicatorValueFormSet(BaseInlineFormSet):

    def __init__(self, disease, *args, **kwargs):
        self.disease = disease
        super(BaseIndicatorValueFormSet, self).__init__(*args, **kwargs)

    def _construct_form(self, i, **kwargs):
        form = super(BaseIndicatorValueFormSet, self)._construct_form(i, **kwargs)
        form.fields['relevantindicator'].parent_instance = self.disease
        return form

    def save_new(self, form, commit=True):
        instance = form.save(commit=False)
        instance.disease = self.disease
        if commit:
           instance.save()
        return instance

    def save_existing(self, form, instance, commit=True):
        return self.save_new(form, commit)

IndicatorValueFormSet = inlineformset_factory(
    Indicator,
    IndicatorValue,
    formset=BaseIndicatorValueFormSet,
    extra=3
)

IndicatorFormSet = inlineformset_factory(
    Disease,
    Indicator,
    formset=BaseIndicatorFormSet,
    extra=0
)

A: Try making a custom ModelForm to filter your relevantindicator field:
class IndicatorValueForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        try:
            disease_obj = kwargs.pop('disease')
        except KeyError:
            super(IndicatorValueForm, self).__init__(*args, **kwargs)
            return
        super(IndicatorValueForm, self).__init__(*args, **kwargs)
        queryset = Indicator.objects.filter(relevantdisease =disease_obj)
        self.fields['relevantindictor'].queryset = queryset

This amends the Forms init method with the disease object you wish to filter on, adding it to the kwargs.
To use it, we need to pass in the Disease object into the form with the curry method:
disease_obj = <your-disease-instance>
CurriedForm = staticmethod(curry(IndicatorValueForm, disease = disease_obj))
IndicatorValueFormSet = inlineformset_factory(Indicator, IndicatorValue,   formset=BaseIndicatorValueFormSet, form = CurriedForm, extra=3)

Now your drop down should only show the indicators filtered by disease.


text:
Q: DataGridVIew row to e-mail I have DataGridView control where I want cell values from every selected row to be send as an e-mail body text as one string line:
        private void buttonReport_Click(object sender, EventArgs e)
    {
        MailAddress from = new MailAddress("hi@greetings.com", "Hello");
        MailAddress to = new MailAddress("hi1234@gmail.com", "Hi");
        string join;

        foreach (DataGridViewRow row in dgvTest.Rows)
        {
            List<string> email = new List<string>();
            {
                if (Convert.ToBoolean(row.Cells[cbSelect.Name].Value) == true)
                {
                    foreach (DataGridViewCell cell in row.Cells)
                    {
                        if (cell.Value != null)
                        {
                            email.Add(cell.Value.ToString());
                        }
                    }
                }
            }
            foreach (string items in email.Skip(1).Take(4))
            {
                join = String.Join(", ", items.ToString());
                SendEmail("Hi!", from, to, join);
            }
        }
    }

This is the code, however I am getting 4 mails now because the SendMail() is in the foreach loop, if I take it out, the local variable join is not accessible..? how to work around this? I am using the email.Skip(1).Take(4) to omit some unnecessary values? Thanks in advance

A: Move declaration List<string> email = new List<string>(); outside foreach. Not sure why you need Skip(1).Take(4)
I suggest following code:
//declared somewhere above
List<string> CellsForReport = new List<string>{ "item1", "item2", "item3", "item4" }

//code inside buttonReport_Click
List<string> emails = new List<string>();
foreach (DataGridViewRow row in dgvTest.Rows)
{
  if (Convert.ToBoolean(row.Cells[cbSelect.Name].Value) == true)
  {
    //list to collect current row items
    var currentMailItems = new List<string>()
    foreach (var cellName in CellsForReport )
    {
       //this can throw exception if you specified wrong name above
       var cell = row.Cells[cellName];
       if (cell.Value != null)
       {
         currentMailItems.Add(cell.Value.ToString());
       }
    }
    //construct email text from row
    var finalEmailText = string.Join(", ", currentMailItems);
    emails.Add(finalEmailText);
  }
}
//sending 1 email per row
foreach (var email in emails)
{
  SendEmail("Hi!", from, to, email);
}


text:
Q: Is there a term for the type of misleading joke comedians such as Stephen Colbert often use? The Late Show host, Stephen Colbert (an American talk show host, don't mind that, just think of him as some random guy you don't have to care about) quite often uses a type of joke whereby he describes one thing to mislead you, then name the other thing that you've thought the preceding description described but in fact didn't. For example:

*

*"Some people are buying the wrong 'Fire and Fury'", instead picking up 'Fire and Fury: The Allied Bombing of Germany, 1942-1945' (...) One is a book about taking down a fascist regime, and the other's about WWII.

*This is amazing, this is the meeting of Disney and Beyonce. The world's most beloved brand and... Disney.

*Disney isn't buying all of Fox (...) "not included in the acquisition: Fox News," which really is surprising, cause you'd think that the masters of fantasy and imagination would want to be bought by Disney.

Is there a term for this kind of joke?

A: On Chris Head's site, a page called "Stand-up Comedy Fundamentals: Part 2, Misdirection" (July 28, 2016) uses the term misdirection for this type of set-up-based joke:

Having explored set-up/ payoff in the first blog we now turn out attention to a particular kind of set-up/ payoff: misdirection. I would unconsciously have laughed at misdirection for years, but I first became consciously aware of it watching Have I Got News For You in the 90s. (A formative decade for me.) I didn't yet have a word for it, but I began to notice that host Angus Deayton would often make the audience assume he was talking about one news story and then, at the last moment, would reveal he was talking about another.
...
Once I had picked up on the technique I began to notice it everywhere. But I didn't have a word for it until I read veteran US stand-up coach Greg Dean's book [Step by Step to Stand-up Comedy (2001)] and found that comedians (like magicians) used the word misdirection. Now, twenty years later, when teaching misdirection I often use a list of example gags that I compiled from a range of sources online. Three examples from the list will suffice here:
A lady with a clipboard stopped me in the street the other day. She said, "Can you spare a few minutes for Cancer Research?" I said, "All right, but we're not going to get much done." (Jimmy Carr)
I hate people who think it's clever to take drugs...like customs officers. (Jack Dee)
My grandmother started walking five miles a day when she was sixty. She's ninety-seven now, and we don't know where the hell she is. (Ellen Degeneres)
Part of the funniness in all of these is the attitude, namely a flippant attitude to a cancer charity, a rebellious attitude to drugs and a couldn't-care attitude to the elderly. A student on the joke class once described the payoffs as transgressing social norms, and there is some truth in this.
Again though, thinking solely about the mechanism, in all three jokes the set-up creates assumptions. Greg Dean talks about the "target assumption". Then the payoff, the rug-pull as comedians sometimes say, subverts those assumptions.

As Head notes, misdirection is an established term in magicians' terminology. Don Wilmeth, The Language of American Popular Entertainment: A Glossary of Slang and Terminology (1981) has this entry for the term:

Misdirection: The magician's art of diverting the audience's attention from some secret maneuver or device involved in making an illusion or trick work.

The absence here of any discussion of misdirection in the context of stand-up comedy suggests that the term was not well-establish in that sense on 1981. Google books searches for "misdirection joke[s]" turn up eight verifiable matches (not including Greg Dean's book, which is not previewable). Seven of those are from 2010 or later, but one rather skimpy reference (previewable in snippet view only) is from 1981.

A: I know it is not a single word, but this form of joke is often called a "Bait and Switch" or "Bait and Switch Comparison".
I suppose one word that might cover this is;
Switcheroo

A sudden unexpected variation or reversal, often for a humorous
  purpose.

https://en.wikipedia.org/wiki/Switcheroo
Another, perhaps better, is;
Paraprosdokian

A figure of speech in which the latter part of a sentence, phrase, or
  larger discourse is surprising or unexpected in a way that causes the
  reader or listener to reframe or reinterpret the first part.

https://en.wikipedia.org/wiki/Paraprosdokian

A: Paraprosdokian (see this Wiki page) :

A paraprosdokian is a figure of speech in which the latter part of a sentence, phrase, or larger discourse is surprising or unexpected in a way that causes the reader or listener to reframe or reinterpret the first part. It is frequently used for humorous or dramatic effect [...]

A: Having watched the second clip in your examples, this is an example of antithesis, juxtapositioning and comic irony.
Antithesis

Makes a connection between two things - "That's one small step for a
  man, one giant leap for mankind." (Neil Armstrong) - Your dictionary.com

The connection in your second example is between the brand of Disney and the brand of Beyonce.
The jokes are also ironic (you would expect that when he talks of the best loved brand having just mentioned Beyonce and Disney, he would actually mean Disney but he continues to say he meant Beyonce), so the jokes demonstrate comic irony.
Comic Irony

Irony is often used in literature to produce a comic effect. This may
  also be combined with satire. For instance, an author may facetiously
  state something as a well-known fact and then demonstrate through the
  narrative that the fact is untrue.- Wikipedia

The jokes also demonstrate the use of juxtaposition:
Juxtaposition:

The fact of two things being seen or placed close together with
  contrasting effect. - OLD

So you could describe the jokes as examples of antithesis, juxtaposition, comic irony, or indeed any combination of these three devices.


text:
Q: randomly generating unique number between 1-999 for primary key in table I have a problem I'm not sure how to solve elegantly.
Background Information
I have a table of widgets.  Each widget is assigned an ID from a range of numbers, let's say between 1-999. The values of 1-999 is saved in my database as "lower_range" and "upper_range" in a table called "config".
When a user requests to create a new widget using my web app, I need to be able to do the following:

*

*generate a random number between 1 and 999 using lua's math.random function or maybe a random number generator in sqlite (So far, in my tests, lua's math.random always returns the same value...but that's a different issue)

*do a select statement to see if there already is a widget with this number assigned...

*if not, create the new widget.

*otherwise repeat process until you get a number that is not currently in use.

Problem
The problem I see with the above logic is two-fold:

*

*the algorithm can potentially take a long time because I have to keep searching until I find a unique value.

*How do I prevent simultaneous requests for new widget numbers generating the same value?

Any suggestions would be appreciated.
Thanks

A: Generate your random numbers ahead of time and store them in a table; make sure the numbers are unique. Then when you need to get the next number, just check how many have already been assigned and get the next number from your table. So, instead of

*

*Generate a number between 1-999

*Check if it's already assigned

*Generate a new number, and so on.

do this:

*

*Generate array of 999 elements that have values 1-999 in some random order

*Your GetNextId function becomes return ids[currentMaxId+1]
To manage simultaneous requests, you need to have some resource that generates a proper sequence. The easiest is probably to use a key in your widget table as the index in the ids array. So, add a record to the widgets table first, get its key and then generate widget ID using ids[key].

A: Create a table to store the keys and the 'used' property.
CREATE TABLE KEYS
  ("id" INTEGER, "used" INTEGER)
;

Then use the following to find a new key
select id
from KEYS
where used = 0
order by RANDOM()
limit 1

A: Don't generate a random number, just pick the number off a list that's in random order.
For example, make a list of numbers 1 - 999.  Shuffle that list using Fisher-Yates or equivalent (see also Randomize a List in C# even if you're not using C#).
Now you can just keep track of the most recently used index into your list.  (Shuffling the list should occur exactly once, then you store and reuse the result).
Rough pseudo-code:
If config-file does not contain list of indices
    create a list with numbers 1 - 999
    Use Fisher-Yates to shuffle that list
    // list now looks like 0, 97, 251, 3, ...
    Write the list to the config file
    Set 'last index used' to 0 and write to config file
end if

To use this,
NextPK = myList[last-index-used]
last-index-used = last-index-used + 1
write last-index-used to config file

A: To get and flag an ID as used at same time (expanding on Declan_K's answer):
replace into random_sequence values ((select id from random_sequence where used=0 order by random()), 1);
select id from random_sequence where rowid = last_insert_rowid();
6
When you run out of "unused" sequence table entries the select will return "blank"
I use replace into as update doesn't have an last_insert_rowid() equiv that I can see.

A: You Can get sql to create a primary key, that will increase by one evert time you add a ros to the database.


text:
Q: how to push webservice code to github I have a project that has a webservice for send sms.
when I add the WSDL address in my project some files add to my project that include some code.
when I add my project to github all file added except the file that web service  add to my project.
why?


text:
Q: I want to set a calculated priority using the server timestamp provided by Firebase I would like to set the priority of a child using the server time stamp provided by Firebase, ServerValue.TIMESTAMP:
mFirebaseref.child(userid).setPriority(ServerValue.TIMESTAMP);

But my case is inverse. I want to set negative ServerValue.TIMESTAMP to move my child to the top based on time. Is it possible to do that in Firebase without using the local time stamp System.CurrentTimeInMillis()?
I would like to do something like this:
mFirebaseref.child(userid).setPriority(-ServerValue.TIMESTAMP);

A: On the client side, ServerValue.TIMESTAMP is an object structured like this: {.sv: "timestamp"}
So, as you know, you can't easily do what you wanted. However, there may be a different solution. If, for example, you wanted the five most recent entries, you could still set the priority by ServerValue.TIMESTAMP:
mFirebaseref.child(userid).setPriority(ServerValue.TIMESTAMP);

And then use the limitToLast() method:
Query queryRef = mFirebaseref.limitToLast(5);

To get the five most recent entries.
Also, this may help: Display posts in descending posted order

A: You are basically asking how to get negative server timestamp and it should work offline. I found a way, there is a hidden field you can use. A snippet from documentation:
Firebase offsetRef = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com/.info/serverTimeOffset");
offsetRef.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    double offset = snapshot.getValue(Double.class);
    double estimatedServerTimeMs = System.currentTimeMillis() + offset;
  }

  @Override
  public void onCancelled(FirebaseError error) {
    System.err.println("Listener was cancelled");
  }
});


text:
Q: attempt to insert nil object from objects[1]' I would like to show ChatViewController via a tab bar controller. The current initial view for the app is a NavigationController that loads the ChatViewController. When the ChatViewController is loaded, it checks to see if the 'joinedchat' method was called. If not, it presents LoginViewController to allow users to authenticate into the ChatViewController. When the user authenticates, LoginViewController is dismissed.
The LoginViewController and the ComposeViewController, are modal view controllers that are displayed on top of the ChatViewController.
I would like to access this ChatViewController at a much later point in the storyboard, while keeping it as the rootviewcontroller so it can still preserve the data model it uses for classes in anticipation of the $_POST method it uses.
Instead of presenting the LoginViewController if joinedchat hasn't yet been called, I am showing a different view controller. About 4 view controllers later, after the user has gone on a different process, I use a tab bar controller to access the LoginViewController again. When I try to call the postUpdateRequest method to access the ChatViewController, the app crashes with the output in the debugger:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[1]'
I suspect it's because the app uses a strict data model that sets snd stores default versions of the strings that will be posted by the user from LoginViewController via postJoinRequest. Does anyone know any ways to authenticate users using this data?
AppDelegate.m - didRegisterForRemoteNotificationsWithDeviceToken
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{

UINavigationController *navigationController = (UINavigationController*)_window.rootViewController;
ChatViewController *chatViewController = (ChatViewController*)[navigationController.viewControllers objectAtIndex:0];

DataModel *dataModel = chatViewController.dataModel;
NSString* oldToken = [dataModel deviceToken];

NSString* newToken = [deviceToken description];
newToken = [newToken stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
newToken = [newToken stringByReplacingOccurrencesOfString:@" " withString:@""];

NSLog(@"My token is: %@", newToken);

[dataModel setDeviceToken:newToken];

if ([dataModel joinedChat] && ![newToken isEqualToString:oldToken])
{
    [self postUpdateRequest];
}

}

AppDelegate.m - PostUpdateRequest
- (void)postUpdateRequest
{
UINavigationController *navigationController = (UINavigationController*)_window.rootViewController;
ChatViewController *chatViewController = (ChatViewController*)[navigationController.viewControllers objectAtIndex:0];

DataModel *dataModel = chatViewController.dataModel;

NSDictionary *params = @{@"cmd":@"update",
                         @"user_id":[dataModel userId],
                         @"token":[dataModel deviceToken]};

AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:ServerApiURL]];
[client
 postPath:@"/api.php"
 parameters:params
 success:nil failure:nil];
}

DataModel.m - initializer
+ (void)initialize
{
if (self == [DataModel class])
{
    // Register default values for our settings
    [[NSUserDefaults standardUserDefaults] registerDefaults:
        @{NicknameKey: @"",
            SecretCodeKey: @"",
            JoinedChatKey: @0,
            DeviceTokenKey: @"0",
            UserId:@""}];
}
}

DataModel.m - userId
- (NSString*)userId
{
NSString *userId = [[NSUserDefaults standardUserDefaults] stringForKey:UserId];
if (userId == nil || userId.length == 0) {
    userId = [[[NSUUID UUID] UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    [[NSUserDefaults standardUserDefaults] setObject:userId forKey:UserId];
}
return userId;
}

LoginViewController.h (Update)
@class DataModel;

// The Login screen lets the user register a nickname and chat room
@interface LoginViewController : UIViewController
@property (nonatomic, assign) DataModel* dataModel;
@property (nonatomic, strong) AFHTTPClient *client;
@end

LoginViewController.m - postJoinRequest & loginAction
- (void)postJoinRequest
{
MBProgressHUD* hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = NSLocalizedString(@"Connecting", nil);

NSDictionary *params = @{@"cmd":@"join",
                         @"user_id":[_dataModel userId],
                         @"token":[_dataModel deviceToken],
                         @"name":[_dataModel nickname],
                         @"code":[_dataModel secretCode]};

[_client postPath:@"/api.php"
                          parameters:params
                             success:^(AFHTTPRequestOperation *operation, id responseObject)
{

                                 if ([self isViewLoaded]) {
                                     [MBProgressHUD hideHUDForView:self.view animated:YES];

                                     if([operation.response statusCode] != 200) {
                                         ShowErrorAlert(NSLocalizedString(@"There was an error communicating with the server", nil));
                                     } else {
                                         [self userDidJoin];
                                     }
                                 }
                             } failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
                                 if ([self isViewLoaded]) {
                                     [MBProgressHUD hideHUDForView:self.view animated:YES];
                                     ShowErrorAlert([error localizedDescription]);
                                 }
                             }];
}

- (IBAction)loginAction
{
if (self.nicknameTextField.text.length == 0)
{
    ShowErrorAlert(NSLocalizedString(@"Fill in your nickname", nil));
    return;
}

if (self.secretCodeTextField.text.length == 0)
{
    ShowErrorAlert(NSLocalizedString(@"Fill in a secret code", nil));
    return;
}

[self.dataModel setNickname:self.nicknameTextField.text];
[self.dataModel setSecretCode:self.secretCodeTextField.text];

// Hide the keyboard
[self.nicknameTextField resignFirstResponder];
[self.secretCodeTextField resignFirstResponder];

[self postJoinRequest];
}

ChatViewController.h (Update)
#import "ComposeViewController.h"

@class DataModel;

// The main screen of the app. It shows the history of all messages that
// this user has sent and received. It also opens the Compose screen when
// the user wants to send a new message.
@interface ChatViewController : UITableViewController <ComposeDelegate>

@property (nonatomic, strong, readonly) DataModel* dataModel;

@end

Update Terminal Output


text:
Q: Cmake change compilation flags I want to run automatic optimization flags benchmark for my cmake project.
Project is cross-compiling, basic c/cxx flags are set in toolchain file assignable with -DCMAKE_TOOLCHAIN_FILE=<...>.
I want to change c/cxx flags during benchmarking, but I don't want to change toolchain file on each benchmark iteration. I just want to change some flags set from toolchain to other value (for example, -mtune=cortex-a8 to -mtune=cortex-a9). I think the best way is use -DMY_TUNE_FLAG=<..>.
But how I can change previously set flag? (not append flag to c/cxx flags).

A: I found solution by myself. Where is helpful string function.
For example, i can use variable BENCH_ARCH  for change ARM arch.
I wrote in toolchain file after all default C/C++ flags definition. First, add variable for caching:
...
set(BENCH_ARCH "${BENCH_ARCH}" CACHE STRING "Arch" FORCE)`
...

After that, check that variable is set and replace flags variable
if(BENCH_ARCH)
    string(REGEX REPLACE "-march=[A-Za-z_0-9/-]*" "-march=${BENCH_ARCH}"          <variable, which set flags> ${<variable, which set flags>})
endif()
...

For example:
string(REGEX REPLACE "-march=[A-Za-z_0-9/-]*" "-march=${BENCH_ARCH}" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS})

Now, i can use cmake -DBENCH_ARCH=armv5te -DCMAKE_TOOLCHAIN_FILE=<...> ... for enabling -march=armv5te and use cmake -DCMAKE_TOOLCHAIN_FILE=<...> ... for enabling default toolchain setting. Hope this will be helpful not only for me.


text:
Q: Elasticsearch: Undefined method 'perform' for # [test env] I'm writing tests for my app (in Rspec) and lost a whole day trying to figure out where did I make a mistake with Capybara. I noticed that when a action is called (change_status), the following errors occur in the test.log:
undefined method `perform' for #<Indexer:0x000000095d9680>

and the changes are not saving. I have no idea where to start looking. I'm guessing it's a problem with Elasticsearch. Here's the whole action from the controller:
def change_status
  product = Product.find_by(id: params[:id])
  product.update_attribute(:status, params[:product][:status])
  if params[:product][:status] == "accepted"
    kind = Kind.where(name: "title").first
    product.author.change_points({points: 2, kind: kind.id})
  elsif params[:product][:status] == "rejected"
    kind = Kind.where(name: "title").first
    product.author.change_points({points: 1, kind: kind.id})
    product.author.change_points({points: -3, kind: kind.id})
  end

  user_id = product.author_id
  products = Product.where(author_id: user_id)
  if products.where(status: "accepted").count == 3
    user = User.find_by(id: user_id)
    user.update_attribute(:approved, true)
    kind = Kind.where(name: "title").first
    user.change_points({points: 1, kind: kind.id})
    redirect_to products_path
  else
    redirect_to action: "pending_products", id: user_id
  end
end

Any suggestion? Besides this, the log is useless...
EDIT:
class Indexer
  include Sidekiq::Worker

  sidekiq_options queue: 'elasticsearch', retry: false, backtrace: true

  Logger = Sidekiq.logger.level == Logger::DEBUG ? Sidekiq.logger : nil
  Client = Elasticsearch::Client.new host: (ENV['ELASTICSEARCH_URL'] || 'http://localhost:9200'), logger: Logger

  def perform(operation, klass, record_id, options={})
    logger.debug [operation, "#{klass}##{record_id} #{options.inspect}"]

    case operation.to_s
      when /index|update/
        record = klass.constantize.find(record_id)
        record.__elasticsearch__.client = Client
        record.__elasticsearch__.__send__ "#{operation}_document"
      when /delete/
        Client.delete index: klass.constantize.index_name, type: klass.constantize.document_type, id: record_id
      else raise ArgumentError, "Unknown operation '#{operation}'"
    end
  end
end


text:
Q: TYPO3 Fluid - Exit a for loop Is it somehow possible to break out of a for loop in fluid?
<f:for each="{subItem.image}" as="imageItem">
 <f:if condition="{selectedCategory} == {subItem.imagecategory}">
  Do Stuff
  Exit loop
 </f:if>
</f:for>

I need to loop trough a couple of images then render one if the category matches and exit the loop after that since I only want to render the first image with the matching category.

A: You can use Fluid variable view helper:
<f:variable name="imageRendered" value="0" />
<f:for each="{subItem.image}" as="imageItem">
 <f:if condition="{selectedCategory} == {subItem.imagecategory} && {imageRendered} == 0">
  Do Stuff
  Exit loop
  <f:variable name="imageRendered" value="1" />
 </f:if>
</f:for>

A: Maybe you can use a dataprocessor to give you an array with just the images in the category, and then you can just grab the first image with {imageItem.0}.
Have a look at TYPO3\CMS\Frontend\DataProcessing\FilesProcessor.


text:
Q: How to prevent NaN values appending to ArrayList? I have data stored in DoubleTimeSeries as:
DoubleTimeSeries width = DoubleTimeSeries.getDoubleTimeSeries(connection, userId, "Width");
DoubleTimeSeries height = DoubleTimeSeries.getDoubleTimeSeries(connection, userId, "Height");

and I am adding the above results into ArrayList as:
ArrayList<String> myArray = new ArrayList<>();
for (int i = 0; i < width.size(); i++) {
    myArray.add(width.get(i) + "," + height.get(i) );
}
System.out.println("My Array: \n" + myArray);

My issue: Some of the width or height value is empty (it is NaN) in my file and when i am adding them into my ArrayList, I am getting such as:
[NaN,NaN, 25,50, 55, 60, NaN,NaN, 45,56]

Now: How I can prevent (or ignore) these NaN values from adding into my ArrayList. I want the ArrayList results as:
[25,50, 55, 60, 45,56]

Thanks

A: Compare the value with NaN, and only add if false.
for (int i = 0; i < width.size(); i++) {
    if (!Double.isNaN(width.get(i)) && !Double.isNaN(height.get(i))) {
        myArray.add(width.get(i) + "," + height.get(i) );
    }
}

A: just add a test for the width : if (width.get(i)==NaN){i++} and do not use for use do .. while


text:
Q: Django Rest Framework: Unclear error message my views.py:
class user_password(generics.UpdateAPIView):
    authentication_classes = ([JSONWebTokenAuthentication])
    serializer_class = user_password_serializer

    def get_queryset(self):
        return User.objects.get(id=self.request.user.id)

But I'm getting this when running it:

AssertionError: Expected view user_password to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly.

I know the serializer is okay because when I use a different type of View for the same thing. It works:
class user_password(APIView):

    authentication_classes = ([JSONWebTokenAuthentication])

    def put(self, request, format=None):

        serializer = user_password_serializer(data=request.data)
        if serializer.is_valid():
            if request.user.check_password(serializer.validated_data[
                                                'old_password']):
                request.user.set_password(serializer.validated_data[
                                          'new_password'])
                request.user.save()

                return Response({'success': True,
                                'result': serializer.validated_data},
                                status=status.HTTP_200_OK)
            else:
                    return Response({'success': False,
                                    'result': "credential mismatch"},
                                    status=status.HTTP_401_UNAUTHORIZED)

        return Response({'success': False,
                        'result': serializer.errors},
                        status=status.HTTP_400_BAD_REQUEST)

I do not wish to change the way an endpoint is constructed. I do have a JWT authenticated call, and I wish /user/password would simply be able to PUT the 'old password' and 'new password' into that very same user.
What am I doing wrong in my generics.UpdateAPIView class? what is that .lookup_field it's talking about?

A: .lookup_feild is the field (capture group) the UpdateAPIView expects in your url pattern (pk by default), like:
r'^user/(?P<pk>\d+)/password/?$'

However, you should be able to override get_object instead of get_queryset and it should work without any changes to the url.
class user_password(generics.UpdateAPIView):
    authentication_classes = ([JSONWebTokenAuthentication])
    serializer_class = user_password_serializer

    def get_object(self):
        return User.objects.get(id=self.request.user.id)

Also, simply returning self.request.user will work just fine (I don't know how exactly JWT authentication implemented in your project, but most of the time Django pulls the user model in request.user anyway).


text:
Q: Same Variable, different result I just started out learning c# and I came across something confusing, I hope someone can explain it to me :)
namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int Md = 0;

        private void cmdAnzeigen1_Click(object sender, EventArgs e)
        {
            int x = 0;
            Md = Md + 1;
            x = x + 1;
            lblErgebnis.Text = "x: " + x + "\n" + "Gx:" + Md;
        }
    }
}

How come Md always increases by 1, but x doesn't (stays at 1)? I don't understand, they are both the same variables.

A: Md is an instance variable, declared outside any method. It's part of the state of the object, so it "lives" (and maintains its value) for as long as the object is "alive". Different instances of Form1 would have independent Md variables.
x is a local variable - there's a new variable every time you call the method, and it always starts with a value of 0.
If that isn't enough explanation, please consult a good introductory C# book or tutorial - explaining everything about variables would be a bit much for Stack Overflow, which is more for handling specific problems than learning the fundamentals of a programming language.

A: x is a local variable. It only exists in the scope of the cmdAnzeigen1_Click()-Method. Whenever it is called, x gets freshly initialized with a 0, then incremented. So at the end of the method, it's always 1. The other, however, lives in the scope of the class, it is not reinitialized and keeps it's value for the time the class lives.

Also, look at the code of the method- you declare and initialize the variable anew each iteration. That's how it works: The code in that method will be processed sequentially when it's called, and that initialization doesn't live past the method.

As for scopes, try something like this and see what happens:
int x = 1;
{
    int y = x + 1;
}
int z = x + y;

It will throw an error, since the brackets introduce a new scope. Variables from the outer are available to the inner, but not vice versa.

A: When your method (cmdAnzeigen1_Click) has finished executing, then the memory that your x variable is using is free'd up ready to be used again elsewhere, as well as any other variables that reside within the method.
The same would happen for your form.
if you had something similar to
using(Form1 frm = new Form1()
{
frm.ShowDialog();
}

Then as soon as you leave the using block, the variable Md's place in memory will be free'd up.
Md is able to increment as it still holds its place in memory, where as x is nolonger required post method

A: Because MD is class level variable and x is not. On every click x is created and destroyed. But value of Md is retained. Md will retain its value till Form1 is retained.

A: This is because of the scope of your variables. MD is declared outside the function scope i.e in Instance scope, therefore it is never re-initialized when you click on button. Whereas x is in the function scope so it is re-initialized to 0 everytime you click on the button.


text:
Q: Can I change the datsource of report model at runtime I've some adhoc reports developed on some report models which are published on Report Server (we're using SSRS 2008). Everything is running well. Now in our production environment we've near about forty (40) customers who have their own database (each have the same table structures and other database objects). Now the challenge is whenever a customer will log into the report server using windows authentication and trying to view those reports we need to get the SQL data from the proper database only.
Reports are designed using the report model and each model has a valid data source which is connected to particular database. We can create forty separate data sources each will be connected to specific database.
My question is, is there any way through which we can change the report model data source name dynamically or during runtime based on the customer name so that during execution of the report, SSRS would fetch the data from the correct database but not from any other database.
Please help me.

A: I don't think there is a way to specify at execution time a data source because the data source is part of the report definition (.rdl) and it has some security around it preventing a find-and-replace type method.  However, there are functions available in the SSRS services (search for ReportingService2010.cs for an example) for us in .NET applications that allow you to set a data source.  I know I've been on a project in the past where we deployed using an in-house created .NET application that uses these calls to set the data source on publish.  This was for SSRS 2005.
On another project I've been on the method of choice is to publish using BIDS publish.  We noticed that if you have the report already published out in an environment with a data source set that re-publishing using BIDS to the same location would retain the data source information (even if it were different than your development source).  This was using SSRS 2008R2.


text:
Q: Receive next page of movies from API when bottom of RecyclerView is reached? I'm currently working on a project in which we have to develop an Android application that retrieves movies from The Movie Database API (https://www.themoviedb.org/). One of the app's functionalities is retrieving Popular movies from the API and displaying them in a RecyclerView, like this:

The movies are retrieved from this URL: https://api.themoviedb.org/3/movie/popular?api_key=4c422ac80f2c83f42b8f905d4303959d&language=en&page=1
As you can see, there are 500 pages. It's not a solution to load all 500 pages in my Asynctask before displaying the data in the RecyclerView, because it would take way too long for everything to load. Instead, I would like for the RecyclerView to detect when the end of the list is reached, and then load the next page from the API. I have no idea how to work this out.
I am very close to a solution, which is adding an OnScrollListener to the RecyclerView and retrieving the next page if the RecyclerView can't scroll vertically 2 items, but I haven't yet got the logic right. With my current code, once I get near the end of the first page, it will instantly load the other 499 pages, which leaves the newly loaded movies unclickable because the tasks haven't finished yet. I need to get it to work so that once the second page has loaded, it once again checks if the RecyclerView can't scroll vertically 2 items.
Method for building the URL in my UrlBuilder class:
    public static URL buildPopularMovieListUrl(int page) {
        Log.d(TAG, "Method called: buildPopularMovieListUrl");

        // Paths and parameters are appended to the base URL.
        Uri builtUri = Uri.parse(BASE_URL_TMDB).buildUpon()
                .appendPath(MOVIE_PATH)
                .appendPath(POPULAR_PATH)
                .appendQueryParameter(PARAM_API_KEY, API_KEY)
                .appendQueryParameter(PARAM_LANGUAGE, LANGUAGE)
                .appendQueryParameter(PARAM_PAGE, String.valueOf(page))
                .build();

        URL url = null;
        try {
            url = new URL(builtUri.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        Log.d(TAG, "Built URL: " + url);

        return url;
    }

MainActivityFragment.java
package nl.avans.cinetopia.presentation;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

import nl.avans.cinetopia.R;
import nl.avans.cinetopia.adapters.PopularMoviesRecyclerViewAdapter;
import nl.avans.cinetopia.data_access.UrlBuilder;
import nl.avans.cinetopia.data_access.get_requests.GenresGetRequest;
import nl.avans.cinetopia.data_access.get_requests.PopularMovieGetRequest;
import nl.avans.cinetopia.data_access.utilities.JsonUtils;
import nl.avans.cinetopia.domain.Movie;

public class MainActivityFragment extends Fragment implements PopularMoviesRecyclerViewAdapter.OnItemClickListener {
    private static final String TAG = MainActivityFragment.class.getSimpleName();

    // RecyclerView attributes
    private RecyclerView mRecyclerView;
    private PopularMoviesRecyclerViewAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private ArrayList<Movie> mMovies = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_main_fragment, container, false);

        retrieveLatestGenresFromApi();
        retrievePopularMoviesFromApi(1);

        // Obtain a handle to the object.
        mRecyclerView = view.findViewById(R.id.activity_main_recyclerView);
        // Use a linear layout manager.
        mLayoutManager = new LinearLayoutManager(getActivity());
        // Connect the RecyclerView to the layout manager.
        mRecyclerView.setLayoutManager(mLayoutManager);

        // Specify an adapter.
        mAdapter = new PopularMoviesRecyclerViewAdapter(getActivity(), mMovies);
        // Connect the RecyclerView to the adapter.
        mRecyclerView.setAdapter(mAdapter);
        // Set OnItemClickListener.
        mAdapter.setOnItemClickListener(this);

        /* Add a divider to the RecyclerView. */
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.rv_divider));
        mRecyclerView.addItemDecoration(dividerItemDecoration);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                for (int i = 2; i < 500; i++) {
                    if (!recyclerView.canScrollVertically(2)) {
                        retrievePopularMoviesFromApi(i);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
        });

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void retrievePopularMoviesFromApi(int page) {
        PopularMovieGetRequest task = new PopularMovieGetRequest(new PopularMovieApiListener());
        task.execute(UrlBuilder.buildPopularMovieListUrl(page));
    }

    private void retrieveLatestGenresFromApi() {
        GenresGetRequest task = new GenresGetRequest(new JsonUtils.GenresApiListener());
        task.execute(UrlBuilder.buildGenreUrl());
    }

    /**
     * Listener class for the PopularMovieGetRequest.
     */
    class PopularMovieApiListener implements PopularMovieGetRequest.PopularMovieApiListener {
        /**
         * Fills our global ArrayList with the retrieved movies and notifies the adapter that the
         * dataset has changed.
         *
         * @param movies The list of movies retrieved by our PopularMovieGetRequest.
         */
        @Override
        public void handleMovieResult(ArrayList<Movie> movies) {
            Log.d(TAG, "Method called: handleMovieResult");

            // Add all movies to our ArrayList and notify the adapter that the dataset has changed.
            mMovies.addAll(movies);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(int position) {
        getActivity().getSupportFragmentManager().beginTransaction()
                .replace(R.id.activity_main_frameLayout, new MovieDetailsActivity(mMovies.get(position).getId()))
                .addToBackStack(null).commit();
    }
}

A: Why you are using raw code to fetch data from server instead of Retrofit library ? Retrofit is very easy to fetch data from server.only API call with object that's it.you can easily paging with library.See here how to implement it https://github.com/square/retrofit


text:
Q: NGINX Reverseproxy Problem: Publishing a Webapp behind a ReverseProxy i have a "little" NGinx Problem.
I have Multiple Webapps and i will publish it through the NGINX Reverseproxy.
Under 1 URL i will publish multiple Webapps:
so:
https://Reverseproxy/webappA
https://Reverseproxy/webappB
https://Reverseproxy/webappC

This work so:
https://Reverseproxy/webappA --> redirect to http://www.webappaWebserver.com/webappA

--> And naturally this works fine ;-).
But with my Webapp B i have a challenge. I must find a way to bring the follow Scenario to work:
https://Reverseproxy/webappB --> redirect to http://www.webappBWebserver.com/

--> And this doesn´t work becuse the Subsite (after the Slash) is not there. But i can´t made URL Webserverchanges on this Webserver.
So how i can get this get running with this Constellation?
Here are my Config for the Reverseproxy:
  location /appb {
    proxy_pass              http://10.254.1.41:80;
    include                /etc/nginx/conf.d/proxy.conf;
  }

proxy.conf:
proxy_http_version                 1.1;
proxy_cache_bypass                 $http_upgrade;

### Proxy headers
proxy_set_header Upgrade           $http_upgrade;
proxy_set_header Connection        $connection_upgrade;
proxy_set_header Host              $host;
proxy_set_header X-Real-IP         $remote_addr;
proxy_set_header Forwarded         $proxy_add_forwarded;
proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host  $host;
proxy_set_header X-Forwarded-Port  $server_port;

### Proxy timeouts
proxy_connect_timeout              60s;
proxy_send_timeout                 60s;
proxy_read_timeout                 60s;
~

Thank you very much for your help.

A: *

*Replace page_name with webappA,webappB or webappC .

*Replace example.com with your subdomain.
  location /page_name/ {
                  rewrite ^([^.]*[^/])$ $1/ permanent;
                  sub_filter_once off;
                  sub_filter_types *;
                  sub_filter /_elderjs /page_name/_elderjs;
                  proxy_ssl_verify off;
                  proxy_set_header Host "example.com";
                  proxy_set_header X-Forwarded-Host "";
                  proxy_set_header X-Forwarded-For "";
                  proxy_set_header Accept-Encoding "";
                  proxy_set_header Cookie "";
                  proxy_ssl_server_name on;
                  proxy_pass https://example.com/;
                  proxy_redirect ~^(http://[^/]+)(/.*)$ https://$http_host$2;
   }

Its works for me ;). Hope this answer solves your problem.


text:
Q: How do I keep an image in the center of the page regardless of browser window size? I want to do this using only CSS + HTML. It has to work in all major/latest browsers - not IE 6 just yet.
The code I have is as follows:

#left_arrow {
    position: absolute;
    left: 0px;
    margin: 10px 0 15px 0;  /* top, right, bottom, left */
    padding: 5px 5px 7px 5px;   /* top, right, bottom, left */
}

I tried doing the position as 'absolute', but if the browser size changes the arrow doesn't move and I want it to always be at the center of the browser regardless of the size.
Edit:
I want it to always be at the center of this div:

This is the entire block of code that it is within:

         |
         |
         |
         text

        Notice will be here.

Edit 2: If there is no CSS solution, a jQuery solution is also fine.
Edit 3: Still no takers? bump

A: I've had succes using "text-align:center" for the horizontal centering.  For the vertical centering, try this:
.vBox {min-height: 12em;   display: table-cell;   vertical-align: middle; }

Lorem Ipsum is simply dummy text

Cheers,
Erik


text:
Q: flutter User.Read azure active directory "Insufficient privileges to complete the operation" I am trying to get the data of a signed in user using Microsoft graph API. I work with the "aad_oauth" package in flutter. When signing in, an access token is provided. This access token is then used in a http.get request.
However every time I try to get the data, the following error appears.
"{"error":{"code":"Authorization_RequestDenied","message":"Insufficient privileges to complete the operation:"
I also added a permission at the ad admin center.

That's how I get the access token

This is my http request

A: I tried to reproduce the same in my environment and got the below results:
I created an Azure AD application and added user.read permission:

Now I generated access token via Postman with below parameters:
GET https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
grant_type:authorization_code

client_id:1b323717-80d8-4172-b141-XXXXXX
client_secret:GTT8Q~PErY3nTbj9LO8Nkkm2ai.XXXXXXX
scope:user.read
code:code
redirect_uri: redirect_uri

To get the details of the signed-in user, I ran the below query by including bearer token:
GET https://graph.microsoft.com/v1.0/me/


text:
Q: OnContextCreated() in Cef not being called I have a similar problem to the person in this post; I'm trying to extend the cefsimple.exe app included with the chromium embedded framework binaries to include a V8 handler. I implemented the OnContextCreated() method and made sure to extend RenderProcessHandler in the SimpleHandler class. I'm trying to implement a simple window bound variable called test_string; here's what my code looks like;
void SimpleHandler::OnContextCreated(
    CefRefPtr<CefBrowser> browser,
    CefRefPtr<CefFrame> frame,
    CefRefPtr<CefV8Context> context)
{
    CefRefPtr<CefV8Value> object = context->GetGlobal();

    object->SetValue("test_string", CefV8Value::CreateString("this is a test"), V8_PROPERTY_ATTRIBUTE_NONE);
}

But the program never arrives at any breakpoints I add within the method, and the variable is undefined on any webpages I load within the app. I saw that one of the solutions in the other thread is to enable the settings.single_process flag, which i've done, but my code still doesn't reach the breakpoint.
To be clear, I'm accessing the variable on pages with window.test_string.

A: Make sure that you are sending that CefApp to CefExecuteProcess.
  CefRefPtr<SimpleApp> app(new SimpleApp);

  // CEF applications have multiple sub-processes (render, plugin, GPU, etc)
  // that share the same executable. This function checks the command-line and,
  // if this is a sub-process, executes the appropriate logic.
  int exit_code = CefExecuteProcess(main_args, app, sandbox_info);
  if (exit_code >= 0) {
    // The sub-process has completed so return here.
    return exit_code;
  }

Found this solution here

A: Have you read through the General Usage guide? Some key points below
https://bitbucket.org/chromiumembedded/cef/wiki/GeneralUsage#markdown-header-cefapp
https://bitbucket.org/chromiumembedded/cef/wiki/GeneralUsage#markdown-header-processes
The single_process mode is not supported so I've never used it. In general I'd avoid it. The multi process architecture means you need to attach the debugger to the process. The Chromium guide is relevant to CEF in this instance.
https://www.chromium.org/developers/how-tos/debugging-on-windows#TOC-Attaching-to-the-renderer

A: you need to ensure your App is derived from CefRenderProcessHandler
not SimpleHandler!!!
class SimpleApp : public CefApp
    , public CefRenderProcessHandler
{

virtual void OnContextCreated(CefRefPtr<CefBrowser> browser,
    CefRefPtr<CefFrame> frame,
    CefRefPtr<CefV8Context> context) OVERRIDE;

valdemar-rudolfovich says you need to pass instance of SimpleApp in
CefExecuteProcess


text:
Q: How am i supposed to give input to pyperclip running in terminal? I am reading Automate the boring stuff with python and when I am running the program in the terminal it is not prompting for a input. I want to give many lines as input. How can I do this?

A: The the example in the book expects you to give your input when you are running program like,
python foo.py username password

If you want to be prompted while running use something like below in your script,
username = input("enter your username")
password = input("enter your password")

and then copy using pyperclip
pyperclip.copy(username)


text:
Q: How to return (not print) a fraction in python without simplifying it? The code below prints simplified fraction. But I want a non simplified one. Ex: If the answer is 2/4 I want the code to return 2/4 not 1/2.
from fractions import Fraction
def frac(n,d):
    print(Fraction(n/d))

frac(2,4) gives 1/2.
from fractions import Fraction
def frac(n,d):
    return(Fraction(n/d))

frac(2/4) gives Fraction(1,2)
What I want is return (Fraction(n/d)) to give 2/4.
How do I achieve this in python?

A: First, let's understand what is happening here, then we'll have a look at how to change it.
You have two different questions/problems in this one question.
Part 1: How to get "1/2" instead of "Fraction(1,2)"
When you print a fraction, it is first cast to string, and that returns the kind of output you want. If you just output the Fraction on the console (what is what happens when you call the function from the REPL), it is instead converted to string using repr()
str(Fraction(2/4)) --> "1/2"
repr(Fraction(2/4)) --> "Fraction(1, 2)"

So first, if you want to return the Fraction as a string, before the return you need to cast it to string:
def frac(n,d):
    return str(Fraction(n/d))

Part 2: Don't normalize the fraction
You said, you want to have frac(2,4) return "2/4" and not "1/2".
Let's see what happens in your code:
Fraction(n/d)

Since you pass n/d as a parameter to Fraction(), the division will be executed first, before the value even goes to Fraction(). To make this point more clear, let's execute the code statement by statement:
n=2
d=4
2/4 -> 0.5
Fraction(0.5)

As you see, you pass the divided result to Fraction(), so there is no way for Fraction() to know the divisor.
But, even passing the numerator and the divisor as separate parameters won't help you, since Fraction represents a normalized fraction.
That's just how that class works.

A: You can return a tuple from Fraction's numerator and denominator like (n, d) or as a string '1/2'. There is no other way

A: Creating a class and suitable functions might work.
class frac():
    def __init__(self,num,den):
        self.num = num
        self.den = den
    def decimal(self):
        return self.num / self.den

Something along the lines of that.


text:
Q: Unable to return JSON from REST API with RESTIFY I'm new to Node.js. I'm trying to create a web server that will 1) serve up static html web pages and 2) provide a basic JSON / REST API. I've been told by my management that I must use RESTIFY (I don't  know why). Currently, I have the following:
var restify = require('restify');
var fs = require('fs');
var mime = require('mime');
var ecstatic = require('ecstatic');

var ws = restify.createServer({
  name: 'site',
  version: '0.2.0'
});

ws.use(restify.acceptParser(server.acceptable));
ws.use(restify.queryParser());
ws.use(restify.bodyParser());
ws.use(ecstatic({ root: __dirname + '/' }));

ws.get('/rest/customers', findCustomers);

ws.get('/', ecstatic({ root:__dirname }));
ws.get(/^\/([a-zA-0-9_\.~-]+\/(.*)/, ecstatic({ root:__dirname }));

server.listen(90, function() {
  console.log('%s running on %s', server.name, server.url);
});

function findCustomers() {
  var customers = [
    { name: 'Felix Jones', gender:'M' },
    { name: 'Sam Wilson', gender:'M' },
    { name: 'Bridget Fonda', gender:'F'}
  ];
  return customers;
}

After I start the web server, and I try to visit http://localhost:90/rest/customers/ in my browser, the request is made. However, it just sits there and I never seem to get a response. I'm using Fiddler to monitor the traffic and the result stays as '-' for a long time.
How can I return some JSON from this type of REST call?
Thank you

A: At 2017, the modern way to do this is:
server.get('/rest/customer', (req,res) => {
  let customer = {
    data: 'sample value'
  };

  res.json(customer);
});

A: never worked with ecstatic but i don't think you need a file server for static content since you run restify and return json.
you are not getting a response because you don't terminate with res.send
the following code looks ok
ws.get('/rest/customers', findCustomers);
but try to change the findCustomers function like this
function findCustomers(req,res,next) {
  var customers = [
    { name: 'Felix Jones', gender:'M' },
    { name: 'Sam Wilson', gender:'M' },
    { name: 'Bridget Fonda', gender:'F'}
  ];
 res.send(200,JSON.stringify(customers));
}


text:
Q: Rails - how to pull specific sorted data out of database I have a database with columns (username, points). I am making a call to return some fields from this database to use in a program. I want to pull:

*

*The top 10 users with the most points

*The 5 users above/below the username requesting the rankings

I can pull the top 10 easily enough...
top_users = UserPoints.find(
  :all,
  :conditions => ['points > 0'],
  :order => "points DESC",
  :limit => 10)

Pulling the specific entry for the username requesting is also easy with find_by_username, but how could I determine where this user is ranked? Then, how would you go about finding the 5 users above and 5 users below the specific user (assuming the user is not in the top 10)?
Thanks!
-mark

A: Maybe do it using two queries?
Users above current user:
UserPoints.all(:conditions => ['points > ?', user.points], :limit => 5, :order => 'points asc')
Users below current user:
UserPoints.all(:conditions => ['points < ?', user.points], :limit => 5, :order => 'points desc')
Maybe there is a way to do it using a single query, I am not an SQL expert, but this should solve it for you.


text:
Q: Check value of both text boxes if they have values in it or not My page have multiple textboxes i wanted to make sure if user select value from text box 1 and leaves text box 2 empty then it should alert a popup that you must have to enter values in both textboxes.
i do not want to compare values with each other.(Like both textbox value must be same)
Textbox 1 is Number field and text box 2 is date field.
If any one value is entered then it should not allow user to submit page it should stop processing and redirect to that textbox which is empty.
Now what i have tried so far.
$( "#button_id" ).click(function() {

var n = document.getElementById('text1');
var m = document.getElementById('text2');

if(n.value.trim() != "" || n.value == undefined)
{
    if (n.value.trim() != "" && m.value.trim() == "")
    {
        alert("text1 should have some value");
        return false;
    }
}
if(m.value.trim() != "" || m.value == undefined)
{
    if (m.value.trim() != "" && n.value.trim() == "")
    {
        alert("text2 should have some values");
        return false;
    }
}

});

As mention below code i just wanted to check if textbox is disable or not if textbox is disable then do not test for validation else do.
Partial Solution :
 var _domArray = [$("#textbox1"),$("#textbox2")]
 var chk = $x('textbox2').disabled = false;

 $( "buttonid" ).click(function() {

 _domArray.forEach(function(item){
  if(item.val() ==''){
  var _getId =item.attr('id');
  alert(_getId +" should have some value" );
  this.browserEvent.preventDefault();
  this.browserEvent.stopImmediatePropagation();
  return false;
 }
 })
 });

A: Use the required attribute on your <input>s, then you can check in JavaScript with document.querySelector('form.insertSelectorHere').matches(':valid').

A: Use an array to store the DOM element,Loop through it and check to check if it is empty, If so through an alert.
Also assuming you are using input type number & date
var _domArray = [$("#text1"),$("#text2")]
$( "#button_id" ).click(function() {
 _domArray.forEach(function(item){
    if(item.val() ==''){
      var _getId =item.attr('id');
      alert(_getId +" should have some value" )
   }
})
});

Using jquery since you have tagged this with jquery
jsfiddle


text:
Q: How to transfer the value to recylerview of one which is received from another fragment? i have made two fragments in my app.
1st fragment (EditFrag) and 2nd fragment (ListTable). i want to transfer the value of 1st fragment(from EditText of 1st fragment) to the recyclerView of 2nd fragment.
how should i do that.....i can't find right documentation.
Thank you for your concern!
MainActivity:
public class MainActivity extends AppCompatActivity implements EditFrag.TransferValue{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListTable frag1=new ListTable();
        FragmentManager manager=getSupportFragmentManager();
        FragmentTransaction transaction=manager.beginTransaction();
        transaction.add(R.id.table_value_container,frag1,"fragment");
        transaction.commit();

        EditFrag frag2=new EditFrag();
        FragmentManager manager1=getSupportFragmentManager();
        FragmentTransaction transaction1=manager1.beginTransaction();
        transaction1.add(R.id.table_container,frag2,"fragment_edit");
        transaction1.commit();
    }

    @Override
    public void sendValue(String value) {
        Log.d("ashu","button is pressed");
        ListTable listTable = (ListTable) getSupportFragmentManager().findFragmentById(R.id.table_value_container);
        listTable.receiveValue(value);
    }

}

2nd fragment(ListTable):
public class ListTable extends Fragment {
    public TextView myEditText1;
    private RecyclerView recyclerView;

    public ListTable() {
//         Required empty public constructor
    }

    public static ListTable newInstance(String param1, String param2) {
        ListTable fragment = new ListTable();
        Bundle args = new Bundle();
        Log.d("ashu", "new instance is called :");
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d("ashu", "oncreata called by inflating: ");

        View view = inflater.inflate(R.layout.fragment_list_table, container, false);
        myEditText1 = (TextView) container.findViewById(R.id.table_value);

        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        MyAdapter a = new MyAdapter();
        recyclerView.setAdapter(a);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    public void receiveValue(String value) {

        myEditText1.setText(value);

    }

    public class MyAdapter extends RecyclerView.Adapter<MyDataViewHolder> {

        @Override
        public MyDataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            Log.d("ashu", "oncreateview holder of adapter ia called");

            LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.fragment_list_table, parent, false);

            return new MyDataViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyDataViewHolder holder, int position) {

            holder.myEditText.setText("Table: " + position);

        }

        @Override
        public int getItemCount() {
            return 10;
        }
    }

    public class MyDataViewHolder extends RecyclerView.ViewHolder {

        public TextView myEditText;

        public MyDataViewHolder(View itemView) {
            super(itemView);
            Log.d("ashu", "DAta view holder is called: ");
            myEditText = (TextView) itemView.findViewById(R.id.table_value);

        }
    }

}

1st Fragment(EditFrag):
public class EditFrag extends Fragment {
    TransferValue SendData;
    EditText inputvalue;
    Button click;

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.edit_frag_layout, container, false);
        inputvalue = (EditText) view.findViewById(R.id.edit_text);
        click = (Button) view.findViewById(R.id.click);

        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String received = inputvalue.getText().toString();

                SendData.sendValue(received);

            }
        });

        return view;

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        try {
            SendData = (TransferValue) context;
        } catch (ClassCastException e) {
            Log.d("ashu", "implement the methods");
            throw new ClassCastException("implemented the methods");
        }
    }

    public interface TransferValue {

        public void sendValue(String value);

    }
}

A: create the instance of fragment2 from where want to receive the value to:
public static Fragment2 createInstance(String data) {
        Fragment2 fragment = new Fragment2();
        Bundle bundle = new Bundle();
        bundle.putString("keyword", data);
        fragment.setArguments(bundle);
        return fragment;

    }

and the get the data as below:
Bundle bundle = getArguments();
        if (bundle != null) {
             String data = bundle.getString("data");
        }

A: You can use bundle in an order to pass data to fragment:
Example:
    // Set bundle as arguments to the fragment
    Bundle bundle = new Bundle();
    bundle.putString(MyKey1, MyValue1);
    bundle.putString(MyKey2, MyValue2);

    MyFragment myFragment = new MyFragment();
    myFragment.setArguments(bundle);

Inside onCreateView of fragment:
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.repairer_part_details_fragment, container, false);

        String value1 = getArguments().getString(MyKey1);
        String value2 = getArguments().getString(MyKey2);

        return view;
    }

A: There are many ways to do that. I see your codes above, and 2 fragments loaded at the same time. I usaually use one of 2 ways below to do it.
The first solution: You can use this link using obserable pattern to communication 2 fragments.
The second solution: you can use EventBus lib for communication, it 's very simple


text:
Q: Count elements in a Dynamic database in Prolog Well, I have something like this:
 :- dynamic boxes/2.
 boxes([],0).
 boxes([2,3,5],5).
 boxes([1,4,6],2).

And within my process I use assert and retract based on my needs, however at the end of the whole process I need to know how many boxes I have, how can I achieve my goal?
I will really appreciate any help, I am so close to finish it up.

A: There may be other ways to do this, but one simple way would be as follows:
count_boxes(NumberOfBoxes) :-
    findall(B, boxes(B, _), L), length(L, NumberOfBoxes).

To include mat's excellent comment, if all you want in the findall is the length of the resulting list, you can reduce memory consumption in the findall call as follows:
findall(t, boxes(_, _), L)

Rather than enumerating a list of the boxes, B, it creates a list, of the same length, of atoms, t.


text:
Q: Existence of a maximum matching such that v is un-saturated Ture or False: for every graph G without a perfect matching and every vertex v of G there is a maximum matching M of G such that v is M-unsaturated.

A: Consider $P_3$, the path graph on 3 nodes. It does not have a perfect matching but two maximal matchings (by picking either of the two edges present in $P_3$) neither of which leave the center vertex unsaturated.


text:
Q: Most efficient way to change a string field value to its substring I have a collection filled with documents that look like this:
{
    data: 11,
    version: "0.0.32"
}

and some have a test suffix to version:
{
    data: 55,
    version: "0.0.42-test"
}

The version field has different values but it always conforms to the pattern: 0.0.XXX. I would like to update all the documents to look like this:
{
    data: 11,
    version: 32
}

and the suffixed version (for test documents - version should be negative):
{
    data: 55,
    version: -42
}

The collection with these documents is used by our critical system, that needs to be turned off while updating the data - so I want the update/change to be as fast as possible. There are about 66_000_000 documents in this collection, and it's about 100GB in size.
Which type of mongodb operation would be the most efficient one?

A: The most efficient way to do this is in the upcoming release of MongoDB as of this writing using the $split operator to split our string as shown here then assign the last element in the array to a variable using the $let variable operator and the $arrayElemAt operators.
Next, we use the $switch operator to perform a logical condition processing or case statement against that variable.
The condition here is $gt which returns true if the value contains "test", and in which case in the in expression we split that string and simply return the $concatenated value of the first element in the newly computed array and the -. If the condition evaluates to false, we just return the variable.
Of course in our case statement, we use the $indexOfCP which returns -1 if there were no occurrences of "test".
let cursor = db.collection.aggregate(
    [
        { "$project": {
            "data": 1,
            "version": {
                "$let": {
                    "vars": {
                        "v": {
                            "$arrayElemAt": [
                                { "$split": [ "$version", "." ] },
                                -1
                            ]
                        }
                    },
                    "in": {
                        "$switch": {
                            "branches": [
                                {
                                    "case": {
                                        "$gt": [
                                            { "$indexOfCP": [ "$$v", "test" ] },
                                            -1
                                        ]
                                    },
                                    "then": {
                                        "$concat": [
                                            "-",
                                            "",
                                            { "$arrayElemAt": [
                                                { "$split": [ "$$v", "-" ] },
                                                0
                                            ]}
                                        ]
                                    }
                                }
                            ],
                            "default": "$$v"
                        }
                    }
                }
            }
        }}
    ]
)

The aggregation query produces something like this:
{ "_id" : ObjectId("57a98773cbbd42a2156260d8"), "data" : 11, "version" : "32" }
{ "_id" : ObjectId("57a98773cbbd42a2156260d9"), "data" : 55, "version" : "-42" }

As you can see, the "version" field data are string. If the data type for that field does not matter then, you can simply use the $out aggregation pipeline stage operator to write the result into a new collection or replace your collection.
{ "out": "collection" }

If you need to convert your data to floating point number then, the only way to do this, simply because MongoDB doesn't not provides a way to do type conversion out of the box except for integer to string, is to iterate the aggregation Cursor object and convert your value using parseFloat or Number then update your documents using the $set operator and the bulkWrite() method for maximum efficiency.
let requests = [];
cursor.forEach(doc => {
    requests.push({
        "updateOne": {
            "filter": { "_id": doc._id },
            "update": {
                "$set": {
                    "data": doc.data,
                    "version": parseFloat(doc.version)
                },
                "$unset": { "person": " " }
            }
        }
    });
    if ( requests.length === 1000 ) {
        // Execute per 1000 ops and re-init
        db.collection.bulkWrite(requests);
        requests = [];
    }}
);

 // Clean up queues
if(requests.length > 0) {
    db.coll.bulkWrite(requests);
}

While the aggregation query will perfectly work in MongoDB 3.4 or newer our best bet from MongoDB 3.2 backwards is mapReduce with the bulkWrite() method.
var results = db.collection.mapReduce(
    function() {
        var v = this.version.split(".")[2];
        emit(this._id, v.indexOf("-") > -1 ? "-"+v.replace(/\D+/g, '') : v)
    },
    function(key, value) {},
    { "out": { "inline": 1 } }
)["results"];

results looks like this:
[
    {
        "_id" : ObjectId("57a98773cbbd42a2156260d8"),
        "value" : "32"
    },
    {
        "_id" : ObjectId("57a98773cbbd42a2156260d9"),
        "value" : "-42"
    }
]

From here you use the previous .forEach loop to update your documents.

From MongoDB 2.6 to 3.0 you will need to use the now deprecated Bulk() API and it associated method as show in my answer here.


text:
Q: Fragment in kotlin i'm stuck in my application because i have to do a fragment with the navigation drawer in kotlin.. can anyone help? I have search a lot of things in web but i didn't find anything yet...
Down here is two items that i have do in main activity and i want  that is present in the fragment too.
override fun onNavigationItemSelected(item: MenuItem): Boolean {
    // Handle navigation view item clicks here.
    when (item.itemId) {
        R.id.home -> {

        }
        R.id.subjects -> {
            val intent = Intent(this, SubjectsActivity::class.java)
            startActivity(intent)
        }
    }

    drawer_layout.closeDrawer(GravityCompat.START)
    return true
}

A: You can use this to replace your frame with HomeFragment()
mainDisplayFrame should be replace by your FrameID
var fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.mainDisplayFrame,HomeFragment()).commit()
mDrawerLayout!!.closeDrawers()

A: You can download the source link from here(Navigation Drawer In Android Kotlin)
MainActivity.kt:
class MainActivity : AppCompatActivity(), View.OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        init()
    }

    private fun init() {
        tv_home.setText("Home Tab")
        tv_title.setText("Home")
        ll_about.setOnClickListener(this)
        ll_home.setOnClickListener(this)
        ll_bookmark.setOnClickListener(this)
        ll_help.setOnClickListener(this)
        rl_menu.setOnClickListener(this)
        rl_header.setOnClickListener(this)

        tv_link.setLinkTextColor(Color.parseColor("#000000"));
        Linkify.addLinks(tv_link, Linkify.ALL)

    }

    override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {

            R.id.ll_home -> {
                drawer_layout.closeDrawer(GravityCompat.START)
                tv_home.setText("Home Tab")
                tv_title.setText("Home")

            }
            R.id.ll_about -> {

                val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("http://deepshikhapuri.blogspot.in/"))
                startActivity(browserIntent)

            }

            R.id.ll_help -> {
                drawer_layout.closeDrawer(GravityCompat.START)
                tv_home.setText("Help Tab")
                tv_title.setText("Help")

            }

            R.id.ll_bookmark -> {
                drawer_layout.closeDrawer(GravityCompat.START)
                tv_home.setText("Bookmark Tab")
                tv_title.setText("Bookmark")

            }

            R.id.rl_header -> {
            }

            R.id.rl_menu -> {
                if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
                    drawer_layout.closeDrawer(GravityCompat.START)
                } else {
                    drawer_layout.openDrawer(GravityCompat.START)
                }
            }

        }

    }

Thanks!

A: Is something like this? @NongthonbamTonthoi
class NavViewFragment : AppCompatActivity(),
NavigationView.OnNavigationItemSelectedListener {

fun AppCompatActivity.addFragment(fragment: Fragment, frameId: Int){
    supportFragmentManager.inTransaction { add(frameId, fragment) }
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_nav_view_fragment)
    setSupportActionBar(toolbar)

    nav_view.setNavigationItemSelectedListener(this)
}

override fun onBackPressed() {
    if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
        drawer_layout.closeDrawer(GravityCompat.START)
    } else {
        super.onBackPressed()
    }
}

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.nav_view, menu)
    return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    when (item.itemId) {
        R.id.action_settings -> return true
        else -> return super.onOptionsItemSelected(item)
    }
}

override fun onNavigationItemSelected(item: MenuItem): Boolean {
    // Handle navigation view item clicks here.
    when (item.itemId) {
        R.id.home -> {

        }
        R.id.subjects -> {
            val intent = Intent(this, SubjectsActivity::class.java)
            startActivity(intent)
        }

        }
    drawer_layout.closeDrawer(GravityCompat.START)
    return true
    }
inline fun FragmentManager.inTransaction(func: FragmentTransaction.() -> Unit) {
    val fragmentTransaction = beginTransaction()
    fragmentTransaction.func()
    fragmentTransaction.commit()
}

}


text:
Q: Node - Wait request response within cycle For Really, I've tried all ways, but I fail to find the solution.
As no English, and I'm using the google translator, I will explain the same thing several times in a row.
1º Try the For loop will wait until everything is finished within
2º I try to know that city is doing OK on an external web request. And like many cities, I need to break the cycle once I check the first city ok.
3º I need to go a json and execute an action while running and wait till it finishes to follow. Then get out of the cycle at any time.

I've been testing with several codes, but present here for better understanding.
---------------------------------------------------------------------

var city =
[
    {'city':'madrid'},
    {'city':'barcelona'},
    {'city':'valencia'},
    {'city':'malaga'}
];

var vBreak = 0;

for (i in city){

    request('example.there-city.com/' + city[i].city ,function (error, response, read) {
        if (read == 'OK') { vBreak = 1}
    });

if (vBreak == 1){ break;}
}

var city =
[
    {'city':'madrid'},
    {'city':'barcelona'},
    {'city':'valencia'},
    {'city':'malaga'}
];

var vBreak = 0;

for (i in city){

    (function(i) {
        request('example.there-city.com/' + city[i].ciudad ,function (error, response, read) {
            if (read == 'OK') { vBreak = 1}
        });
    })(i);

if (vBreak == 1){ break;}
}

Thank you

A: Use async.eachSeries (as jgillich said) to perform each request in order like this:
async.eachSeries(city, function (item, cb) {
  if (vbreak !== 1) {
    request('example.there-city.com/' + item.city ,function (error, response, read) {
        if (read == 'OK') { vBreak = 1}
        cb();
    });
  } else {
    cb() // Skip
  }
}, function () { // we're finished
})

You'll need to add error handling probably.

A: Try to use a recursive function. Just increment the counter, after the response came ...


text:
Q: Fetch API not posting to Node.js server (body is empty) I'm trying to use fetch() to post to another Node.js server I am running. When I take out the headers, my console prints '{}'. When I keep them in, nothing is printed when I call the function.
I have tried using curl and I receive '{}' as well.
//Server.js (what I am trying to POST to)
var express = require('express');
var app = express();
var PORT = 4000;
app.use(express.json());

app.post('/', function (req, res) {
    console.log(req.body);

})
app.listen(PORT, function () {
    console.log('server running on port: ' + PORT);
})

//Post function (this is inside a separate React component which will perform the POST)
postContents() {
    var data = { username: 'example' };

    fetch('http://localhost:4000/', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
      .then(response => response.json())
      .catch(error => console.error('Error:', error))
      .then(response => console.log('Success:', JSON.stringify(response)));
  }

A: You have to use the body-parser as a middleware for your express server.
const express = require('express');
const app = express();
const PORT = 4000;
const bodyParser = require('body-parser');
app.use(bodyParser.json());

A: *

*without headers and with headers the result is different

*the URL is fully qualified with host and port

These two points suggest you are making a cross origin request.
The solution is to have the server

*

*accept and handle OPTIONS requests when required

*issue CORS headers in the response


text:
Q: Spring Data Cassandra codec not found for requested operation set <-> java.util.Set My entity has a field
@Column("authorizations")
@Builder.Default
private Map<String, Set<String>> authorizations = new HashMap<>();

When I query for that object via Spring Data repository I'm getting an exception

CodecNotFoundException: Codec not found for requested operation:
  [set <-> java.util.Set]

Writes work just fine though. I can't believe this is not supported out of the box.
Table definition
CREATE TABLE resource_authorization_rules(
  resource text,
  region text,
  authorizations map<text, frozen<set<text>>>,
  PRIMARY KEY (resource, region)
);

Probably something with type erasure. How to tackle this with least effort?

A: This is a limitation of the the Spring Data Casasndra. There is a JIRA for improving support of frozen collections.  And it looks like that it could be worked around with custom row mapper as described here.
P.S. The DataStax Java Driver has corresponding annotations in their object mapper.


text:
Q: Given some information of $\limsup$ and $\liminf$ of $f$, show that $f(x)+x^{\beta}\longrightarrow\infty$ if and only if $\beta>\frac{1}{2}$. The reason of this post was another post I saw this afternoon. However, I cannot find the post anymore, so I am not able to provide the link.
The OP was about this: he knows about $$\limsup_{x\rightarrow\infty}\dfrac{f(x)}{\sqrt{2x\log\log x}}=1\ \text{and}\ \liminf_{x\rightarrow\infty}\dfrac{f(x)}{\sqrt{2x\log\log x}}=-1.$$
Then, he wants to show $f(x)+x^{\alpha}\longrightarrow\infty$ if and only if $\alpha>\frac{1}{2}$.
There was no answer but only some comments in that post. Among comments, one suggested using the fact that $$\lim_{x\rightarrow\infty}\dfrac{\log x}{x^{r}}=\infty,\ \text{for all}\ r>0,$$ so that $$\lim_{x\rightarrow\infty}(x^{r}-\sqrt{2\log\log x})=\infty\ \text{for all}\ r>0.$$
Then, using the condition of $\liminf$, writing out as $$f(x)+x^{\alpha}>x^{\alpha}+(-1-\epsilon)\sqrt{2x\log\log x},$$ it is fairly easy to prove the direction $(\Leftarrow)$.(Factor out $x^{1/2}$ and replace $r:=\alpha-\frac{1}{2}$.
However, I could not figure out $(\Rightarrow)$. Even though $r\leq 0$ implies $$\lim_{x\rightarrow\infty}(x^{r}-\sqrt{2\log\log x})=-\infty,$$ we cannot use it, since if we apply the similar argument, we would arrive at $$\liminf f(x)+x^{\alpha}>-\infty,$$ which is not useful at all.
Then, I tried to use the condition on $\limsup$, but that only gives $\limsup f(x)+x^{\alpha}<\infty$, which is not useful either..
What should I do? thank you!

A: Let us first consider the case $\alpha=1/2$.
Since $$\liminf_{x \to \infty} \frac{f(x)}{\sqrt{2x \log \log x}} = - 1,$$
there exists a sequence $(x_n)_{n \in \mathbb{N}}$ with $x_n \to \infty$ as $n \to \infty$ and
$$ \frac{f(x_n)}{\sqrt{2x_n\log \log x_n}} \leq -\frac{1}{2} .$$
Thus,
\begin{align*} f(x_n) + \sqrt{x_n} &= \sqrt{x_n} \left( \frac{f(x_n)}{\sqrt{x_n}}+1 \right) \\ &\leq \sqrt{x_n} \left( - \frac{1}{2} \sqrt{2 \log \log x_n} + 1 \right). \end{align*}
Since $\sqrt{x_n} \to \infty$ as $n \to \infty$ and
$$\lim_{n \to \infty} \left( - \frac{1}{2} \sqrt{2 \log \log x_n} + 1 \right) = - \infty,$$
it follows that $$\lim_{n \to \infty} f(x_n) + \sqrt{x_n} = - \infty.$$ (Note: If $(a_n)_n$, $(b_n)_n$ are real-valued sequences such that $a_n \to \infty$ and $b_n \to - \infty$, then $a_n b_n \to -\infty$.) Hence, $$\liminf_{x \to \infty} f(x) + \sqrt{x} = - \infty.$$
If $\alpha < 1/2$, then $x^{\alpha} < \sqrt{x}$ for $x \geq 1$, and hence,
$$\liminf_{x \to \infty} f(x) + x^{\alpha} \leq \liminf_{x \to \infty} f(x) + \sqrt{x} = -\infty.$$