text:
Q: Well I am having issue with publish button in my django site .It is not performing its' function I am using django 3.0.3,python 3.8.5 and Vs code as an IDE. I am clicking on the publish button but it is not working.
---Models.py---
 def publish(self):
        self.published_data = timezone.now()
        self.save()

---views.py---
@login_required
def post_publish(request,pk):
    post = get_object_or_404(Post,pk=pk)
    post.publish()
    return redirect('post_detail',pk=pk)

---urls.py---
 path('post/<int:pk>/publish/',views.post_publish,name ='post_publish'),

--post_detail.html(template)--
 Publish

--post_detail.html(Complete template)--
  {% extends "blog/base.html" %}
{% block content %}

{{post.title}}

{% if post.published_date %}

        {{ post.published_date}}

{% else %}
Publish
{% endif %}

{{ post.text|safe|linebreaksbr}}

{% if user.is_authenticated %}

  <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-pencil" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
  <path fill-rule="evenodd" d="M11.293 1.293a1 1 0 0 1 1.414 0l2 2a1 1 0 0 1 0 1.414l-9 9a1 1 0 0 1-.39.242l-3 1a1 1 0 0 1-1.266-1.265l1-3a1 1 0 0 1 .242-.391l9-9zM12 2l2 2-9 9-3 1 1-3 9-9z"/>
  <path fill-rule="evenodd" d="M12.146 6.354l-2.5-2.5.708-.708 2.5 2.5-.707.708zM3 10v.5a.5.5 0 0 0 .5.5H4v.5a.5.5 0 0 0 .5.5H5v.5a.5.5 0 0 0 .5.5H6v-1.5a.5.5 0 0 0-.5-.5H5v-.5a.5.5 0 0 0-.5-.5H3z"/>
</svg>

  <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-trash" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
  <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"/>
  <path fill-rule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4L4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"/>
</svg>

{% endif %}

Add Comment

    {% for comment in post.comments.all %}

    {% if user.is_authenticated or comment.apporved_comment %}
    {{ comment.created_date }}
    {% if not comment.approved_comment %}

  <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-x" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
  <path fill-rule="evenodd" d="M11.854 4.146a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708-.708l7-7a.5.5 0 0 1 .708 0z"/>
  <path fill-rule="evenodd" d="M4.146 4.146a.5.5 0 0 0 0 .708l7 7a.5.5 0 0 0 .708-.708l-7-7a.5.5 0 0 0-.708 0z"/>
</svg>

  <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-check2" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
  <path fill-rule="evenodd" d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0z"/>
</svg>

{% endif %}

 {{ comment.text|safe|linebreaks}}

 Posted By:{{comment.author}}

    {% endif %}
    {% empty %}

No Comments

    {% endfor %}

{% endblock  %}

I am new and learning django framework and It feels so bad when I stuck on such things where I could not understand what to do but I hope you guys can able to help me.
Any help will be appreciated
Thank you

A: I don't think it would work that way, what i think something like this work would work:
urls.py
path('post/publish',views.post_publish,name ='post_publish'),

forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
    class Meta:
        model = POST
        fields = ['title', 'text', ...] # Your post model fields

views.py
from .forms import PostForm
@login_required
def post_publish(request):
    if request.Method=='POST':
        post_form = PostForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/post_detail/'+str(pk))
    post_form = PostForm()
    return render(response, "publish.html", {"form": post_form})

template publish.html (of course can add other html to present however you like)
<form method="post">
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value="Publish">
</form>

PostForm will automatically convert you Post model into a form, when you 'GET' publish.html, this form will be and when you click on publish button it will submit form data on same url by doing a POST. inside our view when it's POST when parse that request into a filled form then we call is_valid to clean data and make sure that all validation are satisfied. If they are then we call save function that will create the post and redirect to post detail page.
When implementing you still might run into some import errors or other, but this is to give you an idea on how to do this. let me know as you implement this and if you run into some errors.


text:
Q: What Android APIs do I need to perform a USB control transfer (setup, data, status) on a HID device? I am developing the driver for a USB HID controller linked to my Android device using USB-host.
All vendor-specific operations enabling me to poll the status of the controller, or to set different flags, are defined as vendor-specific control commands which contain a setup stage and a data stage (device -> controller). Depending on the different commands, the controller may send back a status stage message.
I understood that the method UsbDeviceConnection.controlTransfer() shall be used to send the setup and data stages. What I don't understand is what method/API I should use to read the status sent back by the controller.
Does someone know?
Thank you very much!

A: According to the well-known open source project https://github.com/mik3y/usb-serial-for-android, that method returns -1 if there's something wrong.

    int result = mConnection.controlTransfer(FTDI_DEVICE_OUT_REQTYPE, SIO_RESET_REQUEST, SIO_RESET_SIO, 0 /* index */, null, 0, USB_WRITE_TIMEOUT_MILLIS);
    if (result != 0) {
        throw new IOException("Reset failed: result=" + result);
    }

(Code extracted from FtdiSerialDriver.java)
I know it, because that's what is happening to me !!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disable iPhone notification when message displayed on Mac I have Messages on my MacBook connected to my iPhone, so when my phone gets an SMS message it's displayed on the Mac. But the iPhone also dings and displays a notification of the message.
What I'd like is that the iPhone doesn't do a notification if I'm using the Mac. The best criteria would be that the phone should do a notification if I'm away from the Mac or the Mac is sleeping or in the screensaver, but if I'm near the Mac and it's active, the notifications should just go to the Mac.
Is there a way to set this up?


text:
Q: Раскрывающееся подменю. Автоматическое закрытие раскрытых пунктов, при открытии новых Есть меню раскрывающееся:

$(".nav-item-toggle > a").on('click', function(e) {
  e.preventDefault();
  if ($(this).hasClass("active")) {
    $(this).next().slideUp("easeOutExpo");
    $(this).removeClass("active");
  } else {
    $(this).next(".nav-item-submenu");
    $(this).addClass("active");
    $(this).next().slideDown("easeOutExpo");
  }

});
.nav-item-submenu {
  display: none;
}

  Ссылка

Ссылка

Ссылка

Ссылка

  Ссылка

Ссылка

Ссылка

Ссылка

  Ссылка

Ссылка

Ссылка

Ссылка

При клике меню раскрывается, при повторном клике закрывается. Если оставить открытым одно подменю и раскрыть другое, то первое меню остается раскрытым. А хотелось бы, чтобы при раскрытии следующего подменю, предыдущие (ранее открытые) закрывались. Скилла мало, как сделать, подскажите люди добрые?

A: Перед раскрытие подменю (на которое кликнули) просто скрывайте все остальные пункты:

$(".nav-item-toggle > a").on('click', function(e) {
  e.preventDefault();
  if ($(this).hasClass("active")) {
    $(this).next().slideUp("easeOutExpo");
    $(this).removeClass("active");
  } else {
    $(".nav-item-toggle > a").removeClass('active');
    $('.nav-item-submenu').slideUp("easeOutExpo");
    $(this).next(".nav-item-submenu");
    $(this).addClass("active");
    $(this).next().slideDown("easeOutExpo");
  }
});
.nav-item-submenu {
  display: none;
}

  Ссылка

Ссылка

Ссылка

Ссылка

  Ссылка

Ссылка

Ссылка

Ссылка

  Ссылка

Ссылка

Ссылка

Ссылка


text:
Q: How to convert a datetime object between CEST and UTC timezones I don't want to use the pytz library as the project I am working on requires paperwork to introduce dependencies. If I can achieve this without a third party library I'll be happier.
I'm having trouble converting a date between CET and UTC when the date is in daylight savings. It's an hour different to what I expect:
>>> print from_cet_to_utc(year=2017, month=7, day=24, hour=10, minute=30)
2017-07-24T09:30Z

2017-07-24T08:30Z  # expected

CET is an hour ahead of UTC and in summertime is 2 hours ahead. So I would expect 10:30 in central Europe in midsummer to actually to 8:30 UTC.
The function is:
from datetime import datetime, tzinfo, timedelta

def from_cet_to_utc(year, month, day, hour, minute):
    cet = datetime(year, month, day, hour, minute, tzinfo=CET())
    utc = cet.astimezone(tz=UTC())
    return '{:%Y-%m-%d:T%H:%MZ}'.format(utc)

I use two timezone info objects:
class CET(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=1)

    def dst(self, dt):
        return timedelta(hours=2)

class UTC(tzinfo):
    def utcoffset(self, dt):
        return timedelta(0)

    def dst(self, dt):
        return timedelta(0)

A: Just complementing @Sergey's answer.
To know when you should apply DST or not, you should get the historical data of the date/times when DST starts and ends, and check if it must be applied or not to the specified datetime. You can get those from IANA database or consult in many online sources, such as timeanddate website.
Another detail is that CET is an ambiguous name, because it's used by more than one timezone. Real timezones names use the ones defined by IANA database (always in the format Region/City, like Europe/Paris or Europe/Berlin).

Gaps and Overlaps
I'm going to use Europe/Berlin timezone as an example. In this year (2017), DST in Berlin started in March 26th: at 2 AM, clocks shifted 1 hour forward to 3 AM, and the offset changed from +01:00 to +02:00.
You can also think that clocks jumped directly from 1:59 AM to 3 AM, which means that all the local times between 2 AM and 2:59 AM didn't exist in that day, at that timezone. That's called a gap, and you should check for this situation (one common approach is to adjust 2 AM to the next valid hour - in this case, 3 AM in DST).
In the same timezone, in 2017, DST will end in October 29th: at 3 AM, the clocks will shift back 1 hour to 2 AM, and the offset will change from +02:00 to +01:00.
This means that all the local times between 2 AM and 2:59 AM will exist twice: once in DST (+02:00) and once in non-DST (+01:00). That's called an overlap, and when creating a datetime that falls in this case, you must decide which one you'll choose to create (should it be 2 AM in DST or non-DST offset? you decide!).

PS: Each european country that uses CET nowadays adopted it in a different year, so if you're dealing with old dates you must consider that too.
Another detail is that DST is defined by governments, and there's no guarantee that the rules will be like this forever, and you'll have to update the rules accordingly - another advantage of using pytz, as its updates are generated from IANA releases and published in PyPI (thanks @Matt Johnson for pointing this info).
Are you sure the paperwork is worse than coding these rules by hand? Just check how to read IANA tz files and perhaps you'll change your mind.

A: You should read the tzinfo manual carefully, as it is explained there.
First, dst() should usually return a timedelta(0) or timedelta(hours=1), never 2 or more hours, and rarely something in between (e.g. 30 mins). This is only a dst shift relative to the normal TZ offset, not the full TZ offset in the dst mode.
Second, utcoffset() must include dst correction already. The dst() method on its own is also used in some cases described in the manual (e.g. for detection if dst is in effect or not), but it is NOT automatically applied to the TZ offset unless you do so.
Your code should look like this:
from datetime import datetime, tzinfo, timedelta

class CET(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=1) + self.dst(dt)

    def dst(self, dt):
        dston = datetime(year=dt.year, month=3, day=20)
        dstoff = datetime(year=dt.year, month=10, day=20)
        if dston <= dt.replace(tzinfo=None) < dstoff:
            return timedelta(hours=1)
        else:
            return timedelta(0)

class UTC(tzinfo):
    def utcoffset(self, dt):
        return timedelta(0)

    def dst(self, dt):
        return timedelta(0)

def from_cet_to_utc(year, month, day, hour, minute):
    cet = datetime(year, month, day, hour, minute, tzinfo=CET())
    utc = cet.astimezone(tz=UTC())
    return '{:%Y-%m-%d:T%H:%MZ}'.format(utc)

print from_cet_to_utc(year=2017, month=7, day=24, hour=10, minute=30)
# 2017-07-24:T08:30Z

Here, I bravely assume that the DST is in effect 20.03.YYYY - 19.10.YYYY inclusive, where YYYY is the year of the date/datetime object.
Usually this logic of the on & off dates is much more complicated: the shifts happen on the Sunday nights only, sometimes on the last Sunday of the month, and vary between the years, sometimes between the sovereignty of the states (with borderlines also changing over the years), and with the daylight saving laws and timezoning changing every few years (hello, Russia).


text:
Q: Insert Multiple Records faster way I am using SQL Server 2008. My database has two tables.
Member

*

*MemberId

*RegCode

*BrokerCode

*Name

TestInstallment

*

*RegCode

*Amount

*Date

*InstallmentNo

In both tables there are many columns but I display here some of columns. TestInstallment is the table in which I import data from Excel and do some calculation. Member table contains rows with unique RegCode and TestInstallment contains multiple rows with same RegCode. For example, in member table there is only one row with RegCode 'A105' so TestInstallment contains approx 30 rows with RegCode 'A105'.
My final table is Installment

*

*InstallmentId

*MemberId

*Amount

*Date

*InstallmentNo

Now I want to insert rows of TestInstallment into Installment with reference of MemberId. Currently I am doing it using a cursor but it takes much time.
Currently in my database Member table has approx 47000 rows and TestInstallment has approx 700000 rows.
So how can I do this faster way? Thanks.

A: I assumed installmentid is identity field.
insert into installment
select m.memberid, t.amount, t.date, t.installmentno,
from member m inner join testinstallment t on m.regcode = t.regcode


text:
Q: how to fix 'Access violation reading location' in this code run this code i got some error like this
' Exception thrown at 0x778D7FCB (ntdll.dll) in Project1.exe: 0xC0000005: Access violation reading location 0x00000014.'
This error occurs in this line
~UnivStudnet() {
delete[]major; // error
    }

#include <iostream>
#include <cstring>
using namespace std;

class Person {
private:
    char * name;
public:
    Person(const char * myname) {
        name = new char[strlen(myname) + 1];
        strcpy_s(name, strlen(name), myname);
    }
    ~Person() {
        delete[]name;
    }

    void WhatYourName() const {
        cout << "My name is " << name << endl;
    }
};

class UnivStudnet : public Person {
private:
    char * major;
public:
    UnivStudnet(const char * myname, const char * const mymajor) :Person(myname) {
        major = new char[strlen(mymajor) + 1];
        strcpy_s(major, strlen(major), mymajor);
    }
    ~UnivStudnet() {
        delete[]major;
    }

    void WhoAreYou() const {
        WhatYourName();
        cout << "My major is " << major << endl;
    }
};

int main(void) {

    UnivStudnet st1("kim", "Mathenatics");
    st1.WhoAreYou();
    UnivStudnet st2("hong", "Physiscs");
    st2.WhoAreYou();
    return 0;
}

How do I fix this error?

A: There are bugs on the two strcpy_s lines.
strcpy_s(name, strlen(name), myname);

should be
strcpy_s(name, strlen(myname)+1, myname);

and likewise
strcpy_s(major, strlen(major), mymajor);

should be
strcpy_s(major, strlen(mymajor)+1, mymajor);

Calling strlen on the newly-allocated char arrays name and major which have indeterminate values, causes undefined behavior which is the cause of your crash.

A: You could go more C++-way:
You need to declare:
virtual ~Person()

destructor in base class and then:
class UnivStudnet : public Person {
private:
    std::string major;
public:
    UnivStudnet(const char * myname, const char * const mymajor) :Person(myname), major(mymajor) {
    }
    virtual ~UnivStudnet() {
    }
...

This way you will achieve what you need and do not think about memory allocation/deallocation. Remember to #include <string> header.
Same way do it in Person class.

A: Your strcpy_s usage is suspect.
    major = new char[strlen(mymajor) + 1];
    strcpy_s(major, strlen(major), mymajor);

The second parameter to strcpy_s is the allocated size of the buffer specified by the first parameter.  (And I just now realized - based on another answer that strlen(major) is undefined before you copy to it!
You are allocating the buffer to be large enough to hold the string, but the subsequent call to strcpy_s is indicating that major isn't big enough to hold the entire string including the null char.
Better:
    size_t len = strlen(mymajor) + 1;
    major = new char[len];
    strcpy_s(major, len, mymajor);

Repeat the above pattern for the base class name parameter as well.


text:
Q: Android: Wrong icon on header, when app is running in backround On 99 % of devices app icon on header taskbar is showing without problem:
image
but on Sony Xperia Z3, Lollipop, it appears as white square:
image
heres application section from my manifest doc:
<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="intent.to.front" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="hidden" />

        <activity
            android:name=".FromActivity"
            android:label="@string/title_activity_from" />
        <activity
            android:name=".ToActivity"
            android:label="@string/title_activity_to" />
        <activity
            android:name=".RateActivity"
            android:label="@string/title_activity_rate" />
        <activity
            android:name=".VerificationActivity"
            android:label="@string/title_activity_verification" />
        <activity
            android:name=".CrashActivity"
            android:label="@string/title_activity_crash" />
        <activity
            android:name=".OrderProgressActivity"
            android:label="@string/title_activity_order_progress"
            android:launchMode="singleTop">
            <intent-filter>
                <action android:name="intent.to.front" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

So if you know answer, please help and why is it only happening to xperia device?

A: Lollipop devices add there own square to notification icons. You need to make sure that your image has an alpha background so when a color fill is applied to it, you can still see the image.
If you still want it to appear as it does on older devices you can do some checking code to see what version of Android they are running and supply a different icon.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {

}

A: To make Android-notification icon easily to all versions.
Android Assets-Notification Icon Generator
Icon generators allow you to quickly and easily generate icons from existing source images, clipart, or text.
Happy Coding :)


text:
Q: j2me multiple cookies how to read http multiple responce headers with the same key name like set-cookie from j2me httpconnection? (looping through headers with getHeaderField(int i) also did not solve the problem). because of this problam i tried to rewite my own http client on a socket connection. but jsr-185 does not allow sockets to port 80, 8080 and 443. to use them application should be signed.

A: Looping through headers with getHeaderField(int i) works for me in WTK emulator. IMHO, some devices can have this bug non-fixed: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4634244

A: The problem can be solved like this. In the code below we are extracting "JSESSION" and "SOME_COOKIE", two cookies coming from a server that is using the same header "set-cookie".
String sessionID = "";
String someCookie = "";
String headerKey = "";
int indexField = 0;
while((headerKey = httpConnection.getHeaderFieldKey(indexField)) != null){
    String headerValue = httpConnection.getHeaderField(indexField);
    if(headerKey.equals("set-cookie")){
        //do something with the string
        if(headerValue.indexOf("JSESSION")>=0){//if "JSESSION" is present in the String
            sessionID = headerValue.substring(0, headerValue.indexOf(";"));
        }
        if(headerValue.indexOf("SOME_COOKIE")>=0){//if "SOME_COOKIE" is present in the String
            someCookie = headerValue.substring(0, headerValue.indexOf(";"));
        }
    }
    indexField++;
}


text:
Q: How do I get an Express JS substr? I'm getting a return error when I try to substr a variable like:
TypeError: Cannot read property 'substr' of undefined
This is my code:
app.get('/reports/FUHAUHS9029019.CSV', function(req, res, next){
    var filepath = req.params.name;
    var ffilepath = filepath.substr(0,12);
    var filename = req.params.name;
    var ffilename = filename.substr(-18);

    console.log(ffilepath);

    res.send('filename: ' + req.params.filepath.substr(-18));
    res.download(filename, edifilepath);
});

How can i get the substring coming from my file? and trying to apply dynamic router to this router but i'm also not getting anything out of it besides the substr error.
Thank you so much :D

A: you need to set the parameter:
app.get('/reports/:name', function(req, res, next){

var filepath = req.params.name;
var ffilepath = filepath.substr(0,12);
var filename = req.params.name;
var ffilename = filename.substr(-18);

console.log(ffilepath);

res.send('filename: ' + ffilename);
//res.download(filename, edifilepath); // also check this line
});


text:
Q: How to rotation DirectX11 FPS Game Camera? http://www.youtube.com/watch?v=M8A1H7xWJcI&feature=youtu.be
watch that video.
My problem is left, right rotation is working well but up, down rotation is not working properly (see video). I guess axis problem
That`s my source
GunObject Source
// Scale
XMMATRIX matScale = XMMatrixIdentity();
    matScale = XMMatrixScaling(m_Scaling.x, m_Scaling.y, m_Scaling.z);

    // rotation
    XMMATRIX matRoation = XMMatrixIdentity();
    matRoation *= XMMatrixRotationNormal(XMLoadFloat3(&XMFLOAT3(0.0f, 1.0f, 0.0f)), m_fRotAngleY);
    matRoation *= XMMatrixRotationNormal(XMLoadFloat3(&vRight), m_fRotAngleX);

    // Translate
    XMMATRIX matTranslate = XMMatrixIdentity();
    matTranslate = XMMatrixTranslation(m_Pos.x, m_Pos.y, m_Pos.z);

    XMMATRIX matWorld = XMMatrixIdentity();
    matWorld = matScale * matRoation * matTranslate;

    XMStoreFloat4x4(&m_f4x4World, matWorld);
    XMStoreFloat4x4(&m_f4x4ViewProj, matViewProj);
    XMStoreFloat4x4(&m_f4x4WorldViewProj, matWorld * matViewProj);

FPSCamera View Matrix Source
XMVECTOR vRight    = XMLoadFloat3(&m_vRight);
    XMVECTOR vUp       = XMLoadFloat3(&m_vUp);
    XMVECTOR vLook     = XMLoadFloat3(&m_vLook);
    XMVECTOR vPosition = XMLoadFloat3(&m_vPosition);

    // 룩벡터와 업벡터, 횡벡터를 정규직교화 한다.
    vLook = XMVector3Normalize(vLook);
    vUp   = XMVector3Normalize( XMVector3Cross(vLook, vRight) );

    // 룩벡터와 업벡터는 이미 정규화과 되어 있으므로 횡벡터를 정규화 할 필요가 없다.
    vRight = XMVector3Cross(vUp, vLook);
    vRight = XMVector3Normalize(vRight);

    // 뷰행렬의 내용물을 설정한다.
    XMStoreFloat3(&m_vRight, vRight);
    XMStoreFloat3(&m_vUp, vUp);
    XMStoreFloat3(&m_vLook, vLook);

    m_f4x4View(0, 0) = m_vRight.x;
    m_f4x4View(1, 0) = m_vRight.y;
    m_f4x4View(2, 0) = m_vRight.z;
    m_f4x4View(3, 0) = -m_fOffsetX;
    //m_f4x4View(3, 0) = -XMVectorGetX(XMVector3Dot(vPosition, vRight));

    m_f4x4View(0, 1) = m_vUp.x;
    m_f4x4View(1, 1) = m_vUp.y;
    m_f4x4View(2, 1) = m_vUp.z;
    m_f4x4View(3, 1) = -XMVectorGetX(XMVector3Dot(vPosition, vUp));

    m_f4x4View(0, 2) = m_vLook.x;
    m_f4x4View(1, 2) = m_vLook.y;
    m_f4x4View(2, 2) = m_vLook.z;
    m_f4x4View(3, 2) = -m_fOffsetZ;

    m_f4x4View(0, 3) = 0.0f;
    m_f4x4View(1, 3) = 0.0f;
    m_f4x4View(2, 3) = 0.0f;
    m_f4x4View(3, 3) = 1.0f;

    m_vPosition.x -= m_fOffsetX;
    m_vPosition.z -= m_fOffsetZ;
    vPosition = XMLoadFloat3(&m_vPosition);

    XMFLOAT4X4 tempTranslateMatrix;
    XMStoreFloat4x4(&tempTranslateMatrix, XMMatrixIdentity());
    tempTranslateMatrix(3, 0) = -XMVectorGetX(XMVector3Dot(vPosition, vRight));
    tempTranslateMatrix(3, 1) = 0.0f;
    tempTranslateMatrix(3, 2) = -XMVectorGetX(XMVector3Dot(vPosition, vLook));;
    tempTranslateMatrix(3, 3) = 1.0f;

    XMMATRIX tempView = XMLoadFloat4x4(&m_f4x4View);
    tempView *= XMLoadFloat4x4(&tempTranslateMatrix);
    XMStoreFloat4x4(&m_f4x4View, tempView);


text:
Q: Passing Large String as arguments - unoptimized? I am receiving some very large strings as a response of Ajax request which are used to generate views on the front end.
I know if its an object then a reference to the object is passed as a argument. But what's the case with String? Is it bad for optimization to pass very large string as arguments?
fetchData(empId, date1, date2).done(function(response) {
      //here response is a very large string
      ...
      ..
      createView(response);
      refreshCumulatives(response);
      ...
      ..
  }).fail(function(jqXHR, textStatus, errorThrown) {

  });

A:
I know if its a object then a reference to the object is passed as a
  argument. But what's the case with String?

Even string will be passed as argument to that callback function in done. It's just data which you're passing to the callback function, it doesn't matter whether it's string or object.
What you're going to do with that response in your done callback will make the actual difference in terms of performance.

A: Everything is an object in JS, including Strings. Passing a string argument is no different as passing any other argument (i.e. approaching a 32 or 64-bit pointer).


text:
Q: Addition of arrays in a function #include <stdio.h>

Here is where the problems begins when i try to write the arrays within the function
 int suma(int a[i], int b[i], int i){

    return a[n] + b[n];

}

void main(void){

int i,n,num;

do{
      printf("Ingrese el tamaño de los vectores: ");
      scanf("%i",&n);
        if (n>50){
             printf("Ingrese el tamaño de los vectores: ");
             scanf("%i",&n);
             num==0;
        }

        else if (n<=50){

            num++;
        }

}while (num==0);

int vec1[n], vec2[n],vec3[n];

for (i=0;i<n;i++){

    printf("Introduce los valores para el primer vector: \n");
    scanf("%i",&vec1[i]);

}

for (i=0;i<n;i++){

    printf("Introduce los valores para el segundo vector: \n");
    scanf("%i",&vec2[i]);

}

    printf("La suma de los dos vectore es: \n");

    for (i=0;i<n;i++){

Here should be the vec3[i]=vec1[i]+vec2[i] but i need to do it with a function
    vec3[i]=suma(vec1[i],vec2[i]);

    printf("Posicion %d -->%i\n",i,vec3[i]);

}

}

A: Arrays do not have the assignment operator.
It seems what you need is the following.
void suma( int a1[], const int a2[], const int a3[], int n )
{
    for ( int i = 0; i < n; i++ )
    {
        a1[i] = a2[i] + a3[i];
    }
}

And call this function before the loop that outputs the result array like
suma( vec3, vec1, vec2, n );

and then
for (i=0;i<n;i++){
    printf("Posicion %d -->%i\n",i,vec3[i]);
}


text:
Q: Symfony Admin Generator in multi user setup (restricting records in LIST view) I am using SF 1.2.9 to build a website. I want to use the admin generator to provide admin functionality for the object models I have used (specifically LIST, edit and delete).
I have read the Symfony docs (Chapter 14), but unless, I am very much mistaken, all examples I have come accross so far, seems to be written for a single user environment only. Meaning that the list of records returned to the user is essentially, ALL the records in that table. In a multiuser environment, this is irresposible at best, and potentially, a security threat. It is a necessary requirement to restrict the list of records returned to a user to only those that they own (i.e. created).
Suppose I have a table with (YML) schema like this:
foobar_dongle:
    id:          ~
    title:       varchar(255)
    info:        longvarchar
    owner_id:   ~
    created_at:  ~

where owner id is a FK into a user table.
Assume I generate an admin module like this:
symfony propel:generate-admin backend FoobarDongle --module=dongle

Question:
How do I modify the list of records returned to a user in the LIST part of the code generated by the admin generator? As I mentioned above, currently, (i.e. out of the box), the admin generator presents the user (rather naively, I feel), with the ENTIRE set of records for the model being administered. I need to be able to restrict that list somehow, so that I can only return records owned by that user.
This is what I am trying to find out how to do.
I would be most grateful to anyone who can show me how I can restrict the list of records returned when using the admin generator for administration of an object model. Ideally, I would like to be able to specify a custom method that has all the custom 'filtering' logic - but so long as I can restrict the LIST of records a user can see (in admin), to only the records that he is the owner of, that is all I want to be able to do.

A: If you only want to restrict the returned objects in one or two modules, do this:
Go to the actions.class.php file of your module. There should be no methods by default and the class should inherit from autoModuleNameActions you. Insert the following method:
protected function buildQuery()
{
   $query = parent::buildQuery();
   // do what ever you like with the query like
   $query->andWhere('user_id = ?', $this->getUser()->getId());
   return $query;
}

But this becomes unhandy if you do it for more modules. In this case I would advice to create a new admin generator theme.
And if you want to make the query depending on some custom parameter in the admin generator config file, then you have to extend this file. But is not just done with adding a new parameter. You can read this article how to do this.
If you want to know more about the auto generated classes, have a look at this class: cache/[app]/[env]/modules/auto[ModuleName]/actions/actions.class.php.

Edit after comments:
I think you looked at the wrong class. Look here: cache/[app]/[env]/modules/auto[ModuleName]/actions/actions.class.php.
I set up a Propel project to check it and the method that is interesting for you is:
protected function buildCriteria()
{
  if (is_null($this->filters))
  {
    $this->filters = $this->configuration->getFilterForm($this->getFilters());
  }

  $criteria = $this->filters->buildCriteria($this->getFilters());

  $this->addSortCriteria($criteria);

  $event = $this->dispatcher->filter(new sfEvent($this, 'admin.build_criteria'), $criteria);
  $criteria = $event->getReturnValue();

  return $criteria;
}

I also posted the whole content of this class to pastebin. It is a lot, the function is in line 245. Even if you don't find this class, you should be able to override this method like this:
protected function buildCriteria()
{
  $criteria = parent::buildCriteria();
  // do something with it
  return $criteria;
}

I don't know about these criteria objects, so I can't help you with that but I hope the other things help you.

A: You should use sfGuardPlugin to provide your login/user functionality - it includes user groups and permissions that can be assigned to users and/or groups.
Using security.yml you can then configure which permissions/credentials are required to access individual actions. IE: you can allow everyone to access the list/update/delete actions, but only people with the create permission to access the create page.
The docs for sfGuardPlugin are worth reading:
http://www.symfony-project.org/plugins/sfGuardPlugin
Plus this section from the jobeet tutorial covers sfGuard and also use of security.yml and credentials:
http://www.symfony-project.org/jobeet/1_2/Propel/en/13
And to round off, this page from the book is relevant too:
http://www.symfony-project.org/reference/1_2/en/08-Security (although not sure it covers anything that isn't in the page i linked from jobeet)


text:
Q: How to test if strings contain alternating numbers of same symbol that are odd numbers that increase by 2? How to test if strings contain alternating numbers of same symbol that are odd numbers that increase by 2?
def test(fn,string):
    fn(string)

def alternating_colors(colors_string):
    print('The string "' + colors_string + '" is accepted') if colors_string.count('r') == ??? colors_string.count('b') == ??? else print('The string "' + colors_string + '" is not accepted')

# these tests should accept
test(alternating_colors, "r")
test(alternating_colors, "rbbb")
test(alternating_colors, "rbbbrrrrr")
test(alternating_colors, "b")
test(alternating_colors, "brrr")
test(alternating_colors, "brrrbbbbb")

# these tests should not accept
test(alternating_colors, "")
test(alternating_colors, "rr")
test(alternating_colors, "brrrr")
test(alternating_colors, "brrrrr")
test(alternating_colors, "rbbbrrr")
test(alternating_colors, "brbrbb")

A: consecutives = list((len(list(x[1])) for x in itertools.groupby("rbbbrrrrr")))
# first get consecutive groupings
print all(y-x == 2 and x%2 and y%2 for x,y in zip(consecutives,consecutives[1:]))
#check that all values are odd and incrementing by 2


text:
Q: Is there a name for this graph density measure? Let $G=(V,E)$ be an undirected graph.
We define the following procedure (randomized greedy coloring):

Fix some random ordering over the vertices (each permutation will be chosen w.p. $\frac{1}{|V|!}$).
Color the graph vertices according to the order such that each vertex gets colored by the minimal color not used already by its neighbors.

We define $\mathfrak C(G)$ to be the expected number of colors according to the procedure.

Is there a name for $\mathfrak C(G)$?

For example:

*

*$\mathfrak C(K_n)=n$ (trivial, every vertex must get a new color regardless of the order).

*$\mathfrak C(C_6)=2\frac{1}{5}$ (in a cycle on 6 nodes, if the second vertex that is colored is of distance 3 from the first colored vertex, the number of colors used will be 3).

A: I believe this is called the chromatic density of a finite graph. See page 8 of this reference. The notation is different, but I think it is the same concept.


text:
Q: Experience in war vs on war My question is that should we say I have experience in war or I have experience on war?
Please, clear the fog in my head. Thanks

A: "On" seems to suggest that you were covering or talking about war, while "in" suggests something more along the lines of participation in battle.


text:
Q: How to test DNS Forwarders without disconnecting the Primary DNS Server? I have two domain controllers in my domain in remote offices (Europe and China) and two domain controllers in the US, 4 in total. We had a network outage in our US office a few weeks back and during this time, the office in Europe and China experienced issues with DNS not working.  I believe part of the issue is that the China server had no forwarder IP addresses set up and the Europe Server did, but it was for our local US ISP.
I want to play around with making some changes to the IP addresses of the DNS Forwarders on these servers but I'm unsure how to test if my changes fix the issue. I would like to avoid disconnecting these remote DC's from our primary DNS servers here in the US. Since everything is up and running well now, if I do nslookup to a website or visit a website in a browser, it will just use our primary DNS servers - how can I specifically test if the DNS forwarder IP addresses are working?
Thanks in advance, let me know if I can give more info or clarify anything

A: Without repeating the incident you can't troubleshoot it - there is no way to know what went screwy with your DNS traffic unless you make it happen again.
Given your problem description, my money is on "Wrong or missing forwarders" like you guessed.

If, as you describe, your European servers are pointing at the US server as a forwarder there are a few sub-optimal results:

*

*Any time you ask for a zone the European server doesn't know about it asks America.

*America doesn't know, so it asks it's forwarder (and so on until we get to the root).

*America gets the answer, and sends it back to Europe.

That's at least two trips across the ocean -- not great.  And if the American name server goes away Europe has nobody to ask.
For best results, each regional nameserver should have all your internal zones, and be configured with a nearby forwarder if it needs to ask someone else for the record.
This lets you benefit from the caches at your upstream provider, and if your domain gets fractured you can still resolve external DNS names.

How can you test this? On Unix we would use the dig tool (dig +trace).
This is not included with Windows as far as I know, but there are implementations of it available (Google dig for windows for more options).
The +trace option shows you which servers were queried in the process of getting you an answer.

Special Note
There are some circumstances where I suggest using an alternate forwarder (or the root servers directly) -- If you have an ISP that hijacks DNS requests and does not properly return NXDOMAIN for non-existent domain names you should not use their DNS servers.
If you have such an ISP configure an alternative forwarder (like Google Public DNS) instead, or use root hints and ensure that you keep your hints data current.

A: So many things to say.

*

*Why use forwarders for external DNS resolution? You're introducing a point of failure and introducing possibly wonky results from whatever forwarders you choose. Why rely on some external ISP to provide external DNS resolution for you? Use the root hint servers instead.

*If you want to test the functionality of the forwarder then query it directly using nslookup.

*Your statement "I would like to avoid disconnecting these remote DC's from our primary DNS servers here in the US" doesn't make any sense. What do you mean "disconnect"?

*If a Windows DNS server isn't configured to use forwarders then by default it will use the root hint servers.

*When you experienced the issue what type of DNS problems did you have? Was it a failure of internal DNS resolution or external DNS resolution?


text:
Q: How to create unique name for each user's input? x = int(input())
for i in range(n):
    x(i) = input()
print(x, x1, x2,…)

It has an error. I know it's wrong, but can I do it?

A: Like @Random Davis mentioned, you can append them to a list.
This snippet takes in x as how many user inputs to take, then adds each user input to input_values list:
x = int(input())
input_values = []
for i in range(x):
    input_values.append(input())

Now you can access all the user inputs in the list all at once or individually using its index:
print(input_values)
print(input_values[2])

Here is an example of user entering 5 numbers:


text:
Q: How can I pass the data from a TableViewController when I dismiss it? I have a segue from my MainViewController to my ThemesTableViewController. After performing the segue, I choose a theme on my ThemesTableViewController. When I dismiss my ThemesTableViewController, I want to see the theme selected already applied to my MainViewController. How can I achieve that?
// Here's my Theme
struct Theme {
    var name: String!
    var backgroundColor: UIColor!
    ...
}

themes = [red, blue, green]

// I have no idea how I can pass chosenTheme to my MainViewController
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    chosenTheme = themes[indexPath.row]
    dismiss(animated: true, completion: nil)
}

A: protocol ThemeDelegate {
    func didSelectTheme(theme: Theme)
}

var delegate: ThemeDelegate?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    chosenTheme = themes[indexPath.row]
    self.delegate?.didSelectTheme(theme: chosenTheme)
}

You can create a protocol and implement it like this and pass the chosenTheme to the previous viewcontroller. In your MainViewController prepare for segue function do it like this.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    if let themeVC = segue.destination as? ThemesTableViewController {
        themeVC.delegate = self
    }
}

Also implement an extension like this in MainViewController.

extension MainViewController: ThemeDelegate {

    func didSelectTheme(theme: Theme) {
        // do something with the selected theme.
    }

}

A: Passing data with unwind segue :
Passing data with unwind segue
Using NotificationCenter for applying theme after unwind :
Adding dark mode to iOS app


text:
Q: My application is in the process of being installed for a long time it is android 6.0.
release version:The installation time is too long(10-15 minutes) apk size:8M.
debug version: normal.
What should I do? thanks.


text:
Q: FHIR DSTU2 Java reference implementation XhtmlParser bug We use the FHIR DSTU2 Java reference implementation(me.fhir:fhir-dstu2:1.0.1.7108) and encountered a problem with XhtmlParser.
The parseHtmlNode method, with the element and attribute white list, is very good and we typically want to use this both for json as well as xml data.

*

*Currently this is only used for xml parsing and there is another parse method, used for json parsing, which doesn't enforce the white list and allows malicious inline scripts. Is there any reason as to why this white list is not enforced for json parsing?

*The XhtmlParser's security policy(Accept/Drop/Reject) is not exposed to the user as a configurable parameter. Currently we had to override parseXhtml method in a derived class of JsonParser/XmlParser and initialize the XhtmlParser with the desired security policy.

*With the security policy set to Drop, the parseHtmlNode method goes into a infinite loop due to a missing xpp.next() call after ignoring an element.
I would appreciate if the FHIR developers can respond to these issues and if they could be fixed in a minor update to the Java reference implementation. Please let me know if I had grossly misunderstood something.
Thanks,
Anand Mohan

A: One response to all 3: whoops. I'll fix and release an update


text:
Q: Question related to integration and function Let $f\colon [0,\infty)\to\mathbb R$ be a non decreasing function. Prove inequality
$$(z-x)\int_y^z f(u)\,du\ge(z-y)\int_x^z f(u)\,du$$
$$0\le x \lt y \lt z$$
How to solve this question?

A: If $f(x)$ is an increasing function over $\mathbb{R}^+$, its primitive:
$$ F(x) = \int_{0}^{x}f(t)\,dt $$
is a convex function, so:
$$\Delta(u,v) = \frac{F(u)-F(v)}{u-v} $$
is increasing with respect to both its arguments. Since $x<y<z$,
$$ \Delta(z,y)\geq \Delta(z,x) $$
holds, but that is equivalent to the claim.


text:
Q: What JS error help prevent with typescript error when it is Functions that return promises must be async @typescript-eslint/promise-function-async I feel like this is not necessary. Is this error rule is to prevent promise that return, no error? What does this error help with?
I read the official doc https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/promise-function-async.md
But I do not understand what does it really mean here:

non-async Promise - returning functions are technically capable of either. Code that handles the results of those functions will often need to handle both cases, which can get complex

Is the both referring to is resolve or reject or something else?

A: Paraphrasing the description in the rule's documentation: if a function can both throw a synchronous error and return a rejected promise, it's tough to write code to handle that. This rule ensures that a function either does one, or the other, never both.
For example, if a function might have both a synchronous and an asynchronous error, then handling them needs to be something like this:
function example (obj) {
  // this might throw synchronously
  const result = JSON.stringify(obj);
  // This might reject (asynchronously)
  return new Promise((resolve, reject) => {
   if (Math.random() > 0.5) {
     resolve(result);
   } else {
     reject('too bad');
   }
  });
}

try {
  example({ foo: 'bar' })
    .catch(err => {
      // Have to split my error handling to two places, not one
    });
} catch (err) {
 // Have to split my error handling to two places, not one
}

Instead of just one catch
example({ foo: 'bar' })
  .catch(err => {
    // All error handling in one place
  });

As with all lint rules, if you don't find it useful, feel free to disable it.


text:
Q: Definition by Recursion - Need for Rigour Suppose you define the factorial $n!$ by
\begin{align}
\tag{1}0!&:=1,\\
\tag{2}(n+1)!&:=(n+1)n!.
\end{align}
Consider the following argument showing that $n!$ is a uniquely defined function.
Let
$$
P(n):="n!\text{ is uniquely defined }".
$$
Then $(1)$ gives $P(0)$ and $(2)$ gives $P(n)\implies P(n+1)$. So, by induction, $P(n)$ is true for every natural number $n$, that is, the factorial $n!$ has been uniquely defined.

Question: Why is this argument erroneous?

There might be some ambiguity talking about $n!$ in advance of knowing that it exists, but what if we write
$$
P'(n):="\text{The symbol }n!\text{ is uniquely defined }".
$$
In the end, is it the impossibility of translating $P'(n)$ in, say, the formal language of ZF that is problematic?

A: We have to distinguish between first-order arithmetic and second-order one.
The original (1889) Peano version is second-order; see Arithmetices Principia, page 1 has :

Axiomata

1) $1 ∈ N$ [...]
9) $(k∈Class \land 1∈k∧x∈N∧∀x(x∈k→(x+1)∈k)→N⊆k)$.

Also Landau express his Axiom 5 (Induction) as :

Let there be given a set $\mathfrak M$ of natural numbers, with the following properties:

I) $1$ belongs to $\mathfrak M$. [...]

In a modern treatment of second-order arithmetic (see e.g.Dirk van Dalen, Logic and Structure (5th ed - 2013), page 152), we need the following axioms :

1) $∀x¬(0=S(y))$
2) $∀xy(S(x) ∧ S(y) → x = y)$
3) $∀P(P(0)∧∀x(P(x) → P(S(x))) → ∀xP(x))$.

We can for simplicity extend the language with $+$ and $\times$, but we can define them, according to Church, as follows :

$x+y=z \leftrightarrow \forall F(F(0,x) \land \forall x \forall y (F(x,y) \to F(S(x),S(y)) \to F(y,z))$.

With this definition, and the corresponding one for $\times$, we can prove existence and uniqueness of the corresponding operations.

In f-o arithmetic, we cannot prove the existence of a function, because we cannot quantify neither predicate nor function letters, i.e. we cannot express in it $\exists F (F(\ldots))$.
Thus, we need the so-called rucursive axioms for sum and product :

$x+0=x$
$x+S(y)=S(x+y)$

and similar for $\times$.
The $+$ symbol is a function symbol, interpreted - according to the "standard" semantical specifications - as an operation :

$+ : N × N → N$, where $N$ is the domain of the interpretation.

With the equality axiom for function symbols :

$∀x_1 \ldots x_n y_1 \ldots y_n \ (x_1=y_1 \land \ldots x_n=y_n → f(x_1,\ldots, x_n) = f(y_1,\ldots, y_n))$,

"applied" to $+$ we get :

$\forall x_1 x_2 y_1 y_2 \ (x_1=y_1 \land x_2=y_2 \to x_1+x_2=y_1+y_2)$.

We can say that the "existence" and "uniqueness" of the $+$ and $\times$ operations are built-in into the syntax and semantics of the language.

If we are working in set theory, the arithmetical "notions" are nor more primitive : we define suitable "substitute" for $0$ and the successor operation as well as for $+$ and $\times$.
In this case, we can prove Peano axioms (Induction included) and the uniqueness of the sum and product function, via recursion; see :

*

*George Tourlakis, Lectures in Logic and Set Theory : Volume 2, Set Theory (2003), page 246;

*Kenneth Kunen, The Foundations of Mathematics (2009), page 43 :

On $\omega$ we already have the Principle of Ordinary Induction (Theorem 1.8.14 : For any set $X$ : if $0 \in X$ and $\forall y \in X(S(y) \in X)$, then $X$ contains all natural numbers.), whereas recursion would be used to justify the definition of the factorial ($!$) function by:

$0! = 1$
$(n + 1)! = n!(n + 1)$.


text:
Q: Angular Demo app I've been learning Angular and hit a strange wall . . . first off I ran an angular demo using DEPLOYD and SERVER.JS and everything ran fine.  I also ran another that hits a RESTful web service online, and it ran fine.  So I take what seems to be the next logical step and create my own RESTful web service and it deploys to TOMCAT just fine.  I can query the service in my browser to localhost, and it runs fine.  So far so good.
So, I build a very simple Angular app to hit that service and nothing gets returned.  OK, I figure I messed something up . . . so I mod my demo app to hit a DEPLOYD instance, and it works.  I mod it to his the existing service, and it works . . . but when I point it to my own RESTful service nothing gets returned.  I can't afford to lose any more hair over this.  Here are some particulars:
When tested in the browser, my service is returning:
    [{"person":{"id":1,"fullName":"Alpha","age":10}},{"person":{"id":2,"fullName":"Bravo","age":20}},{"person":{"id":3,"fullName":"Charlie","age":30}},{"person":{"id":4,"fullName":"Delta","age":40}},{"person":{"id":5,"fullName":"Echo","age":50}},{"person":{"id":6,"fullName":"Foxtrot","age":60}}]

A pretty simple JSON array, right?
Here is my HTML:
    <!doctype html>

        <title>Hello AngularJS</title>

        <link href="css/bootstrap.css" rel="stylesheet" />
        <link href="css/bootstrap-theme.css" rel="stylesheet" />

                {{person.id}}

                    {{person.age}}

And here is my controller javascript:
    function Hello($scope, $http) {

        $scope.data = {};
        $http.get("http://localhost:8085/TestWS/service/getAllPersonsInJSON").
            success(function(data) {
                $scope.data.person = data;
            });
        @scope.data.person();
    }

I pared it down to the essentials, I think . . . but no joy getting data displayed.  Anyone care to help me avoid making a larger bald spot?
TIA,
     Ted

A: Remove this line as that's not really valid Angular code and person isn't a function.
@scope.data.person();

Everything else looks great.

A: I was able to run this on my machine.
The issue looks like with nesting of data to an extra step.
The data you are receiving is a json array, to display this I directly assigned it to person.
Made these changes to controller :
removed $scope.data = {};
So controller had the below 3 lines.
 $http.get("url").
        success(function(data) {
            $scope.person = data;
        });

Then accessed the data in HTML file :

              person is
                {{person.person.id}}

                    {{person.person.age}}

Hope it will help.
Cheers

A: Try this:
 $scope.data.person = data.data;

This is because, the $http.Get(function(data){},..) will return http response packet in data variable. In order to access the data inside http response packet, you've to access data.data object.
Edit:
If above workaround donot works, use console.log(data) inside success callback and have a look at browser's console to inspect what data is being actually passed on by the success callback function.
Hope this helps.


text:
Q: Next callback in Backbone Router Is it possible to navigate to the next route handler if the first handler doesn't satisfy/catch a specific situation?
Is something that you can achieve in Express (nodejs) with the next()method.
Imagine that you have this router configuration:
routes: {
    '*path': 'onPath',
    '*notFound': 'onNotFound'
},

onPath: function(path, next){
    if(path == 'something'){
        console.log('ok');
    } else {
        next();
    }
},

onNotFound: function(){
    console.log('KO');
}

I know that I can mix the onPath and onNotFound methods, but I just want do know if is possible. Thanks!

A: First of all, I'm not sure you can have 2 path matchers in a router.  How would the Router know which to use?  Here is an option.  Remove the notFound route and call the method directly :
routes: {
    '*path': 'onPath'
},

onPath: function(path){
    if(path == 'something'){
        console.log('ok');
    } else {
        this.onNotFound(path);
    }
},

onNotFound: function(path){
    console.log('KO');
}

Or an even cleaner approach: you can throw an event (avoid too many App level events if you can.  This is just an example)
App.trigger("pathNotFound", path);

Somewhere else in your code (again, perhaps not at the App level), you will need to listen for this event:
App.listenTo("pathNotFound", function(){
               console.log('KO');
});

This is all roughly written. You will need to adapt it to your application of course.


text:
Q: Prove $[\sqrt{n}+\sqrt{n+1}]=[\sqrt{n}+\sqrt{n+2}]$ for all integers $n\ge 1$ This is the full question

Prove that of the two equations $$ [\sqrt{n}+\sqrt{n+1}] = [\sqrt{n}+\sqrt{n+2}] \\ [\sqrt[3]{n}+\sqrt[3]{n+1}] = [\sqrt[3]{n}+\sqrt[3]{n+2}]$$ the first one holds for every positive integer $n$, but the second one does not. Note: $[x]$ denotes the greatest integer function/floor function of $x$.

For the second equation, using python I was able to find two values of $n$ between $1$ and $100$ for which the equation is false. They were $n=15$ and $n=42$. Is there a way to actually calculate these values directly from the equation. Also, I don't have any ideas for proving the first equation. Any hints?

A: Assume that there is an integer $m$ such that
$$\sqrt{n}+\sqrt{n+1}<m<\sqrt{n}+\sqrt{n+2}.$$
Squaring quickly proves that
$$\lceil(\sqrt{n}+\sqrt{n+1})^2\rceil=4n+2$$
and
$$
\lceil(\sqrt{n}+\sqrt{n+2})^2\rceil=4n+4.
$$
These imply that $m^2$ must be equal to either $4n+2$ or $4n+3$, both of which are impossible by considering quadratic residues modulo $4$.

It seems to me that for all $n\ge2$ we have
$$\lfloor(\root3\of{n}+\root3\of{n+1})^3\rfloor=8n+3$$ and
$$\lfloor(\root3\of{n}+\root3\of{n+2})^3\rfloor=8n+7.$$ Whenever there is a perfect cube in between (allowing equality at the upper limit), there will be a failure with the cube roots. When $n=15$ we have $8n+3=123<5^3<127=8n+7$. When $n=42$ we have
$8n+3=339<7^3=8n+7$.
The cubes of even numbers are divisible by eight, and won't produce more examples. On the other hand for odd numbers $m$ we have $m^3\equiv m\pmod8$. Therefore the cubes of integers $m\equiv5,7\pmod8$ do give more examples. Indeed, with $m=13$ we have $m^3=8\cdot274+5$, and we get the next counterexample when $n=274$. The next counterexample comes at $n=421$ as
$8\cdot421+3<15^3=8\cdot421+7.$


text:
Q: Enable CDN to S3 bucket without granting public access in AWS I am trying to set up Amazon cloud front with s3 bucket behind. As per my company policy i cannot grant public access to the bucket.
How can we achieve this without violating company security?
People should able to access content with only URL.


text:
Q: Can't ping host from docker container my /etc/network/interfaces file when I am logged as the container looks like this
auto eth0
iface eth0 inet static
    address 192.168.1.27
    netmask 255.255.255.240
    gateway 192.168.1.1

but when I do ping 192.168.1.1 I get
connect: Network is unreachable

I don't understand why I cannot do that.
I get the same thing when pinging 8.8.8.8


text:
Q: Asp.net core, what is difference between cache Taghelper and IMemoryCache? I am workinog on Asp.net core 2.1 project. In my project, there is a menu that bind from 2 tables Group and subGroup.
Group Table contains Id and GroupName and subGroup table contains Id,groupId and subGroupName.
Now to improve the speed of loading the site i want use caching.
1 - What is the best way to cache data from database.
2 - What is the diffrence between <cache></cache> (Which is used in the view) and IMemoryCache (Which is used in the controller or class) in asp.net core?

A: You can use IMemoryCache if you want to cache just the query results server side or you can use Cache TagHelper to cache a specific part of the view which may or may not contain the results of that said query.
Also with IMemoryCache you can have global settings where with Cache TagHelper you'll have to do it manually for each tag use.
Fun fact: at its core Cache TagHelper implementation uses an instance of an IMemoryCache.


text:
Q: Existence of certain event
Suppose that $X$ is an unbounded random variable such that $\operatorname EX=0$ and $\operatorname E|X|^q=1$ with some $q>2$. Only the distribution of $X$ matters, so the probability space can be chosen freely. Choose any $p\in(0,1)$. I want to prove that there exists an event $F$ such that

*

*$P(F)=p$;

*$|X'|\le p^{-1/q}$, where $X'=X\chi_{F^c}+p^{-1}\operatorname E[X\chi_F]\chi_F$.

  How can I prove that such an event exists?

Since $|X'|$ has to be $\le p^{-1/q}$, this means that $|X(\omega)|\le p^{-1/q}$ when $\omega\in F^c$. Using Jensen's inequality and the assumption that $\operatorname E|X|^q=1$, $|p^{-1}\operatorname E[X\chi_F]|\le p^{-1/q}$.
As a starting point, consider $G=\{|X|>p^{-1/q}\}$. Clearly, $|X(\omega)|\le p^{-1/q}$ when $\omega\in G^c$. However, using Markov's inequality and the fact that $\operatorname E|X|^q=1$, we only have that $P(G)\le p$. So $G$ only satisfies one of the required conditions.
Consider $\tilde G$ which is obtained by taking some $\omega$'s from $G^c$ and putting them into $G$ so that $G\subset\tilde G$. Since $\tilde G^c\subset G^c$, we have that $|X(\omega)|\le p^{-1/q}$ when $\omega\in\tilde G^c$. Since $G\subset\tilde G$, $P(\tilde G)\ge P(G)$. So perhaps if we take, loosely speaking, the right amount of $\omega$'s from $G^c$ and put them into $G$, we might have that $P(\tilde G)=p$ and $|X(\omega)|\le p^{-1/q}$ when $\omega\in\tilde G^c$. Is it possible to make this argument rigorous?
Maybe there is a better and simpler way to prove the existence of such an event. Any help is much appreciated.
P.S. This is a part of a very nice answer that I have received previously and I am trying to understand every part of it.

A: For real $a$, let $Q(a):=P(|X|>a)$. Then the function $Q$ is right-continuous. So,
\begin{equation*}
 b:=a_p:=\inf\{a\in\mathbb R\colon Q(a)\le p\}=\min\{a\in\mathbb R\colon Q(a)\le p\}\in\mathbb R
\end{equation*}
and hence
\begin{equation}
 P(|X|>b)=Q(b)\le p\le Q(b-)=P(|X|\ge b)\le1/b^q, \tag{1}
\end{equation}
by Markov's inequality, so that
$$b\le p^{-1/q}.$$
Also, (1) implies that
\begin{equation}
 P(|X|=b)=P(|X|\ge b)-P(|X|>b)\ge p-P(|X|>b)\ge0. \tag{2}
\end{equation}
Since the probability space can be chosen freely, assume that it is non-atomic. Then, by (2), there is an event $H\subseteq\{|X|=b\}$ such that $P(H)=p-P(|X|>b)$. Let $F:=H\cup\{|X|>b\}$. Then
$$P(F)=p$$
and $|X|\le b\le p^{-1/q}$ on $F^c$. Also, by Hölder's inequality,
$\frac1p\,|EX\chi_F|\le \frac1p\,P(F)^{1-1/q}=p^{-1/q}$.
Thus, your conditions 1 and 2 both hold.


text:
Q: Convergence Criteria in R's lmer In this article , it is written in the Convergence and estimation bias para that :

It is important to consider the minimum number of cases needed to ensure the model
  converges and that sample estimates are not biased. In my experience, most simple models with 50
  or more groups and approximately 5 cases per group will not have convergence problems. More
  cases may be needed for convergence if the model is more complex, when there is more missing
  data (unbalanced N), and when more slope variances are estimated (Raudenbush, 2008).

I have a two-level model with one explanatory variable at the individual level(X) and one explanatory variable at the group level (Z) :
$$Y_{ij}=\gamma_{00}+\gamma_{10}X_{ij}+\gamma_{01}Z_j+\gamma_{11}X_{ij}Z_j+u_{0j}+u_{1j}X_{ij}+e_{ij}$$
I am doing a simulation study for determining sufficient sample size that produces accurate estimates of the parameters of the model . I am using lmer under package lme4 in R to fit the model . But when I have sample size $5$ at lower level , it produces many warning message about convergence. It seems to me this non-convergence issue is followed by that as I have a complex model more
cases is needed for convergence which is mentioned in the above article. I have checked it also by lme under package nlme and though it fits the model , but if I try to construct confidence interval by intervals , it gives error that :

Error in intervals.lme(fit) :
  cannot get confidence intervals on var-cov components: Non-positive definite approximate variance-covariance

But I am in doubt because the paper I am using give results when there is 5 cases in each group and they have used MLwiN . As far I know , there is an  issue in the method of evaluating an approximation to the log-likelihood which varies.
Douglas Bates replied about  valid estimates using lme4 in the context of GLMM that :

In some ways I think that reliable optimization of
  the approximate log-likelihood is more important and that is an area
  where R is not strong.  Far too much optimization code is covered by
  licenses that are not compatible with R's license and the pickings for
  Open Source optimization code are somewhat slim.  I wish I had access
  to some of the optimizers that SAS uses but we don't so we make use of
  what we do have.

Is it applicable also in the context of lmer so that I am facing non-convergence criterion where as MLwiN overcome the difficulties ?
Any help is appreciated. Thanks in advance.


text:
Q: Xcode 4.6.1 crashes whenever i try to add my device to the provisioning portal. Xcode 4.6.1 crashes whenever i try to add my device to the provisioning portal through Xcode Organizer.

A: Here's the solution:

*

*Exit Xcode.

*Run the following commands in Terminal:

mkdir ~/Library/Developer/Xcode/OldPortalDBs; mv
  ~/Library/Developer/Xcode/connect1.apple.com*
  ~/Library/Developer/Xcode/OldPortalDBs

*Start Xcode and try again!
For more details, see the official post on Apple Developer Forums.

A: It is definitely a bug in Xcode. Was working fine in the past. The command does not work for me either. The directory ~/Library/Developer/Xcode not found. Any advice, please. It is interesting, my new iPad was added without any problems. Cannot add iPhone to provisioning profile. iPhone runs iOS 6.1.3, iPad 6.1.2. It seems Xcode 4.6.1 does not support iOS 6.1.3

A: It's probably a bug in Xcode. I have a similar problem - it crashes when I refresh the provisioning profiles in the Organizer - every time. I ended up doing everything through the provisioning portal them manually downloading the profiles and updating them in Xcode.

A: ~/Library/Developer/Xcode/connect1.apple.com*   No such file or directory;
Oh my god, what's the problem.
==========
update
the answer did not work for me, after all, I cleaned all the related informations in keychain, and all provisioning files in Xcode, and renewed all these files, fixed this issue


text:
Q: Best Practice: Authenticated User and User Management Somewhat new to Laravel and I'm building an application in Laravel 5 and I have the authenticated user who is then managing user records. I'm currently using Zizaco Entrust and have roles and permissions all setup nicely. At the moment I'm passing a user object to my templates through the controller for the authenticated user as that is the only way I can find to check hasRole through entrust.  This becomes a problem when I start managing user records as I'd like to pass user and users and use REST but now user is occupied by the logged in user.
I'm basically looking for the best practice in having the logged in user always available (so the page header has their name and info and I can always log their edits to the data) and then the user model loading the user index, edit, etc. I was looking into Model Binding but now that has me even more confused - I implemented that on one of my models and now the hasMany children aren't loading.
I had hoped that Auth::user() provide me with the logged in user info but I can't do Entrust hasRole on that so it's unusable unless I use Auth::user() to load up the user from the model.

A: While it has caused an issue with my login, I discovered that If I change my model in config/auth.php
'model' => 'App\User',

to
'model' => 'App\Models\User',

That I'm able to use Auth::user()->hasRole('admin'). Now If I can just work out why doing so causes me this error on authentication:
ErrorException in EloquentUserProvider.php line 106:
Argument 1 passed to Illuminate\Auth\EloquentUserProvider::validateCredentials() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\Models\User given, called in /Users/dylanglockler/Sites/laravel-lovelaundry-5/vendor/laravel/framework/src/Illuminate/Auth/Guard.php on line 383 and defined


text:
Q: How to make mpv use the pulseaudio volume controls again? Since some recent update (mpv 0.18.something), mpv has stopped using the pulseaudio volume and instead used a software volume control.
This has downsides such as additional processing, but most importantly, the volume is not saved across mpv restarts anymore, while pulseaudio saves and restores the volume last used for mpv.
How can this be fixed?

A: To fix this, one can re-bind the volume control keys to use the ao-volume and ao-mute properties instead of the built-in softvol filter controls (see also the corresponding ArchWiki entry).
For this we need to modify ~/.config/mpv/input.conf (create it if it doesn't exist) and add the following entries:
0 add ao-volume 2
9 add ao-volume -2
m cycle ao-mute

This overrides the bindings existing for 0, 9 and m. If you prefer to use the internal softvol additionally, use different keybindings as suggested in the linked ArchWiki entry.


text:
Q: jqLite and element.querySelector outputs error Hi I have newly started to look at AngularJS and jqLite and have bumped into this issue that I don't understand.
I have this directive
angular
    .module('app')
    .directive('jqLiteTest', jqLiteTest);

/* @ngInject */
function jqLiteTest () {

    return {
        scope: {},
        restrict: 'E',
        template: '
Hello World
',
        link: function (scope, element, attrs) {
            element.prepend('this is prepend
');
            element.append('
 this is append');
            var hr = document.querySelector('#select-this-hr');
        }
    };

}

basically when I try to change the line above to
var hr = element.querySelector('#select-this-hr');

I get this error:

TypeError: undefined is not a function

Am I not allowed to use element instead of document? I'm lost.

A: Document.querySelector() is a function on the DOM Document.
In your example, element is a jqLite object.
You need to use the raw DOM element instead, for example:
var hr = element[0].querySelector('#select-this-hr');


text:
Q: C++ Why program with extern instance referenced before defined compiles and links The problem can be shown on a simple example:
extern A<bool> a;
B b(a);
A<bool> a("a");

In header file:
template<typename T>
class A {
    public:
        A(const char * name) : m_name(name) {}

        const char * name() const {
            return m_name;
        }
        ...
        ...
    private:
        const char * m_name;
};

class B {
    public:
        B(A<bool> & a) {
            printf("%s = %p\n", a.name(), &a);
        }
};

The code actually compiles, links and produce:
(null) = 0044F604

Demo
I wonder if this shouldn't be caught by compiler and fail.
Compiler in question is gcc 9.2.0 (mingw-w64-i686).

A: *

*There is nothing wrong with passing around and using references to uninitialised objects. The standard explicitly allows this.

*It is the programmer's responsibility to use such a reference in one of the limited ways permitted by the standard. The compiler is not required to complain if usage falls outside of the permitted range. Instead, the behaviour of a program that does this is undefined.

See basic.life/6 and basic.life/7 for detailed information.

A: In C++, global objects within the same translation unit are initialized in the order they are defined (though the order across TU's is undefined). See [basic.start.init]/2:

... Variables with ordered initialization defined within a single translation unit shall be initialized in the order of their definitions in the translation unit.

On the other hand, storage for objects of static storage duration is allocated at program loading time, so each global object has an address from the beginning.
In general in C++ it is allowed to reference a not-yet-initialized object, but accessing it is undefined behavior. Generally no diagnostic is required for undefined behavior.
In your case, B can be constructed with a reference to A, and it can save the passed-in reference to be used later:
class B {
    A<bool> & a_;
    public:
        B(A<bool> & a) : a_(a) { }

        void run() {
            printf("%s = %p\n", a_.name(), &a_);
        }
};


text:
Q: Typescript: Method to implement an interface with 3 different signatures? I am trying to wrap a function/method available in winston (node loggin framework), I have found its interface
interface LeveledLogMethod {
    (msg: string, callback: LogCallback): LoggerInstance;
    (msg: string, meta: any, callback: LogCallback): LoggerInstance;
    (msg: string, ...meta: any[]): LoggerInstance;
}

I would like to implement a method called "error" that would take the above signatures.
I am only wrapping it, so I will be calling the winston function directly.
If anybody is familiar with winston, I basically have 2 loggers setup and all consumers go through my main loggging class and I use either the 1st logger or second logger depending on the loglevel so I need to wrap it.

A: You can use optional properties and types to add that to your function so it matches the interface.
For example:
interface LeveledLogMethod {
    (msg: string, callback: () => void): string;
    (msg: string, meta: any, callback: () => void): string;
    (msg: string, ...meta: any[]): string;
}

let error: LeveledLogMethod = function (msg: string, b: () => void | any, c?: () => void): string {
    return '';
}

A: Use 3 interfaces this way:
interface A {}
interface B {}
interface C {}

const variable: A|B|C = {};


text:
Q: Amazon Route 53 Pointer Record not working I have a problem with a PTR (Pointer) in Route53.
I want http://tradehubz.com to redirect to http://www.tradehubz.com.
From what I gathered, the way to do it is via the PTR record which should do a HTTP Redirect (301)?
Example of Configuration on Route53

Ping Result

A: PTR record is for reverse DNS lookup or reverse DNS resolution is the determination of a domain name that is associated with a given IP address using the Domain Name Service (DNS) of the Internet.  DNS is not capable of acting like an HTTP redirect in any way. I think you should create "A" record for WWW and setup server side redirect.

A: DNS can do a lot more than you think it can. But I don't think you should be playing with records you have no clue about. Although I think an .htaccess rewrite rule makes more makes more sense ~ not every domain name is going to have hosting. Thus you create a CNAME (Canonical Name record) that directs to another url.
In this case it seems like your wanting to cover your bases in case someone goes to www. Then I would agree to use an IPv4 address (A- IPv4) or IPv6 (AAA-IPv6) record~
Set the a record - then go learn about rewrites (.htacess) server side changes respond faster than DNS records.


text:
Q: Update record without automatic joins to respective belongsTo associations I want to update a record for a specific condition in only items table but when I checked the query, it automatically add joins with it's associated tables. For examples:
$this->Item->updateAll(
    array('Item.alg_update' => 0),
    array('Item.id' => 123456),
);

it executes following query:
UPDATE `DB`.`items` AS `Item` LEFT JOIN
`DB`.`item_favorites` AS `ItemFavorite` ON
(`ItemFavorite`.`item_id` = `Item`.`id`) LEFT JOIN
`DB`.`categories` AS `Category` ON (`Item`.`category_id` =
`Category`.`id`) LEFT JOIN `DB`.`subcategories` AS `Subcategory` ON
(`Item`.`subcategory_id` = `Subcategory`.`id`) LEFT JOIN
`DB`.`item_descriptions` AS `ItemDescriptions` ON
(`Item`.`description_id` = `ItemDescriptions`.`id`) SET
`Item`.`alg_update` = 0  WHERE `Item`.`id` = 123456

A: From the manual (last paragraph

By default, updateAll() will automatically join any belongsTo
  association for databases that support joins. To prevent this,
  temporarily unbind the associations.

so you have to do
$this->Item->unbindModel(
    array('belongsTo' => array('Subcategory'))
);

$this->Item->updateAll(
    array('Item.alg_update' => 0),
    array('Item.id' => 123456),
);


text:
Q: Differential Geometry Notation When we have a metric on a manifold, there is a natural isomorphism between the tangent space and the cotangent space, and so, if I understand correctly, it is not so important to keep track of which indices are up and which are down since you basically always implicitly assume that if an index that was defined to be up is down the metric has been used to "lower" it, and vice versa.
Thus, when we do have a metric, why do we ever need to care about which indices are up and which are down? Couldn't we, by convention, write all indices down (as is done in the rest of mathematics) and finish with this story?

A: No, that is, if you do not want to have the derivatives of the metric tensor crop up everywhere.
You could also do differential geometry essentially without indices and insert the basis and dual basis at appropriate places. If you use the tradition of latin letters for the primal and greek letters for the dual basis, then lower indices everywhere are acceptable. But the formulas get much longer.

A: It might be helpful to consider an alternative system of doing differential geometry and how it handles this problem.
"Gauge Theory Gravity" was developed to use clifford algebra and "frame fields" on an intrinsically flat manifold for gravity, but it is essentially a framework for differential geometry.  It replicates the usual constructs of differential geometry using a linear map $h$, called the "displacement (or position) gauge field" that is kinda like the square root of the metric.  In particular, $g(a, b) \equiv h^{-1}(a) \cdot h^{-1}(b)$ for two vectors $a, b$.
You might notice I said vectors, and not covectors.  The elements of the base manifold aren't really distinguished from each other because it's a flat space, so in principle, you could put covectors in instead.  The distinguishing between vectors and covectors comes in how $h$ is used to develop a geometrically significant quantity (i.e. one that obeys tensor transformation laws).  Vectors always use $h^{-1}$, and covectors always use $h^T$.  Derivatives, like the covariant derivative $\nabla$, must always be wrapped in $h^T$ to get $h^T(\nabla)$ instead, while a curve $\alpha(t)$ will naturally pick up $h^{-1}$ when differentiated to get $h^{-1}(\alpha')$.
So while you could transform all covectors using the metric so that everything is wrapped in $h^{-1}$ instead of $h^T$, it's somewhat cumbersome to do so.  The GTG approach allows you to just define quantities like $\tilde v = h^{-1}(\alpha')$ and forget how the bare quantities were wrapped in the first place.  Dot products between quantities that obey the proper transformation laws are inherently meaningful from a geometric standpoint, so there's no issue.  This is something conventional differential geometry can't do!
So until DG comes up with something like that, you're kinda stuck.  You can write all formulas and such assuming only vector arguments (do Carmo does this in his Riemannian geometry book), or you can keep track of everything by hand.  I prefer the latter approach because while there is an equivalence, keeping track of whether a quantity is vector or covector or such can tell you a bit about the nature of that quantity: did it come from a gradient, say, or is it a derivative along a curve?
GTG may be a bit "out there," but if you're studying gravity, I could consider looking into frame fields at least (or tetrads, or vierbeins; they all mean the same thing).


text:
Q: Kotlin, how can I read a dynamic website as text? As titled, I'm trying to read the content of sites like this one, which appears to be javascript based.
I tried using plain jdk lib, then jsoup and then htmlunit, but I couldn't get anything useful out of it (I see just the source code or just the title or null):
val url = URL("https://registry.terraform.io/providers/hashicorp/tls/latest/docs/data-sources/certificate")
val connection = url.openConnection()
val scanner = Scanner(connection.getInputStream())
scanner.useDelimiter("\\Z")
val content = scanner.next()
scanner.close()
println(content)

val doc = Jsoup.connect("https://registry.terraform.io/providers/hashicorp/tls/latest/docs/data-sources/certificate").get()
    println(doc.text())

WebClient().use { webClient ->
    val page = webClient.getPage<HtmlPage>("https://registry.terraform.io/providers/hashicorp/tls/latest/docs/data-sources/certificate")
    val pageAsText = page.asNormalizedText()
    println(pageAsText)
}

WebClient(BrowserVersion.FIREFOX).use { webClient ->
    val page = webClient.getPage<HtmlPage>("https://registry.terraform.io/providers/hashicorp/tls/latest/docs/data-sources/certificate")
    println(page.textContent)
}

It should be something easy peasy, but I cant see what's wrong

A: In order for this to be possible, you need something to execute the JS that modifies the DOM.
It might be a bit overkill depending on the use case, and probably won't be possible if you're on Android, but one way to do this is to launch a headless browser separately and interact with it from your code. For instance, using Chrome Headless and the Chrome DevTools Protocol. If you're interested, I have written a Kotlin library called chrome-devtools-kotlin to interact with a Chrome browser in a type-safe way.
There might be simpler options, though. For instance maybe you can run an embedded browser instead with JBrowserDriver and still use JSoup to parse the HTML, as mentioned in this other answer.

A: Regarding HtmlUnit:
the page has initially no content, all you see is rendered from javascript magic on the client side using one of this spa frameworks.
It looks like there is some feature check in the beginning that figures out the js support in HtmlUnit does not have all the required features and based on this you only get a hint like "Please enable Javascript to use this application".
You can use
page.asXml()

to have a look at the content trough HtmlUnit's eyes.
You can open an HtmlUnit issue on github but i fear adding support for this will be a longer story.


text:
Q: clearInterval on hover after ready page Good morning, I ask for help for my code. It works but i would like to load the content right away and not after hover-in and hover-out.
How can I fix it? thank you
`

<? print"

"; ?>

[SOLVED]
This is the solution, thank you all
`

<? print"

"; ?>

`
`

A: Most of your JavaScript code is just nonsense. You only really need one line of it. I also added a wrapper so that this will load when the document is ready, instead of straight away  where it might not work:
$(function() {
    $('#tabella').load('pres_tl_admin_ajax_load.php');
}

You can remove the rest of the JavaScript.

A: Try this:
$(document).ready(function() {
  $(document).hover(
    function(){ // quando è tutto pronto...
       clearInterval(timer);
    },
    function(){
      timer = setInterval(aggiornatabella, 1000); // ogni secondo aggiorna la tabella
    }
  );
});


text:
Q: Variable as a key for path in GruntJS Weird behavior, when i try in grunt-contrib-sass make key variable, instead path.
var sourseScssFolder = 'src/scss/*.scss';
var destCssFile = 'src/packed.css';
sass: {
            dist: {
                options: {
                    style: 'nested'
                },
                files: {
                    // Key don't wanna load from variable
                    destCssFile: sourseScssFolder,
                }
            }
        },

After this compiler create file "dest File", instead read from var. How fix this?

A: Grunt is being configured using vanilla Javascript. In other words, the issue you are describing is the same as this one: JavaScript set object key by variable
In this particular case, I would do something like this:
var sourseScssFolder = 'src/scss/*.scss';
var destCssFile = 'src/packed.css';
var configuration = {
    sass: {
        dist: {
            options: {
                style: 'nested'
            },
            files: {}
        }
    }
};
configuration.sass.dist.files[destCssFile] = sourseScssFolder;
grunt.initConfig(configuration);


text:
Q: Flutter IOS & ANDROID Widgets Implementation I wanted to ask about the implementation of IOS & Android Widgets for Flutter.
Current Scenario :
Basically, i have developed the app on android platform and now i want to convert it to IOS platform. Since this is my first app, i really need some experienced voice on some issues i am facing.
Questions :
1 - Is there any simple way to detect that the widgets currently used are of Android/IOS Platform ?
How can we know for sure that a specific widget is of Android platform and is not going to work on IOS platform and vice versa.
2 - If somehow we know for sure that the current widget we are using is of Android platform, then how can we find its equivalent widget to implement for IOS platform.
3 - Are these widgets specifically required when we are going to upload/publish to these platforms respective stores. For example in a scenario where i hadn't converted all of my android app widgets to ios widgets and when i try to publish the app for IOS store, does the IOS Store rejects that or not?
Any suggestions or help is greatly appreciated.

A: All standard widgets will work on iOS as is. Flutter paints the UI, rather than call the native APIs. You might use a plugin that does not support iOS, but I have not yet come across such a plugin on pub.dev.
If you want to write platform specific code, you can import dart:io and use the boolean Platform.isIOS or Platform.isAndroid.
Both the App Store and Play Store have specific requirements before your app is approved.

A: In case you really want to have Android specific widgets on Android devices and iOS specific widgets on iOS devices, then use the Flutter Platform Widgets package. This will exactly do that - drawing iOS buttons using the Cupertino library and Android buttons using the Android library (and most other widgets as well).
As @Mudassir mentioned in the other comment this is not a requirement. In case you go with the default widgets, you will have the same look on all devices (even web, Windows, etc.).


text:
Q: ajaxToolkit:AsyncFileUpload - Dynamic controls created in the AsyncFileUpload1_UploadComplete() is not rendering to page I am using a ajaxToolkit:AsyncFileUpload  that allows the user to upload a excel file. In the AsyncFileUpload1_UploadComplete() event, I am reading the excel data and creating excel structure using div and adding to the page. But these dynamically created controls are not being added to the page. I added a button in the updatepanel and checked. On button click event, I created same above controls. In this case, the controls are rendering to the page. The controls are not rendering in case of ajaxToolkit:AsyncFileUpload only. Can anybody please tell me what is the fix for this.

A: Add Button into UpdatePanel where you want to show new controls and make it invisible with css style.
In the AsyncFileUpload1_UploadComplete server-side method, save your data to Session state.
In the client-side OnClientUploadComplete event handler call __doPostBack function with hidden button's UniqueID first parameter value. Then make all stuff required to render dynamic content in that button's click handler.


text:
Q: Can I tell if screen is off vs the browser is minimized or tab has been changed with js? Can I tell if the screen is off vs the browser is minimized or tab has been changed with js?
I want to be able to run a function when the user has done something on his phone that was not on my page aside from turning the screen off.
Basically, I want to ignore the screen being turned off but run a function when the user minimized the browser app or changed tabs.
Is there such a way to do this with js? or node.js?
How can I tell I trigger different events for screen off vs any other action that removes focus or makes page visibility hidden?
thank you


text:
Q: How to bind buttons in Qt Quick to Python PyQt 5 How can bind the buttons I create in a .qml script to python PyQt5 code?
example:
python:
import sys
from PyQt5.QtCore import QObject, QUrl, Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine

if __name__ == "__main__":
  app = QApplication(sys.argv)
  engine = QQmlApplicationEngine()
  ctx = engine.rootContext()
  ctx.setContextProperty("main", engine)

  engine.load('test.qml')

  win = engine.rootObjects()[0]
  win.show()
  sys.exit(app.exec_())

qml:
import QtQuick 2.2
import QtQuick.Window 2.1
import QtQuick.Controls 1.2
import QtQuick.Dialogs 1.1

ApplicationWindow {
 title: qsTr("Test Invoke")

 width: 200
 height: 100

 Button{
  y : 70
  text : "About"
  onClicked: {
   print('Hello')
  }

 }
}

How can I do something with Python when the button is clicked?
Also: Does anyone has a good resource of examples or doc. about pyqt + qml (qt quick)?

A: If you name the button, you can connect to its onClick signal, or to a custom signal that it emits in onClicked. Example:
ApplicationWindow {
 title: qsTr("Test Invoke")
 width: 200
 height: 100

 Button {
  signal messageRequired
  objectName: "myButton"
  y : 70
  text : "About"
  onClicked: messageRequired()

 }
}

Note the signal in Button and the objectName property. Then the Python code just before exec could be for example:
def myFunction():
    print 'handler called'

button = win.findChild(QObject, "myButton")
button.messageRequired.connect(myFunction)
button.clicked.connect(myFunction) # works too

Note that in the Button above, onClicked just emits the messageRequired signal, so it is better to drop the custom signal and connect to clicked directly. Both onClicked() and any slots connected to clicked will get called when you click button.

A: There is another solution which uses a Python model (QObject) in QML.
Python
engine = QQmlApplicationEngine()
engine.load("main.qml")

class Greeter(QObject):
    @pyqtSlot(str)
    def sayHello(self, name):
        print("Hello, " + name)

ctx = engine.rootContext()
ctx.setContextProperty("greeter", Greeter())

QML
Button {
    onClicked: {
        greeter.sayHello("Alice")
    }
}

Ref.

*

*https://wiki.qt.io/Qt_for_Python/Connecting_QML_Signals


text:
Q: Check if variables contain identical value I have problem to check either any of my variable contains identical value. Assume I have 8 variable with random generated lowercase alphabet only. For your info, this value don't need to be secure.
$variable1 = random_string();
$variable2 = random_string();
$variable3 = random_string();
$variable4 = random_string();
$variable5 = random_string();
$variable6 = random_string();
$variable7 = random_string();
$variable8 = random_string();

function random_string($length = 6) {
    $characters = 'abcdefghijklmnopqrstuvwxyz';
    $characters_length = strlen($characters);
    $random_string = '';
    for ($i = 0; $i < $length; $i++) {
        $random_string .= $characters[rand(0, $characters_length - 1)];
    }
    return $random_string;
}

I have seen this accepted answer at this question. My question, is there any simpler method to compare all this 8 variables if any of this variables have same or identical value? And if it do have same value, then regenerate another random string until none of it contain same value.

A: If the number of variables is static then try:
$variable1 = random_string();
$variable2 = random_string();
$variable3 = random_string();
$variable4 = random_string();
$variable5 = random_string();
$variable6 = random_string();
$variable7 = random_string();
$variable8 = random_string();

function random_string($length = 6) {
    $characters = 'abcdefghijklmnopqrstuvwxyz';
    $characters_length = strlen($characters);
    $random_string = '';
    for ($i = 0; $i < $length; $i++) {
        $random_string .= $characters[rand(0, $characters_length - 1)];
    }
    return $random_string;
}
$arr = [];
for($i=1;$i<=8;$i++)
{
    if(!in_array(${"variable$i"}, $arr))
    {
        $arr[] = ${"variable$i"};
    }else
    {
        ${"variable$i"} = random_string();
        $i--;
    }
}

This will access all variables dynamically, and generate a new value for the var which value already exists. This works by storing all the values in an array 1 by 1, and comparing the new value with the one that already exists.

A: How about using array_unique() and count()?
$a = array();
array_push($a, random_string());
array_push($a, random_string());
array_push($a, random_string());
array_push($a, random_string());
array_push($a, random_string());
array_push($a, random_string());
array_push($a, random_string());
array_push($a, random_string());

$num_dups = count($a) - count(array_unique($a));
if ($num_dups == 0) {
  echo("all unique\n");
} else {
  echo("number of dups: " . $num_dups . "\n");
}

echo("create one dup\n");
$a[1] = $a[2];

$num_dups = count($a) - count(array_unique($a));
if ($num_dups == 0) {
  echo("all unique\n");
} else {
  echo("number of dups: " . $num_dups . "\n");
}

function random_string($length = 6) {
    $characters = 'abcdefghijklmnopqrstuvwxyz';
    $characters_length = strlen($characters);
    $random_string = '';
    for ($i = 0; $i < $length; $i++) {
        $random_string .= $characters[rand(0, $characters_length - 1)];
    }
    return $random_string;
}

Output is:
$ php uniq.php
all unique
create one dup
number of dups: 1

A: I think, that in this situation is better to use a one array (not eight separate variables), it's allow easily to check if generated string is not used already.
With list function you can assign the data from array to separate variables.
Example:
<?php
$variables = [];
for($i = 0; $i < 8; $i++) {
    $randomString = random_string();
    if ($i > 0 && in_array($randomString, $variables))
        $i--;
    else
        $variables[$i] = $randomString;
}
list($variable1, $variable2, $variable3, $variable4, $variable5, $variable6, $variable7, $variable8) = $variables;

print_r([$variable1, $variable2, $variable3, $variable4, $variable5, $variable6, $variable7, $variable8]);


text:
Q: series.add doesn't add new series I've modified XYseries demo for charting with Android using AChartEngine.  It doesn't add the second array as a new series. Here is my code.
 private XYMultipleSeriesDataset getDemoDataset() {
     XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
    final int nr = 10;

    double[] test1=new double[] {121.0,122.0,123.0,124.0,125.0,126.0,127.0,128.0,129.0,130.0};
    double[] test2=new double[] {131.0,132.0,133.0,134.0,135.0,136.0,137.0,138.0,139.0,140.0};

    double[] testArray= new double[test1.length + test2.length];
    System.arraycopy(test1, 0, testArray, 0, test1.length);
    System.arraycopy(test2, 0, testArray, test1.length, test2.length);

    for(double d:testArray){
    Log.i(MAIN_DEBUG_TAG, "testArray "+d);
    }

      Random r = new Random();
      for (int i = 0; i < SERIES_NR; i++) {
      XYSeries series = new XYSeries("Demo series " + (i + 1));
      for (int k = 0; k < nr; k++) {

     // series.add(k, 120 + r.nextInt() % 100);
    series.add(k, testArray[k]);

    Log.i(MAIN_DEBUG_TAG, "series.add  "+k +"   "+test1[k]);

     }
    dataset.addSeries(series);
    }

        return dataset;
  }

Test1 array is repeated. If I remove the comments from series.add(k,120+ random......  it will genereated 2 series of data to plot.  Any help appreciated. TIA

A: You're adding the same data points twice - testArray[0] to testArray[9] in both iterations of the outer loop. k always goes from 0 to 9, and the current code doesn't rely on anything other than k:
// No sign of anything that changes between iterations of the outer loop
series.add(k, testArray[k]);

How about:
 series.add(k, testArray[k + i * nr]);

That way the first series will have testArray[0] to testArray[9], and the second series will have testArray[10] to testArray[19].


text:
Q: Where is the azure notification hubs node sdk usage documentation? Obviously Stack Overflow is not the place for this question, but twitter @azuresupport refuses to do anything other than tell people to post here with a tag. So here goes.
Where the #$%@ are the node sdk docs? They used to be in google cache, and now they aren't even there. There are multiple issues in the github asking for the docs.
https://github.com/Azure/azure-sdk-for-node/issues/2291

A: The Internet Archive still has a cached copy at https://web.archive.org/web/20170107075814/https://azure.github.io/azure-sdk-for-node/azure-sb/latest/global.html

A: The docs were inadvertently removed from the doc repo, and we are working to resurrect them. We're sorry about that and will comment here when they're back.
Thank you for your patience,
Karl


text:
Q: Is it possible to use the Java 8 Stream API on Android API < 24? I've read this post here. But still I cannot run code containing Java 8 Stream API features like the following on minSdkVersion < 24.
List<Car> newCars = cars.stream()
                        .filter(s -> s.getColor().equals("red"))
                        .collect(Collectors.toList());

This doesn't run due to the error message

Call requires API level 24 (current min is 15): java.util.Collection#stream

So does someone know a solution?

A: [original answer]
You can not use Java8 streams on API level < 24.
However, there are some libraries that backport some of the stream functionality
https://github.com/aNNiMON/Lightweight-Stream-API
https://github.com/konmik/solid
https://sourceforge.net/projects/streamsupport/ (mentioned by @sartorius in comment)
[update k3b 2019-05-23]
https://github.com/retrostreams/android-retrostreams is a spinoff from streamsupport which takes advantage of Android Studio 3.x D8 / desugar toolchain's capability to use interface default & static methods across Jar file boundaries. There are also links to other android-retroXXX ie for  CompletableFuture.
[update aeracode 2020-07-24]
Good news, now we can use Java 8 Stream API and more without requiring a minimum API level.

A: Might be a little late to the party, but I just saw that If we use java8.util.stream.StreamSupport then we can run the same functional programming approach and use it prior to Api 24. Eg taken from web3j -
StreamSupport.stream(transactionReceipt.getLogs())
            .map(log -> extractEventParameters(event, log))
            .filter(Objects::nonNull)
            .collect(Collectors.toList());

A: Since release 8.2 of DexGuard it is possible to use the Java 8 streams API also on Android devices < API level 24. In order to do so, one needs to include the streamsupport library and DexGuard will translate all Java 8 stream API calls to the provided library. No additional handling is needed, and developers can simply code using the provided Java 8 streams API. Dependencies are also translated automatically, so it is possible to use libraries with Java 8 features also for Android development.
This feature will also be included in ProGuard in the near future, stay tuned.
Edit: Proguard 6.1.0 for which there already exists a beta version supports backporting Java 8 stream and time API.

A: Yes, it is! Starting from AGP 4.0.0 we can use Stream API and some other Java 8+ APIs (e.g. java.time)
Minimal required changes to your app's build.gradle:
android {
  compileOptions {
    // Flag to enable support for the new language APIs
    coreLibraryDesugaringEnabled true
  }
}

dependencies {
  coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'
}

A: Another solution I like to use is to statically use Kotlin's extensions over Collections from Java code, if the project supports both of course:
List<Car> newCars = CollectionsKt.filter(cars, s -> s.getColor().equals("red"));

Same for .map, .reduce, .first, ...etc

A: Create a İnterface.
public interface Pre<T,R> {
            R get(T item);
        }

Create a Filter Method.
public static  <T> List<T> Filter(List<T> list, Pre<T,Boolean> pre) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        {
            return list.stream().filter(p -> pre.get(p)).collect(Collectors.toList());
        }
        else
        {
            List<T> col = new ArrayList<T>();
            for (int i = 0 ; i < list.size() ; i++)
                if (pre.get(list.get(i)))
                    col.add(list.get(i));
            return col;
        }
    }

Using Code
    public static class model {
            public String Name;
        }
List<model> models = new ArrayList<>();
            ...
            List<model> filtermodels = Filter(models,p-> p.Name.equals("filter"));