text:
Q: ConstraintLayout: z-index issue I am using ConstraintLayout for activity:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.site.path.to.AuthenticationActivity">

    <EditText
        android:id="@+id/login"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:inputType="none"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <EditText
        android:id="@+id/password"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/login"/>

    <Button
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Log in"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/password"/>

    <FrameLayout
        android:visibility="gone"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@color/default_background"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </FrameLayout>
</android.support.constraint.ConstraintLayout>

FrameLayout should hide all content of the page when visible. But it hides all content except button. Why the button doesn't hide? How to fix it?

A: Editted:
Try to set android:stateListAnimator="@null" to the Button/AppCompatButton
In Lollipop (Android 5.0 (API 21)) and above, Buttons have a default elevation which causes them to always draw on top.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/background_image"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        android:tint="#80000000"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/logo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginRight="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="24dp"
        android:src="@drawable/logo"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/background_image"
        app:layout_constraintVertical_bias="0.049"
        tools:layout_constraintLeft_creator="1"
        tools:layout_constraintRight_creator="1" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="7dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="7dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:fontFamily="sans-serif-light"
        android:text="There is More"
        android:textColor="@android:color/white"
        app:layout_constraintBottom_toTopOf="@+id/scrollView2"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="@+id/logo"
        app:layout_constraintTop_toTopOf="@+id/logo"
        app:layout_constraintVertical_bias="1.0"
        tools:ignore="HardcodedText" />

    <ScrollView
        android:id="@+id/scrollView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginRight="32dp"
        android:layout_marginStart="32dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/logo"
        app:layout_constraintVertical_bias="0.050000012">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <android.support.design.widget.TextInputLayout
                android:id="@+id/input_layout_first_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/ThemeEditTextLight">

                <EditText
                    android:id="@+id/input_name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Name"
                    android:inputType="textPersonName"
                    android:theme="@style/ThemeEditTextLight" />

            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout
                android:id="@+id/input_layout_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/ThemeEditTextLight">

                <EditText
                    android:id="@+id/input_email"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Email"
                    android:inputType="textEmailAddress"
                    android:theme="@style/ThemeEditTextLight" />

            </android.support.design.widget.TextInputLayout>

            <android.support.design.widget.TextInputLayout
                android:id="@+id/input_layout_phone"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:theme="@style/ThemeEditTextLight">

                <EditText
                    android:id="@+id/input_phone"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Phone"
                    android:inputType="phone"
                    android:theme="@style/ThemeEditTextLight" />

            </android.support.design.widget.TextInputLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <android.support.design.widget.TextInputLayout
                    android:id="@+id/input_layout_password"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:theme="@style/ThemeEditTextLight">

                    <EditText
                        android:id="@+id/input_password"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="Password"
                        android:inputType="textPassword"
                        android:theme="@style/ThemeEditTextLight" />

                </android.support.design.widget.TextInputLayout>

            </LinearLayout>

        </LinearLayout>
    </ScrollView>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/sign_up_button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="32dp"
        android:layout_marginLeft="32dp"
        android:layout_marginRight="32dp"
        android:layout_marginStart="32dp"
        android:layout_marginTop="16dp"
        android:backgroundTint="#2a98f0"
        android:stateListAnimator="@null"
        android:elevation="0dp"
        android:paddingBottom="16dp"
        android:paddingTop="16dp"
        android:text="Sign up"
        android:textColor="@android:color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/scrollView2"
        app:layout_constraintVertical_bias="0.100000024" />

    <TextView
        android:id="@+id/or_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:fontFamily="sans-serif-light"
        android:gravity="center"
        android:text="or\nSign up with social sites"
        android:textColor="@color/white"
        app:layout_constraintBottom_toTopOf="@+id/imageView6"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

    <ImageView
        android:id="@+id/imageView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@+id/or_tv"
        app:layout_constraintVertical_bias="0.8"
        app:srcCompat="@drawable/ic_google_plus" />

    <FrameLayout
        android:id="@+id/progressBar"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@color/red"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <ProgressBar
            android:id="@+id/progressBarChild"
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" />
    </FrameLayout>

</android.support.constraint.ConstraintLayout>

This worked for me.

A: The problem is (as @motis10 noted) that Buttons have elevation by default (post Android 5.0), so they are drawn above other things that have no elevation.
If you give the thing you want drawn over the button a higher elevation value, then it will be drawn on top. I used: android:elevation="40dp" just to be safe, but I believe 8dp is the default button elevation.


text:
Q: How do I get index of a specific dropped element in a form element array? I have this html:

Tjänster

Priser

Om mig

When the dom has been loaded I save text (html) from each button like this:
$(".button").each(function(index) {
       //Store all texts (html) from buttons for later user with drag/drop
       lastHtml[index] = $(this).html();
}

where lastHtml is defined as a global array.
In some circumstances I want to change html of a button, but when I drag and drop it somewhere I want to go back to its original state. Therefore I save the texts(html) when the dom is loaded into variable lastHtml-array.
In the drop-section I retrieve the button's index by it's ID (The index number is retrieved by the elements button (useButtonId´), ex. button_id1 will return index 1, button_id2 will return index2 when dropped).
$( ".content").droppable({
    accept: ".button.dragme", //Must come from this dragged element
    drop: function( event, ui ) {
        //Show ordinary text for button
        var id = $(ui.helper).prop("id");
        var idArray = id.split("_id");                  //array of split between _id, example: [0] = button, [1] = 2
        var useButtonId = idArray[1];
        $(ui.helper).addClass("trans-effect").removeClass("dragme").removeClass("ui-draggable").html(lastHtml[useButtonId]);
    }
}

BUT what I really want is something like this: (I want to have how many buttons I like without having to take in account the id, but I still want all the html-values to be saved when dom is loaded and restored to it's original state when a specific button is dragged and dropped).

Tjänster

Priser

Om mig

I think!? I can use index(), but I really can't figure out how. I've tried with:
$(ui.helper).index())
$('.content').index(ui.helper))

but neither of them seems to return the correct index.

A: Might be easier to store the html on the element itself using .data()
var $btns=$('.button')
$btns.each(function(){
  var $btn=$(this);
  $btn.data('lastHtml', $btn.html());
});

data() is both getter and setter so to reset:
$(this).html( $(this).data('lasthtml') );

Alternatively create an attribute or data store like btn-index to reference your stored array
$btns.each(function(index) {
       //Store all texts (html) from buttons for later user with drag/drop
       lastHtml[index] = $(this).html();
       $(this).attr('btn-index',index)/* or*/.data('btn-index',index);
});

If only using it within your droppable example, storing on element seems like easiest way to go

redpajama_set_name: RedPajamaStackExchange


text:
Q: Synchronizations vs thread safe collections vs atomic wrapper classes vs locks I am new to concurrent programming. As I was going through the topics I got confused between Synchronizations, thread safe collections, atomic wrapper classes, locks.
Locks and Synchronization do same work by making a piece of code thread safe. Why do we need thread safe collections or atomic wrapper classes then? As locking will enable only a single thread to access the code and won't let collections or primitive types to be thread unsafe.

A: Because you need to be careful when using synchronization. If you abuse of it, you may have performance issues. Using thread-safe collections when possible is usually better for performance and you make sure that you haven't errors or deadlocks.

A: This is a very wide question that you're asking. Problem is, not all of these things have a single, strict definition. For example, thread-safe collections might use various forms of synchronization (like e.g. locks or atomic operations) to achieve thread-safety. However, not even the term "thread-safe" is well-defined!
However, there is one thing you got wrong surely: Synchronization is the goal, while locks, mutexes, atomics etc are means to achieve that. Synchronization just means that different threads access resources in a synchronized way. In other words, they coordinate access so that they don't badly interact with each other. BTW: I'm talking here about threads, but the different entities could also be processes or even different computers, but let's keep it simple at first.
Now, you ask about the use of "thread safe collections or atomic wrapper classes" and why they are required at all. The answer is pretty simple, these things provide different interfaces or services on a higher level. For example, when I have a FIFO connecting two threads, it doesn't matter how they synchronize access to the underlying queue. If the interface for the two threads is implemented properly, you get certain guarantees. Doing so manually with just locks is possible but complicated, so providing these as high-level building blocks in addition to the low-level primitives just makes software development easier and the results more reliable.
Lastly, one advise for further questions: As initially mentioned, not all terms have a universal meaning associated with them. Therefore, it would help if you provided additional info, like in particular the programming language you intend to use.


text:
Q: Making the minimum integer value positive in C So I've got the following code
printf("atoi(input) = %d\n", atoi(input));
long number = 0;
if(atol(input) < 0){
    printf("went into here\n");
    printf("atoi = %d\n", atoi(input));
    number = -1 * atoi(input);
    printf("number = %d\n", number);
}else{
    number = atoi(input);
}

But for some reason when my user inputs -2147483648 (and probably other really large decimals), the multiply by -1 doesn't work, and the number remains negative. Any ideas?

A: Unfortunately memory allocated for any standard tipe is limited, so ranges of all all types have quite definite borders. Violated borders lead to computing errors.
To know borders (like min and max possible values) for integer types (not only int, but also char, short, etc.) you can use limits.h. E.g.:
#include <stdio.h>
#include <limits.h>

int main(void)
{
    printf("INT_MIN = %d\n", INT_MIN);
    printf("INT_MAX = %d\n", INT_MAX);
    printf("LONG_MIN = %ld\n", LONG_MIN);
    printf("LONG_MAX = %ld\n", LONG_MAX);
    printf("LLONG_MIN = %lld\n", LLONG_MIN);
    printf("LLONG_MAX = %lld\n", LLONG_MAX);
    return 0;
}

Note:
1) values of limits depends on compiler and platform (e.g. for my system LONG_MIN is equal to INT_MIN, but perhaps, you will see different values);
2) limits.h is just text file that can be oppend and explored
3) also learn about stdint.h, that provide types with fixed sizes (and allows programs to be portable without "perhaps" in my first note)
4) there are some techniques to detect integer overflow

A: For both atoi() and atol(); if the converted value is out of range for the return type (int and long int respectively), then you get undefined behaviour (e.g. "format hard drive").
To avoid undefined behaviour you must ensure that the value in the string is within a certain range before using either atoi() or atol().
Any technique that correctly ensures the value in the string is within a certain range (without using either atoi() or atol()) is also a technique that can be modified slightly and used to detect and handle the INT_MIN case (without using either atoi() or atol()).

A: You are running into the value limit for a signed long integer. You will need to try using another data type.


text:
Q: Why does Biot-Savart's Law seem to fail when the current element is directed perpendicular to the position vector from the point concerned? To see why I think the law fails, please check the following situation.
The law states that $d\mathbf B=k\dfrac{id\mathbf l \times \mathbf r}{r^3}$.
Consider a current element through the centre of a circular loop.
We want to calculate the magnetic field at a point on the boundary of the loop.
In a closed loop, the Maxwell-Ampere Law states implies that $$c^2\times(\text{the circulation of B around it})=\frac{(\text{current through it})}{\epsilon_0}+(\text{rate of change of electric flux through it})\>.$$
In the situation described, the rate of change of flux can be calculated by noticing that a charge of magnitude idt flows from one side of the loop to the other. Since the charge is always extremely close to the centre, the flux through the loop before the charge crosses can be calculated by imagining a hemisphere (as in the figure ,drawn on the side opposite to the charge). As the flux through the hemisphere is $idt/2\epsilon_0$(due to the symmetry of a sphere) and the total flux through the surface comprising the loop and the hemisphere is zero, the flux through the loop is $idt/2\epsilon_0$.
When the charge crosses over, the flux is the same but with opposite sign.Hence,the total change in electric flux is $-idt/2\epsilon_0$.
This implies that the time-derivative of the flux is $-i/2\epsilon_0$ which cancels the other term in the equation, as $i$ is the current flowing through the loop, making the circulation of $B$ zero. Then, from symmetry, we can conclude that $B$ is zero at any point on the boundary of the loop, which contradicts Biot-Savart's Law.
However this problem does not arise if the current element does not cross the loop.
I do not know if I have made a mistake. Please explain it if I have. Otherwise an explanation of this failure is welcome.

A: It seems that you have a misunderstanding of the flux as used in Ampere's Law. First I want to restate Ampere's law in the integral form,
$$
\oint_C \mathbf B\cdot d\mathbf l = \mu_0 \iint_S \mathbf J\cdot d\mathbf S \>.
$$
The integral on the right is done over a surface $S$ that has the closed loop $C$ as its boundary. Here $S$ is not a closed surface as the one used in Gauss's law. There is no unique choice for this surface. In fact, one may chose a hemisphere with $C$ as its boundary, or one may simply choose a disk. For any current element that passes through the loop, it only crosses such a surface once, so you do not need to calculate the flux twice as you would for a closed surface. Therefore the total flux as represented by the integral on the right is nonzero.


text:
Q: How to get Historical Traffic Data from Here API Was looking at using the Here API to get some historical traffic data. Their website says they have historical traffic data, but I don't see a way to access it via their API other than getting a time-aware route, which takes historical traffic into account but doesn't give me info about it. Does anyone have any suggestions?

A: Several years is not accessible through these APIs.
Ask to be contacted from contact form on developer.here.com

A: use  REST API from Fleet Telematics Advanced Data Sets with layer TRAFFIC_SPEED_RECORD_FC1...5
Online documentation is there:
https://developer.here.com/documentation/versions
look for "Fleet Telematics Advanced Data Sets"


text:
Q: Deployment From one Dev org to another Dev Org is it possible to deploy the classes and respected test classes one dev org to another dev org using Change-Set.

A: From documentation:-

You can move metadata only between the production org and its
  sandboxes. You can't move changes between two production orgs or
  Developer Editions.

You can take advantage of ANT or Eclipse Force.com ide instead.
Can have look into this link for more info. https://trailhead.salesforce.com/en/alm_deployment/alm_tools


text:
Q: Tight layout for matplotlib 3d surface plot I am trying to create a 3d surface plot in matplotlib. the plot surface works fine using ax.plot_surface api. But I couldn't find a way to remove the padding surrounding the subplot. In fact, I don't need the outer axes that go from 0.0 to 1.0 at all. How can i remove the padding? I already tried many suggestions from stackoverflow like "ax.autoscale_view('tight')" and "fig.tight_layout()". autoscale_view don't change anything and fig.tight_layout() is not available in the matplotlib version i am using. For strict compatibility requirements i have to use a very old (Version 0.99) version of matplotlib. Any ideas ?
For completeness I have added a sample source code i am using:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize = (18,12))
rect = fig.add_subplot(2, 3, 2).get_position()
ax = Axes3D(fig, rect)
X = np.arange(-5, 5, 0.025)
Y = np.arange(-5, 5, 0.025)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet)
ax.view_init(azim=-90, elev=90)
ax.axis('off')

plt.show()


text:
Q: Cannot create unknown type clr-namespace: ONLY on one "TFS build agent" Something strange happened to one of our TFS Build servers
This is the scenario:
I have one Controller and two Build servers with two agents each one

*

*If I queue any build forcing it to run on my Build server 01, the build success

*If I queue the same build on my Build server 02, the build fails
The error is the following:

Cannot create unknown type '{clr-namespace:MyNamespace;assembly=MyAssembly}MyClassName'.

This is a custom MSBuild assembly and it targets the .Net Framework 4.5, this is checked in on the TFS control version, the controller is pointing to the correct path on TFS.
The DLL has not being updated in like 6 months
I do not understand why this is happening. And more disconcerting is the fact that this build server was working correctly yesterday, and anyone in the team has done anything to the server, they do not even have access.
I think the error is occurring before executing the build workflow, this would mean that for some reason the build template cannot be loaded which makes sense since the type cannot be resolved
Things that I have done so far:

*

*Yesterday morning the build server 02 was running smoothly

*I'm sure i"m using the same build running it on both build servers. This makes me think that there is no problems with the build template

*I'm sure any build fails on my build server 02 with the same error

*All the builds that I have tested run on 01 without issues

*Both build servers are enable, available and accessible on the network

*Both build servers have been configured with the domain account that is used to run the builds

*Both servers have access to the working folders and the TFS user has access to those servers

*The domain account belongs to the Administrators group on both build servers

*I double checked and these assemblies are not in the GAC on both build servers (I would not like to put them on the GAC, and again, my build server 01 is working correctly without the need to put the DLL's on the GAC)

*I compared the Windows Update history, and both servers were updated on the same date like 3 months ago
This is what I found
On my build server 01, I found that the custom build DLL's used to build were in the correct locations:
C:\Users\MyTFSServiceAccount\AppData\Local\Temp\BuildAgent\24\Assemblies

C:\Users\MyTFSServiceAccount\AppData\Local\Temp\BuildAgent\25\Assemblies

The previous paths had all the assemblies needed
On my build server 02, the folder was containing only one DLL, for some reasons the DLL's are not being copied, I checked the folder permissions and everything looks good, the tfsservice account has permissions to the folders and it is an administrator on the box
These are the paths on my build server 02
C:\Users\MyTFSServiceAccount\AppData\Local\Temp\BuildAgent\22\Assemblies

C:\Users\MyTFSServiceAccount\AppData\Local\Temp\BuildAgent\23\Assemblies

Well, I thought that copying the DLL's manually would solve the problem temporally....I was wrong =( I copied the DLL's but I'm receiving the same error
Could you guys please point me to the right direction?

A: jaja
This is why I hate TFS and this is why I love being a Software Engineer
After spending almost all day on this issue and validating everything that crossed to my mind,  at the end, it seems that the simplest approach always work...
I just restarted the TFS Services and magically everything started working again....


text:
Q: How to add product in to cart by sku or by model in Opencart 3.0 I want to add products into the cart by SKU or MODEL instead of Product id.
here is the code of how it adds in the category.twig file
<button type="button" onclick="cart.add('{{ product.product_id }}', '{{ product.minimum }}');"> {{ button_cart }}</button>

And here is js
// Cart add remove functions
var cart = {
    'add': function(product_id, quantity) {
        $.ajax({
            url: 'index.php?route=checkout/cart/add',
            type: 'post',
            data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
            dataType: 'json',
            beforeSend: function() {
                $('#cart > button').button('loading');
            },
            complete: function() {
                $('#cart > button').button('reset');
            },
            success: function(json) {
                $('.alert-dismissible, .text-danger').remove();

                if (json['redirect']) {
                    location = json['redirect'];
                }

                if (json['success']) {
                    $('#content').parent().before('
 ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">×</button>
');

                    // Need to set timeout otherwise it wont update the total
                    setTimeout(function () {
                        $('#cart > button').html(' ' + json['total'] + '');
                    }, 100);

                    $('html, body').animate({ scrollTop: 0 }, 'slow');

                    $('#cart > ul').load('index.php?route=common/cart/info ul li');
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
            }
        });
    },
}

in above code opencart uses product_id to add product into cart but instead i want to add it by sku or model

A: In common.js new method derived from add (basically product_id changed to sku and addBySku is called)
    'addBySku': function(sku, quantity) {
        $.ajax({
            url: 'index.php?route=checkout/cart/addBySku',
            type: 'post',
            data: 'sku=' + sku + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
            //nothing else changed from 'add' method

In catalog/controller/checkout/cart.php derived from add method. Just get product_id by sku, put it into post and keep everything else unchanged.
    public function addBySku() {
        $this->load->language('checkout/cart');
        $this->load->model('catalog/product');

        $json = array();

        if (isset($this->request->post['sku'])) {
            $product_id = (int)$this->model_catalog_product->productIDBySku($this->request->post['sku']);
        } else {
            $product_id = 0;
        }
        $this->request->post['product_id'] = $product_id;

        //nothing else changed from 'add' method

In catalog/model/catalog/product.php. Add this method which retrieves sku by product_id
    public function productIDBySku($sku) {
        $query = $this->db->query("select product_id from " . DB_PREFIX . "product where sku = '" . $this->db->escape($sku) . "'");
        return $query->row['product_id'];
    }

Hope that helps. I didn't test it though.
Don't forget to call correct method and pass sku

<button type="button" onclick="cart.addBySku('{{ product.sku }}',


text:
Q: Filtering Sentinel2 image collection to get least cloudy image for entire ROI I am trying to obtain the least cloudy image (or images) across my entire ROI. Though I do not get any errors, the true color composite is not being mapped for me to check if I have indeed sorted and used the least cloudy image in the entire Sentinel 2 image collection in my ROI and within a date range.
/////////////////////////////////////1. Parameters
//Load asset
var asset= ee.FeatureCollection('users/myfolder/asset'); //you can use any asset you have, eg consider a country like US. I cannot make my asset public
Map.addLayer(asset);

//Load Sentinel 2 image collection
var sentinel2 = ee.ImageCollection('COPERNICUS/S2');

//Function for masking clouds
// http://xzsunbest.tk/2018/07/05/MaskingOutCloudInSentinel2WithGEE/

// Bits 10 and 11 are clouds and cirrus, respectively.
var cloudBitMask = ee.Number(2).pow(10).int();
print (cloudBitMask); //1024
var cirrusBitMask = ee.Number(2).pow(11).int();
print (cirrusBitMask); //2048

var cloudmask = function (image) {
var qa = image.select('QA60');
// Both flags should be set to zero, indicating clear conditions.
var mask = qa.bitwiseAnd(cloudBitMask).eq(0).and(
         qa.bitwiseAnd(cirrusBitMask).eq(0));
return image.updateMask(mask);
 }

// Create clipping function
var clipper = function(image){
return image.clip(asset);
  };

/////////////////////////////////////2. Application
var clipped = sentinel2.map(clipper);
//var filtered = clipped.filterDate('2015-06-01','2018-08-30')
//                  .filter(ee.Filter.lte('CLOUDY_PIXEL_PERCENTAGE',2))
//        filtering to images with cloud cover of 2%. I do not want to
//filter.
//print (clipped); //Image Collection- will not print because there are >5000
//elements
var count = clipped.size();
print('Count: ', count); //8168695 across Sentinel2 in ROI

var filtered_date = clipped.filterDate('2015-01-01','2015-12-31');
var count_filtered = filtered_date.size();
print('Filtered (by date) Image Count: ', count_filtered);//259629 reduced
because of date range

var images = ee.Image(filtered_date.sort('CLOUDY_PIXEL_PERCENTAGE').first())
print('Least cloudy image: ', images);
Map.addLayer(images, {bands:['B4','B3','B2']}, 'true color composite');

A: First your actual question; why the image is not showing in the map: That is because you did not filter the images on your area of interest. Somewhere else on the world, your image was added (it gave no error). You can check where using:
Map.centerObject(images);

What you are doing now is using the full image collection of sentinel 2 in your analysis. That's a huge amount of data, and therefore you cannot print it. The function clip does not filter the image collection on your area of interest. You will need to filter the collection on the area (and date range), using:
// FIRST, reduce the collection spatially and temporally
var filtered = sentinel2.filterBounds(geometry).filterDate('2015-01-01','2015-12-31');
print('Filtered Image Count: ', filtered.size());

Your asset seems to be a feature collection, to clip images on that, use:
image.clipToCollection(asset);

Then apply you clip and cloudmask function by mapping over the image collection:
var clipped = filtered.map(cloudmask).map(clipper);

If you will add the image to the map as you did, you will see an image appearing on the map in the area of your study area
// Get a least cloudy image
var leastCloudy = ee.Image(filtered.sort('CLOUDY_PIXEL_PERCENTAGE').first());
Map.addLayer(leastCloudy, {bands:['B4','B3','B2'], min: 0, max: 3500}, 'true color scene');

For your further work, note that sentinel-2 images are cut into 100x100km granules (see the ESA user handbook or GEE dataset catalog). Probably you want to merge them by time or make a composite image for your studyarea and time range. See the link. Also note that cloudmasking for sentinel based on the QA band won't get rid of all the clouds, unfortunately.
Link script

A: You may collect such data from LandViewer. This tool has a vast database of satellite imagery from numerous satellites including Sentinerl-2 and it is updated on a regular basis.
All you need to do is follow this tutorial:

*

*Open LandViewer

*Click "filters" on the top right

*Select "Sentinel-2" from the sensors tab below

*Locate an area you need

*Set cloudiness level via settings bar above the sensors list

As an example, let's take a look at this image of New York. As you can see I set cloudliness level at 16% and I can see the image perfectly fine.
Direct link -> https://eos.com/landviewer/?lat=40.86446&lng=-73.01033&z=11&datasets=4&id=LV-UzJC-X3Rp-bGVf-MjAx-OTAy-MTdf-MThU-WExf-MA%3D%3D&b=Red,Green,Blue&anti
Here's a brief guide to free satellite data that can be found on LandViewer:

*

*Landsat 4 - archive 1982-1993

*Landsat 5 - archive 1984-2013

*Landsat 7 - archive since 1999

*MODIS - archive since 2012

*Landsat 8 - archive since 2013

*Sentinel-1 - archive since 2014

*Sentinel-2 - archive since 2015

All the satellite data is free to use and easy to find thanks to the convenient search interface, which reduces time needed to find right image data.


text:
Q: Installing Linux on hard disk that will be used by another computer with different hardware I was given a laptop with a totally dead display. I do not want to pay to replace the broken display, but I would like to use the laptop as a server and connect to it via SSH to control it.
I have pulled out the internal hard drive from the broken laptop, and I want to install Debian GNU/Linux and the SSH server onto this HDD using a working Debian laptop.
However, the hardware in the two laptops is very different, and I am wondering what kind of problems I would run into when I plugged the drive back in to the laptop with the broken display because of this?
How would I make this work? What is the proper way for me to install a bootable copy of Linux onto a HDD that will be used by a computer with different hardware?

A: The Linux kernel is able to load almost every driver it needs at runtime.  Distros like Debian typically build modules for every piece of hardware that might be encountered so if you just install Linux on the HDD and plug it into the laptop it will probably work.  The only issue I've had doing something similar recently was for a computer that had an old Nvidia network card.  The Nvidia forcdeth drivers aren't included in the standard kernel anymore so I had to install them manually but once I did it worked like a charm.

A: Can you attach an external monitor to the laptop with the broken display? If so, you may be able to leave the drive connected to that laptop and install Linux with all the proper hardware drivers for that laptop while being able to view the process on the external monitor.


text:
Q: Get unique row with distinct multiple column in oracle table Hi I have a tables tag which is like
id   loc_id   org_id   comp1   comp2   comp3   comp4  paper_id
1      5        4       A        C       B     (null)    1
2      6        3       F        D       E     (null)    1
3      5        4       C        B       A     (null)    1
4      6        3       E        F       D     (null)    1

I want to get a result like
id   loc_id   org_id   comp1   comp2   comp3   comp4  paper_id
3      5        4       C        B       A     (null)    1
4      6        3       E        F       D     (null)    1

Note I want a unique row having max id with distinct comp1, comp2, comp3, comp4 value inspite their column name but value should be same.
e.g if 1st row has A, B, C in comp1, comp2 & comp3 respectively
and    2nd row has C, B, A in comp1, comp2 & comp3 respectively
I want a single row.
I tried below query and this is not returning unique rows
SELECT DISTINCT loc_id, org_id, comp1, comp2, comp3, comp4, MAX(id)
  FROM tags t
  WHERE t.paper_id = 1
  GROUP BY loc_id, org_id, comp1, comp2, comp3, comp4;

Please help thanks.

A: In the frst step concatenate the compN columns in a given order.
You'll use LISTAGG - note that you use the delimiter and NVL function to make the result unique - you don't want to interpret (A,A,null,null) as a duplicate to (AA,null,null,null)
with t1 as (
select id, nvl(comp1,'-') comp from test union all
select id, nvl(comp2,'-') comp from test union all
select id, nvl(comp3,'-') comp from test union all
select id, nvl(comp4,'-') comp from test)
select id,
listagg(comp,',') within group (order by comp) as comp_key
from t1
group by id
order by 2
;

       ID COMP_KEY
---------- --------
         3 -,A,B,C
         1 -,A,B,C
         4 -,D,E,F
         2 -,D,E,F

The rest is as simple as group on the COMP_KEY and select some row from your source.
Here is an example selecting the highest ID per group (see max(id)in t3subquery).
with t1 as (
select id, nvl(comp1,'-') comp from test union all
select id, nvl(comp2,'-') comp from test union all
select id, nvl(comp3,'-') comp from test union all
select id, nvl(comp4,'-') comp from test),
t2 as (
select id,
listagg(comp,',') within group (order by comp) as comp_key
from t1
group by id
), t3 as (
select comp_key, max(id) id from t2
group  by comp_key)
select * from test
where id in (select id from t3)
order by id
;

.
        ID     LOC_ID     ORG_ID COMP1 COMP2 COMP3 COMP4        PAPER_ID
---------- ---------- ---------- ----- ----- ----- ---------- ----------
         3          5          4 C     B     A                         1
         4          6          3 E     F     D                         1

A: Here's one option; See if it suits your needs.
In order to do that, I'm going to create a function which sorts 4 IN parameters (representing comp1, ..., comp4 from your sample data).
SQL> create or replace function f_sort(p1 in varchar2, p2 in varchar2,
  2                                    p3 in varchar2, p4 in varchar2)
  3  return varchar2
  4  is
  5    /* sorts IN parameters. For example: if IN parameters are a, d, c, b
  6       then RETVAL = a:b:c:d
  7    */
  8    retval varchar2(200);
  9  begin
 10    with temp (p) as
 11      (select p1 from dual union all select p2 from dual union all
 12       select p3 from dual union all select p4 from dual
 13      )
 14    select listagg(p, ':') within group (order by p)
 15      into retval
 16    from temp;
 17
 18    return retval;
 19  end;
 20  /

Function created.

SQL>

What do I need it for? To select MAX(ID) for equal combinations of comp1, ..., comp4 values - as you described it (that's done in the inter CTE, below in a query).
SQL> with test (id, loc_id, org_id, comp1, comp2, comp3, comp4) as
  2  (select 1, 5, 4, 'a', 'c', 'b', null from dual union all
  3   select 2, 6, 3, 'f', 'd', 'e', null from dual union all
  4   select 3, 5, 4, 'c', 'b', 'a', null from dual union all
  5   select 4, 6, 3, 'e', 'f', 'd', null from dual
  6  ),
  7  inter as
  8  (select max(id) maxid, f_sort(comp1, comp2, comp3, comp4) srt
  9   from test
 10   group by f_sort(comp1, comp2, comp3, comp4)
 11  )
 12  select t.*
 13  from test t join inter i on i.maxid = t.id
 14  order by t.id;

        ID     LOC_ID     ORG_ID COMP1 COMP2 COMP3 COMP4
---------- ---------- ---------- ----- ----- ----- -----
         3          5          4 c     b     a
         4          6          3 e     f     d

SQL>

A: Thanks to @marmite-bomber following query worked for me,
SELECT comp_key, loc_id, org_id, max_id, 1, sysdate, sysdate
FROM (
  SELECT comp_key, max(id) max_id
  FROM (
    WITH t1 AS (
      SELECT t.id, t.loc_id, t.org_id, nvl(comp1,0) comp FROM tags t WHERE t.paper_id = 1 AND t.paper_id IS NOT NULL UNION
      SELECT t.id, t.loc_id, t.org_id, nvl(comp2,0) comp FROM tags t WHERE t.paper_id = 1 AND t.paper_id IS NOT NULL UNION
      SELECT t.id, t.loc_id, t.org_id, nvl(comp3,0) comp FROM tags t WHERE t.paper_id = 1 AND t.paper_id IS NOT NULL UNION
      SELECT t.id, t.loc_id, t.org_id, nvl(comp1,0) comp FROM tags t WHERE t.paper_id = 1 AND t.paper_id IS NOT NULL
    )
    SELECT t1.id, t1.loc_id loc_id, t1.org_id org_id, listagg(comp,',') within group (ORDER BY comp) AS comp_key
    FROM t1
    GROUP BY t1.id, t1.loc_id, t1.org_id
  )
  GROUP BY comp_key, loc_id, org_id
) t2, tags tg
WHERE tg.id = t2.max_id;

A: You may get your desired results by grouping greatest, least functions, and their mean(average values) by contribution of ascii function which converts the related columns to integers :
select *
  from tags
 where id in
  (
  select max(id)
    from tags
   group by least(ascii(comp1),ascii(comp2),ascii(comp3)),
         greatest(ascii(comp1),ascii(comp2),ascii(comp3)),
         (least(ascii(comp1),ascii(comp2),ascii(comp3))+
          greatest(ascii(comp1),ascii(comp2),ascii(comp3)))/2
  );

SQL Fiddle Demo


text:
Q: Rails 5 after removal of assigns function for controller tests I used assert_template and assigns extensively before Rails 5 in my controllers tests. For example to test that a link in the view is correct:
assert_select ".left-off-canvas-menu ul li a[href=?]", event_all_items_path(assigns(:event)), "Back to all items"

I figured that assert_template was not difficult to get rid of.
However, I don't know how to replace test cases like the one above.
I know about the gem to include those functions, but I'd like to try without them. So alternatives would be:
Would you make a case to keep the assigns function or would you say it is meant to be hard coded?


text:
Q: How to check the python socket recvfrom() data I am working on socket programming in python. Using ESP python i have created a socket to server and sending a request (in API packet format, according to server code it will respond). In receiving socket, i need to check the data(if data is received, it need continue to next operation. If not, i need to send request once again).
sending is okay. In receiving socket, if it is not receiving data, it is not going to next instruction.. please help me out.
code:
try:

    s = socket(AF_INET, SOCK_DGRAM)
    print "socket created"

except socket.error:

    print "failed to create socket"
    sys.exit()

sending data:
s.sendto("packet of data", 0, (HOST,PORT))

In receiving:
recvpack, payload=s.recvfrom(1024)

if not recvpack:

    s.sendto("packet of data", 0, (HOST,PORT))

elif(recvpack[]="packet of data"):

    pass # continue to next operations..

In the above receiving statement, if recvfrom() in not getting anydata, how to check recvpack and get back to next operations.. If socket.settimeout() or socket.setblocking() is the solution, how to use these..

A: If you don't mind a blocking call, I usually use settimeout to wait for a message. settimeout will raise an exception if it doesn't receive a message in time.
So basically you could do something like this:
s.settimeout(1)
try:
    recvpack, payload = s.recvfrom(1024)
except error:
    recvpack = None
if recvpack is not None:
    ...

Source : https://docs.python.org/2/library/socket.html#socket.socket.settimeout


text:
Q: why similar routes is not working in express.js example Get ,post ,patch ,delete Can any one help me only one route is working after adding second route
I am unable to trigger the second route
getting error
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Error</title>

Cannot GET /api/sellProduct1

Note : Please don't suggest to change  the route names , I am curious why they are not working with same routes but I am using different methods like post,get,delete.
plz can any one can help with proper answer.
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var productModel = require("./productSchema");

// Connecting to database
var query = 'mongodb://127.0.0.1:27017/mylibs'
const db = (query);
mongoose.Promise = global.Promise;

mongoose.connect(db, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}, function (error) {
    if (error) {
        console.log("Error!" + error);
    }
});

router.get("/", (req, res) => {
    res.send("welcome");
});

// find product by productname
router.get("/sellProduct:product", function (req, res) {

    productModel.findOne({ productName: req.query.product },
        function (err, data) {
            if (err) {
                console.log(err);
            }
            else {
                res.send(data);
            }
        });
});

router.post('/sellProduct', function (req, res) {
    var newProduct = new productModel({
        productName: req.body.productName,
        costPrice: req.body.costPrice,
        sellPrice: 0
    });

    newProduct.save(function (err, data) {
        if (err) {
            console.log(error);
        }
        else {
            res.send("Data inserted");
        }
    });
});

A: You should access the routing this way:
/api/sellProduct/1


text:
Q: How to dynamically add data to a dataframe? I have data I need to clean for each row in a file, and I want to insert the cleaned data in a SQLite3 database.  I'm using the RSQLite library which requires a dataframe.  Here's the code I trying to get working:
# Select feature names for use as column names in X train/test loading
feature_names <- unlist(dbGetQuery(con, "select feature_name from features order by feature_id"), use.names = FALSE);

# Load X training data
X_train_lines <- readLines("data/train/X_train.txt"); # Space delimited with leading and trailing spaces
X_train_values <- vector("list", length(X_train_lines));
names(X_train_values) <- feature_names; # colnames or names?
for (index in 1:length(X_train_lines)) {
  cleaned_line <- gsub("^ *|(?<= ) | *$", "", X_train_lines[index], perl=TRUE); # remove extraneous whitespaces
  X_train_values[index] <- strsplit(cleaned_line, " "); # Wondering if X_train_values[index] is correct?
}
# Write features data to features table
dbWriteTable(con, "X_train", as.data.frame(X_train_values), row.names = FALSE);

While the code executes without incident, when I attempt to look at the database using DbVisualizer I get an error:

An error occurred while performing the operation:
malformed database schema (X_train) - too many columns on X_train

My only guess is that rows and columns are somehow transposed.  My column names should be the value of the feature_names vector.
Also, if anyone has any suggestions for a better approach...
UPDATE
I tried doing a dput, though I had no idea what I was looking at. Here's the top of the summary:
head(summary(X_train_values))

                   Length Class    Mode
tBodyAcc-mean()-X "561"  "-none-" "character"
tBodyAcc-mean()-Y "561"  "-none-" "character"
tBodyAcc-mean()-Z "561"  "-none-" "character"
tBodyAcc-std()-X  "561"  "-none-" "character"
tBodyAcc-std()-Y  "561"  "-none-" "character"
tBodyAcc-std()-Z  "561"  "-none-" "character"

Again, this leads me to believe the data is all mixed up.  It should have 561 columns, some of which are represented above as tBodyAcc-mean()-X etc.  The column values should be floating-point numbers which I don't see above.
The table command did not work:
table(X_train_values)
Error in table(X_train_values) :
  attempt to make a table with >= 2^31 elements

I should have 7,352 rows with 561 columns.
UPDATE 2
I believe my problem is that I'm trying to use a list like an array or arrays.  In Ruby, for example, I could do something like this:
x_train_values = []
x_train_lines.each { |line| x_train_values << line.split(' ') }

A: In the following lines
for (index in 1:length(X_train_lines)) {
    cleaned_line <- gsub("^ *|(?<= ) | *$", "", X_train_lines[index], perl=TRUE);
    X_train_values[index] <- strsplit(cleaned_line, " ");
}

you are using single square brackets ([) to access the columns of a data frame, when you should be using double ones ([[). When you use X_train_lines[index], a data frame is returned, which has one column, equal to X_train_lines[index]. When you use X_train_lines[[index]], however, the actual contents of that column are returned (see http://adv-r.had.co.nz/Subsetting.html for more details).
Now, the way gsub works, is that it first converts its argument to a character using as.character and then processes it. In your case, X_train_lines[index] returns a data.frame whose single column is a factor (I guess) and therefore when coerced to a character you will get the factor levels, not the actual contents! So you are actually calling gsub on a string that looks like "1:2:3:...". If you use double brackets instead, then gsub will coerce a factor (instead of a data frame) to a character, which will work as desired.
As an aside, in R you do not need to end your lines with ;. This is needed only to separate multiple statements on the same line.
Finally, it is best to try and avoid for loops because they can be slow and because there are more efficient functions with simpler syntax that can usually accomplish what you need (like lapply, apply, sweep, etc). For column/row/element-wise operations on a data frame/matrix/etc you can use apply, in which case your code will look like
apply(X_train_values, 2, gsub, pattern = "^ *|(?<= ) | *$",
    replacement = "", perl = T)


text:
Q: What is the maximum area of a rectangle circumscribing another rectangle? The problem says that we have to find the maximum area of a rectangle that circumscribes another rectangle of sides $a$ and $b$.

A: A solution based on trigonometry:
Let $\alpha$ be the (smallest) angle formed by a side of the original rectangle and a side of the circumscribing rectangle. Then the area $A$ of the circumscribing rectangle is equal to the area $ab$ of the original rectangle plus the area of four right triangles, $a\sin\alpha\cdot a\cos\alpha + b\sin\alpha\cdot b\cos\alpha$. So
$$
A = ab + a^2\sin\alpha\cos\alpha + b^2\sin\alpha\cos\alpha
= ab + (a^2+b^2)\sin\alpha\cos\alpha
$$
$$
= ab + {1\over2}(a^2+b^2)\sin2\alpha.
\quad\mbox{(We used: } \ \sin2\alpha=2\sin\alpha\cos\alpha.)
$$
The area $A$ attains its maximum when $\sin2\alpha=1$, i.e. when $\alpha=45^\circ$, and we have
$$
A_\max = ab + {1\over2}(a^2+b^2) = {(a+b)^2\over2}.
$$
(It is easy to check that the circumscribing rectangle with area $A_\max$ is a square with side ${a+b\over\sqrt2}$.)


text:
Q: Ansible - Set content of file based on dictionary key Goal : Set the content of a file based on a dictionary value that I retrieve via  FACT.
In other words, I have  dictionary with like:
clients:
  client0:
    bar: my stuff

I learn the client name from a FACT, I would like to use the client name to index into the dictionary and retrive bar and set as the content of the file.
- name: Copy Client File Content
  copy:
    dest="/opt/myfile"
    content=clients[{{client_name}}].bar
    owner=root
    group=root
    mode=0600
    no_log: true

Expected Content of File is : my stuff

A: This works for me:
- hosts: localhost
  vars:
    clients:
      client0:
        bar: my stuff
    client_name: client0
  tasks:
    - name: copy client file content
      copy:
        dest: ./myfile.txt
        content: "{{clients[client_name].bar}}"

Your issue is that you appear to be trying to perform variable de-referencing outside of a Jinja2 variable substitution; putting everything inside {{...}} is what makes this work.


text:
Q: AngularJS 1.2.0 $resource response is empty I'm using AngularJS 1.2.0.
When I'm calling a webservice with $resouce the response variable is always empty. The webservice is called correctly and the webservice is sending the result to the browser. The problem is that (callback(response){}) response is always empty.
angular.module('app').factory('geoCoding',['$resource', function ($resource) {
return $resource('http://open.mapquestapi.com/geocoding/v1/address', {key: getGeoKey()}, {
    locate: {method: 'GET', isArray: false}
});
}]);

$scope.getLocations = function (locationName) {
    return geoCoding.locate({location: locationName}).$promise.then(
      function (response) {
        log.log('response ', response);
        if (response && response.data && response.data.results && response.data.results[0]) {

          var locations = [];

          response.data.results[0].locations.forEach(function (location) {
            locations.push({name: geoUtils.location2String(location), location: location});
          });

          return locations;
        } else {
          return {};
        }

      }, function (error) {
        log.error('Locations Query error: ', error);
      });
  };

A: Here are a few different approaches using 1.2.0rc1.
var app = angular.module('app', ['ngResource']);
app.factory('geoCoding',['$resource', function ($resource) {
  return $resource('response.json', {key: 123}, {
    locate: {method: 'GET', isArray: false}
  });
}]);

app.controller('MainCtrl', function($scope,geoCoding){
  // bind it directly to the async result
  $scope.locations = geoCoding.locate({location: "a location"});

  // use a function to trigger the request
  $scope.getLocations = function () {
    $scope.resp = geoCoding.locate({location: "a location"});
  };

  // use a function to trigger the request using the promise
  $scope.getLocationsAlt = function() {
    geoCoding.locate({location: "a location"}).$promise.then(function(response){
      $scope.respAlt = response;
    }, angular.noop);
  };
});

Updated based on comment
It looks like the problem you are facing is that the data is coming back in an unexpected format. Here is what the updated code would look like (http://plnkr.co/edit/xzZHvm?p=preview):
var app = angular.module('app', ['ngResource']);
app.factory('geoCoding',['$resource', '$http', '$log', function ($resource, $http, $log) {
  return $resource('http://open.mapquestapi.com/geocoding/v1/address', {}, {
    locate: {method: 'GET', isArray: true, transformResponse: $http.defaults.transformResponse.concat(function(data, headersGetter) {
      // probably be better if you examined the results in here
      $log.info(data.results[0]);
      return data.results[0].locations;
    })}
  });
}]);
app.controller('MainCtrl', function($scope, $log, geoCoding){
  $scope.locations = geoCoding.locate({location: "Dallas, TX"});
});

A: I've created a plunker which shows $resource callbacks being logged working with similar code to yours here:
http://plnkr.co/edit/o7hjbd3H2vl2LuHBjI8O?p=preview
When I used the URL you have above I got an ORIGIN error and the request wasn't being made successfully, so I've demonstrated with a response.json stub instead.

A: I appreciate all of you for the help, and probably I'm saying the same thing, but the truth is, I can't do it right yet. I fixed my errors and at this moment, my code doesn't have errors but all my page disappeared. I don't understand if I am opening the api already or simply it's not working. I'll send my .js code to create a little discussion about it.
Thanks for your help.
'use strict';
angular.module('SiteApp', [])
.controller('LoginCtrl', ['$scope', '$location', '$http', function ($scope, $http) {
    $scope.user = {username: '', password: ''};
$scope.go = function() {
    $http.jsonp('http://beta.cloogy.com:6969/api/1.0', {
          data : {
            User: user.username,
            Password: user.password
          }
      })
    .success(function (data) {
      $scope.$parent.image = data;
      $location.path('/Index'); //this is a simply second view to test
    })
    .error(function (data) {
      $scope.msg="Error loading the page!";
    });
}

}
]);


text:
Q: Count number of files within a directory in Linux? To count the number of files in a directory, I typically use
ls directory | wc -l

But is there another command that doesn't use wc ?

A: this is one:
ls -l . | egrep -c '^-'

Note:
ls -1 | wc -l

Which means:
ls: list files in dir
-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|: pipe output onto...
wc: "wordcount"
-l: count lines.


text:
Q: Electron-Builder: Failed building windows installer with squirrel on MacOS I have searched after a solution to build a windows installer on MacOS with squirrel, but without any luck.
I have successfully installed mono via my terminal.
Version 6.4.0.198.
Versions:

electron: ^4.2.5
electron-builder: ^20.41.0
electron-builder-squirrel-windows: ^20.44.0

I run the command npm run build:win, after a bit of packaging this error comes up

Error: Exit code: 255. Command failed: mono /Users/admin/Library/Caches/electron-builder/Squirrel.Windows/Squirrel.Windows-1.9.0/Update-Mono.exe --releasify /Users/admin/Desktop/myTestBuild/dist/squirrel-windows/mytestbuild-1.0.0-full.nupkg --releaseDir /Users/admin/Desktop/myTestBuild/dist/squirrel-windows
  2019-10-05 18:55:36> Unhandled exception: System.ComponentModel.DataAnnotations.ValidationException: Description is required.
    at NuGet.Manifest.Validate (NuGet.Manifest manifest) [0x000b1] in <64ead1da9ab54e29ae45ecd50faea709>:0
    at NuGet.Manifest.ReadFrom (System.IO.Stream stream, NuGet.IPropertyProvider propertyProvider, System.Boolean validateSchema) [0x0007b] in <64ead1da9ab54e29ae45ecd50faea709>:0
    at NuGet.Manifest.ReadFrom (System.IO.Stream stream, System.Boolean validateSchema) [0x00006] in <64ead1da9ab54e29ae45ecd50faea709>:0
    at NuGet.LocalPackage.ReadManifest (System.IO.Stream manifestStream) [0x00000] in <64ead1da9ab54e29ae45ecd50faea709>:0
    at NuGet.ZipPackage.EnsureManifest () [0x00050] in <64ead1da9ab54e29ae45ecd50faea709>:0
    at NuGet.ZipPackage..ctor (System.String filePath, System.Boolean enableCaching) [0x00049] in <64ead1da9ab54e29ae45ecd50faea709>:0
    at NuGet.ZipPackage..ctor (System.String filePath) [0x00000] in <64ead1da9ab54e29ae45ecd50faea709>:0
    at Squirrel.Update.Program.ReleasifyElectron (System.String package, System.String targetDir, System.String baseUrl) [0x0000d] in <64ead1da9ab54e29ae45ecd50faea709>:0

Hope someone can help me, have a great day.

A: Finally found a solution!
your "description" in package.json cannot be empty. That is why it says

Description is required. at NuGet.Manifest.Validate........

This should definitely be added to docs of electron-builder and/or electron-builder-squirrel-windows.


text:
Q: WordPress - prevents server from sending mails and wp_mail does't work? Why WP prevent me from sending mail?
I created a file mail.php and tested the PHP mail():
$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" . "\r\n" .
"CC: somebodyelse@example.com";

mail($to,$subject,$txt,$headers);

I uploaded it my server, in the root directory. I run it and I received emails with that.
But when I use
$message = trim($_POST['sender_message']);
$email = trim($_POST['sender_email']);

//php mailer variables
$to = get_option('admin_email');
$subject = "Someone sent a message from ". get_bloginfo('name') . ": " . $subject;
$headers = 'From: '. $email . "\r\n" .
  'Reply-To: ' . $email . "\r\n";

// $sent = wp_mail($to, $subject, strip_tags($message), $headers);
$sent = mail($to, $subject, strip_tags($message), $headers);
var_dump($send); // bool true
if($sent) {
 // do something
}

I get bool true in the var_dump check. But I never received any email from my server.
Any ideas? Have I missed something to configure in WP?
EDIT:
The server won't send any email from yahoo accounts! Why???
$to = "xxx@yahoo.co.uk"; // works!
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: bbb@yaho.co.uk" . "\r\n" . // won't work!
"CC: lau.tiamkok@gmail.com";

mail($to,$subject,$txt,$headers);


text:
Q: Multi-threading in Qt problematic? I have been learning Qt for a while and a few days ago I decided to go on multi-threading by QThread. I have been following this person. Since he says that subclassing QThread is not the appropriate way but by using QObject is. I am following his method. But he has created another class which inherits from QObject. I decided to make a few changes:
class myclass
{
private:
    dowork();

private slots:
    slota();
    slotb();
    slotc();
}

myclass::dowork()
{
    QThread lett;
    QThread latt;
    QThread pltt;
    QObject lethread;
    connect(&lett, SIGNAL(started()), this, SLOT(slota()));
    lethread.moveToThread(&lett);
    QObject lathread;
    connect(&latt, SIGNAL(started()), this, SLOT(slotb()));
    lathread.moveToThread(&latt);
    QObject plthread;
    connect(&pltt, SIGNAL(started()), this, SLOT(slotc()));
    plthread.moveToThread(&pltt);

    lett.start();
    latt.start();
    pltt.start();/*
    lett.wait();
    latt.wait();
    pltt.wait();*/
    while(lett.isRunning())
    {
        //qDebug() << "Still Running!";
    }
    lett.quit();
}

If I run the program it keeps running while loop infinitely! It doesn't come out of that at all.
I used qdebug inside the implementation of the 3 slots to check whether it is entering them or not, and surprisingly none of the slots gets called. Why is that so?
If I remove the comments for .wait then the program pauses.
What is wrong in this method? I want to avoid that extra class as my program is very small.

A: while(lett.isRunning())
{
    //qDebug() << "Still Running!";
}
lett.quit();

Terribly wrong. The current thread is busy waiting and will be eating all the time. But this is not your problem. Your problem is certainly that the main event loop has probably not started yet, ie you didn't do QApplication.exec() yet.
Qt uses events to start threads, and when you do use movetoThread, start, specific events are queued in the current thread (ie the thread executing these methods). If the main event loop has already started, then will be processed as soon as they can. But in your case I bet that you main function is :
 int main(){
   QApplication app();
   myclass onlyclassIwanttomake;
   onlyclassIwanttomake.dowork();
   app.exec(); <----HERE!!!
 }

The thread will be started when the main thread executes app.exec();. When you are busy waiting, you are preventing the main thread to process the events required to start your
events.
EDIT: Well, another issue is that
lett.start();
latt.start();
pltt.start();

start 3 threads which are started, and stay idle forever. They are not doing anything, but they are running (even if you remove your loop).
This is a entry written about Qt threading. Please take the time to read it.


text:
Q: Push to next View on button click from SwiftUI View which is inside UITableView Cell I have one view named WelcomeView in SwiftUI which is having next button. so on click of next button I want to push my view to other view using NavigationLink.
Problem that I am facing is I have to render my WelcomeView inside UITableView Cell in Swift file. so when I render that page inside UITableView Cell, and click on join button it is pushing my view to next view but inside UITableViewCell only.
I want to show my next view in whole page and not inside table cell.
TableFile (Swift)
 public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

   let cell = theTableview.dequeueReusableCell(withIdentifier: "SessionCardCell", for: indexPath) as! HostingTableViewCell<WelcomeView>

  cell.host(WelcomeView(), parent: self)

  return cell

}

Cell Class

class HostingTableViewCell<Content: View>: UITableViewCell {

    private let hostingController = UIHostingController<Content?>(rootView: nil)

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        hostingController.view.backgroundColor = .clear
    }

    override func sizeThatFits(_ size: CGSize) -> CGSize {
        return CGSize(width: ScreenSize.width, height: 100 * ScreenSize.width/375)
        // return hostingController.sizeThatFits(in: CGSize(width: ScreenSize.width, height: 250))
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        hostingController.view.frame.size = CGSize(width: ScreenSize.width, height: 100 * ScreenSize.width/375)//self.sizeThatFits(bounds.size)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func host(_ view: Content, parent: UIViewController) {

        self.hostingController.rootView = view
        self.hostingController.view.invalidateIntrinsicContentSize()

        let requiresControllerMove = hostingController.parent != parent
        if requiresControllerMove {
            parent.addChild(hostingController)
        }

        if !self.contentView.subviews.contains(hostingController.view) {
            self.contentView.addSubview(hostingController.view)
            hostingController.view.translatesAutoresizingMaskIntoConstraints = false
            hostingController.view.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor).isActive = true
            hostingController.view.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor).isActive = true
            hostingController.view.topAnchor.constraint(equalTo: self.contentView.topAnchor).isActive = true
            hostingController.view.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor).isActive = true
        }

        if requiresControllerMove {
            hostingController.didMove(toParent: parent)
        }
    }
}

WelcomeView (SwiftUI root View)
struct WelcomeView: View {

 @State var pushToNextScreen : Bool = false

 var body: some View {
     NavigationView {
        VStack {
            Button {
                //action
                self.pushToNextScreenRoot = true
            } label: {
                Text("Join")
           }

           NavigationLink(destination: SecondView(), isActive: self.$pushToNextScreenRoot) { }

        }//vstack
     }//navigation view
  }
}


text:
Q: rbind and cbind commands equivalent in SPSS can someone provide and equivalent code in SPSS that merges datasets in SPSS to replicate the rbind and cbind commands usable in R ? Many thanks !

A: To add rows from dataset1 to dataset2, you can use ADD FILES. This requires that both datasets hold the same variables, with matching variable names and formats.
To add columns from dataset1 to dataset2, use MATCH FILES. This command matches the values for the desired variables in dataset2 to the right rows in dataset1 using keys present in both files (such as a respondent id). The keys are defined in the BY subcommand.
Please note that R and SPSS work in a totally different way. In short, SPSS (mainly) works with datasets in which variables are defined and formatted, while R can handle single values, vectors, matrices, dataframes etc. Simply copying columns from an existing dataset to another dataset (without paying attention tohow the files are sorted) and  simply adding rows without matching the variable names and types in the existing dataset are very unusual in SPSS.
If you post an example of what you are trying to achieve, I could give you a more useful answer...


text:
Q: How to extract the the data with delimiter I am parsing the csv file using while loop in shell script which has data in below format
ba04ba54,1234,MMS,"[""some"", ""somet2"", ""somet""]",21556,48834

code:
while IFS=, read -r id mvid conkey values cretime modified;
do
echo $id,$mvid,$conkey,$values,$cretime,$modified

but values is assigned with
"[""some""

instead of
"[""some"", ""somet2"", ""somet""]" how to achieve this using shell script

A: Could you please try following.
awk 'match($0,/\"\[\".*\]\"/){print substr($0,RSTART,RLENGTH)}' Input_file


text:
Q: Which plugin is contributing Java perspective? I wanted to know which plugin is contributing Java perspective in eclipse?
And does the same plugin contribute the Create new Java project? If not which plugin contributes it?

A: The org.eclipse.jdt.ui plugin provides the java perspective
See the plugin.xml inside the plugin:
<extension
     point="org.eclipse.ui.perspectives">
  <perspective
        name="%perspectiveName"
        icon="$nl$/icons/full/eview16/jperspective.gif"
        class="org.eclipse.jdt.internal.ui.JavaPerspectiveFactory"
        id="org.eclipse.jdt.ui.JavaPerspective">
     <description>
        %java.perspective.description
     </description>
  </perspective>

You can also often use the plugin spy if you want to know from which plugin a UI component comes.
For example open the "Create a Java Project" dialog and press Shift + Alt + F1

A:
I wanted to know which plugin is contributing Java perspective in eclipse?

All the Java related things in Eclipse goes into plugins namely: org.eclipse.jdt.*. You can look through it for more details.

contribute the Create new Java project

The class responsible for creating Java project is JavaProjectWizard under org.eclipse.jdt.ui plugin.
In-fact you can get information on any Plugin using in-built Eclipse Plugin Spy using Alt + Shift + F1.

A: Java Perspective is contributed by org.eclipse.jdt.ui and it includes the New Java Project. Recently discovering these things has been greatly simplified: for example, if you create an extension for org.eclipse.ui.perspectiveExtensions via the Extensions tab of the rich editor for plugin.xml, you'll have a Browse... button next to the targetID text box, where you can search for the perspective by its user-readable name. Similar for many other extension points.


text:
Q: Pygame ship movement only Up & Down (left right is working) This part is gamefunction.py file
import sys

import pygame

def check_keydown_events(event,ship):
    """Respond to the keypressess."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_UP:
        ship.moving_up = True
    elif event.key == pygame.K_DOWN:
        ship.moving_down = True

def check_keyup_events(event, ship):
    """Respond to the keyreleases."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False
    elif event.key == pygame.K_UP:
        ship.moving_up = False
    elif event.key == pygame.K_DOWN:
        ship.moving_down = False

def check_events(ship):
    """Respond to keypresses and mouse events."""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event,ship)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)

this is named ship.py
import pygame

class Ship():

    def __init__(self,ai_settings,screen):
        """Initialize the ship and set its starting position."""
        self.screen = screen
        self.ai_settings = ai_settings
        #Load the ship image and get its rect.
        self.image = pygame.image.load('images/ship.png')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        #Start each new ship at the bottom center of the screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        #Store a decimal value for the ship's center.
        self.center = float(self.rect.centerx)
        #Movement Flags
        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False

    def update(self):
        """Update the ship's position based on the movement flag."""
        #Update the ship's center value, not the rect
        if self.moving_right and self.rect.right<self.screen_rect.right:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left>0:
            self.center -= self.ai_settings.ship_speed_factor
        #Up-dwon motion added ***Please check the logic for 1200x800 screen***
        if self.moving_up and self.rect.top<self.screen_rect.top:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_down and self.rect.bottom>800:
            self.center -= self.ai_settings.ship_speed_factor

        #Update rect object from self.center.
        self.rect.centerx = self.center

A: Source: Python Crash Course
Just a few tweeks in ship.py:
Under self.center = float(self.rect.centerx), add self.bottom = float(self.rect.bottom) and change:
if self.moving_up and self.rect.top<self.screen_rect.top:
    self.center += self.ai_settings.ship_speed_factor
if self.moving_down and self.rect.bottom>800:
    self.center -= self.ai_settings.ship_speed_factor

to:
if self.moving_up and self.rect.top<self.screen_rect.top:
    self.bottom -= self.ai_settings.ship_speed_factor
if self.moving_down and self.rect.bottom<800:
    self.bottom += self.ai_settings.ship_speed_factor

and finally under self.rect.centerx = self.center, add self.rect.bottom = self.bottom.
This should make you be able to go up and down in your game!

A: Here is a problem I spotted, in these functions:
check_keydown_events
check_keyup_events
check_events

In each of these cases, you are doing if-elif-elif-elif statements. This means when the if statement is True, the elif statements will not run.
In your case, if the left or right keys are pressed, you will never be able to move up or down.
You should change this code so that you only use if-elif with the up/down and left/right movement separately.
Here is one (corrected) example:
if event.key == pygame.K_RIGHT:
    ship.moving_right = True
elif event.key == pygame.K_LEFT:
    ship.moving_left = True
if event.key == pygame.K_UP:
    ship.moving_up = True
elif event.key == pygame.K_DOWN:
    ship.moving_down = True

Your problem will be fixed if you change each if-elif-elif-elif statement to if-elif-if-elif.

A: Ship.py
.....
self.bottom = float(self.rect.bottom)
self.moving_up = False
self.moving_down = False

def update(self):
    .....
    # check if the ship is moving up and stop the ship to move up if
    # it's top edge position is less than
    # screen's top (top right corner is 0,0) position
    if self.moving_up and self.rect.top > self.screen_rect.top:
        self.bottom -= self.ai_settings.ship_speed_factor

    # check if the ship is moving down and stop the ship when it's
    # bottom position is greater than the screen bottom edge position.
    if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
        self.bottom += self.ai_settings.ship_speed_factor

    self.rect.bottom = self.bottom

game_function.py
def check_keydown_event(event, ship):
    """Respond to keypresses"""
    ....
    elif event.key == pygame.K_UP:
        ship.moving_up = True
    elif event.key == pygame.K_DOWN:
        ship.moving_down = True

def check_keyup_event(event, ship):
    ....
    elif event.key == pygame.K_UP:
        ship.moving_up = False
    elif event.key == pygame.K_DOWN:
        ship.moving_down = False


text:
Q: Retrieving a list of blog posts with related tags with less query image this two tables:
Table: Item
Columns: ItemID, Title

Table: Tag
Columns: TagID, ItemID, Title

Which is the best way (without changing table structure (yes, I don't mind if they are not normalized)) to retrieve a list of items with all their tags attached using less possible query (i.e. not doing 11 queries to retrieve 10 items)?

A: Here's a simple outer join.  Is that what you are after?
SELECT
  It.ItemID,
  It.Title [ItemTitle],
  Tg.TagID,
  Tg.Title [TagTitle]
FROM Item It
LEFT OUTER JOIN Tag Tg
ON It.ItemID = Tg.ItemID

A: I'm not entirely sure what you're after, but does this help?
select Item.ItemID, Item.Title, Tag.TagID, Tag.Title from Item, Tag
  where Item.ItemID=Tag.ItemID

When you say you don't want to do 11 queries, do you mean you don't want to do 11 SQL queries, or you don't want to receive your results in 10 rows? If the latter, then I think it really just means you need to loop through the results in whatever language you're using to call SQL. E.g., in PHP:
$query = "select Item.ItemID as i, Item.Title as t1, Tag.TagID as t, Tag.Title as t2 from Item, Tag where Item.ItemID=Tag.ItemID";
$dataset = mysql_query($query) or die(mysql_error());

$items = Array();

while ($data = mysql_fetch_assoc($dataset))
{
  $items[$data['i']] = Array($data['t1'], $data['t'], $data['t2']);
}


text:
Q: FLUTTER -Turn on and Turn off your device Is there any way to schedule the time to turn on your phone from flutter app on android and ios?

A: In Android there is a way to bring up the shutdown dialog as mentioned in this SO thread. However, iOS apps have no way of achieving this as the only way to perform a shutdown is through physically holding down the power button for about 10 seconds and sliding a slider to the left.
So to answer your question: no, you cannot do that across platforms.


text:
Q: Retrieve Entire SAML Response in Spring Security SAML Extension I have a Spring Boot application that is setup as a Service Provider. My end goal is to be able to call the AWS STS Assume Role with SAML service to generate AWS temporary credentials on behalf of the user with the SAML response used to initially authenticate users of my application.
I found this other question. With that answer I am able to get only the assertion, not the entire response. From my testing, the AWS API call linked above wants the entire response, not just the assertion piece.
I used this Chrome Extension to view the SAML response. When I include everything (outline below)
<samlp:Response>
   ...
   <saml:Assertion>
       ...
   </saml:Assertion>
</samlp:Response>

The AWS STS Assume Role with SAML works. The other related question's answer only provides me the
<saml:Assertion>...</saml:Assertion>
block and the AWS STS Assume Role with SAML fails.
So my question is how do I get the entire SAML Response XML object back in a controller of my Spring Boot application?

A: I don't know any direct way in spring-security-saml, but maybe you could try to  implement your own SAMLProcessingFilter ie simply extending the existing one and overriding the method attemptAuthentication().
Principle:

*

*In this method, you have access to the response returned from the IdP and post back to the SP (at least in a Redirect-POST profile)

*You probably have a way to extract what you need from the httpRequest

*Then you can store (session, ThreadLocal variable, ...)

*And finally you delegate the authentication process to the parent (by calling super.attemptAuthentication())

`
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if ("POST".equalsIgnoreCase(request.getMethod())) {
        String samlResponse = request.getParameter("SAMLResponse");
        System.out.println("Original SAML Response (base64 decoded) : " + new
        String(Base64.getDecoder().decode(samlResponse), StandardCharsets.UTF_8));
    }
    return super.attemptAuthentication(request, response);
}

`


text:
Q: Give preference to AWS change with Terraform I have this simple Cloudfront configuration:
resource "aws_cloudfront_distribution" "s3_distribution" {
  ...
  origin {
    domain_name = <bucket domain name>
    origin_id   = <origin id>
    origin_path = /path/1
  }
  ...
}

If I run terraform apply it creates the CloudFront distribution as it should. But after I created it, a Continuous Deployment pipeline is changing its origin_path from /path/1 to /path/<another number>.
If I make any change on this distribution and update it with terraform apply, the origin_path goes back to /path/1 and breaks the environment. Is there any way to avoid this?
For example:
resource "aws_cloudfront_distribution" "s3_distribution" {
  ...
  origin {
    domain_name = <bucket domain name>
    origin_id   = <origin id>
    origin_path = creationOnly("/path/1")
  }
  ...
}

And creationOnly would update origin_path only if the resource is being created.
Edit:
Thanks to Helder and Mark in the comments I figured out lifecycles would be a possible solution. Sadly, even though I used a resource on my example, the real problem involves a module.


text:
Q: How to check if string contains a certain substring like [3:0] I am working on a project where i need to search for a particular string token and find if this token has the [3:0] format of number, how can i check it? i searched for reference on stack overflow, i could find how to search "{my string }:" in a string like the following:
String myStr = "this is {my string: } ok";
if (myStr.trim().contains("{my string: }")) {
    //Do something.
}

But, could not find how to search if a string contains a number in the regular expression, i tried using the following, but it did not work:
String myStr = "this is [3 string: ] ok";
if (myStr.trim().contains("[\\d string: ]")) {
    //Do something.
}

Please help!

A: for "[int:int]" use \\[\\d*:\\d*\\]  it's working

A: You cannot use a regex inside String#contains, instead, use .matches() with a regex.
To match [3 string: ]-like patterns inside larger strings (where string is a literal word string), use a regex like (?s).*\\[\\d+\\s+string:\\s*\\].*:
String myStr = "this is [3 string: ] ok";
if (myStr.matches("(?s).*\\[\\d+\\s+string:\\s*\\].*")) {
    System.out.println("FOUND");
}

See IDEONE demo
The regex will match any number of any characters from the start of string with .* (as many as possible) before a [+1 or more digits+1 or more whitespace+string:+0 or more whitespace+]+0 or more any characters up to the end of string.
The (?s) internal modifier makes the dot match newline characters, too.
Note we need .* on both sides because .matches() requires a full string match.
To match [3:3]-like pattern inside larger strings use:
"(?s).*\\[\\d+\\s*:\\s*\\d+\\].*"

See another IDEONE demo
Remove \\s*  if whitespace around : is not allowed.


text:
Q: Appropriate cookie domain for Django dev server running multiple sites I have multiple Django dev sites running locally like http://localhost:8000, http://localhost:8001, http://localhost:8002, etc.
Originally, I had SESSION_COOKIE_DOMAIN and CSRF_COOKIE_DOMAIN set to '' or 127.0.0.1 but this causes each site to overwrite the other's cookies, causing me to have to login every time I switch between sites. I tried using 127.0.0.1:<port> but that had no effect.
How do I get these sites to use separate cookies?

A: One solution to this problem is to use local domain name resolution to reach each of your different development servers.  If you leave SESSION_COOKIE_DOMAIN as None, then the returned cookie is a standard domain cookie and will have the same domain as the request.
Have a look at http://en.wikipedia.org/wiki/Hosts_(file) which describes how to add local host file entries.
With a hosts file like this:
127.0.0.1 www.testserver1.com www.testserver2.com

You could then access each of your different test servers at:
http://www.testserver1.com:8000
http://www.testserver2.com:8001

I haven't tried this, but I believe it should work.
Alternatively, as per Mikhail's answer, use a different session cookie name for each instance.

A: Cookies are shared across ports for the same domain according to various RFCs (see e.g. https://www.rfc-editor.org/rfc/rfc6265#section-8.5). So this is not django-specific.
I think you could use different SESSION_COOKIE_NAME to have at least sessions separated.


text:
Q: Trying to access labels from UIView I have created a .xib file that has a bunch of labels in it to be used with SwipeView . My problem is that I can't/don't know how to access and change their text after loading the view:
let newView = NSBundle.mainBundle().loadNibNamed("SwipeHelperView", owner: self, options: nil)[0] as UIView

for (var subview) in newView.subviews
{
    if (subview.isKindOfClass(UILabel) && subview.tag == 0)
    {
        subview.text = "asdaS" //ERROR: cannot assign 'text' in 'subview'
    }
}

Would it be easier to create the labels on spot, something like this:
var label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(0, 0)
label.text = "some text"
newView.addSubview(label)

rather than trying to access them from the "newView" UIView ? Is there a 'recommended' way or it's about prefferences ?

A: You should cast it:
let newView = NSBundle.mainBundle().loadNibNamed("SwipeHelperView", owner: self, options: nil)[0] as UIView

for subview in newView.subviews as [UIView]
{
    if subview.tag == 0
    {
        if let label = subview as? UILabel {
            label.text = "asdaS"
        }
    }
}

If you set a custom tag (e.g 333) you can get it as it:
if let label = newView.viewWithTag(333) as? UILabel {
    label.text = "TEST"
}

A: Both ways are fine but depends on your goal that you want to achieve. You could do as follow :-

*

*You could create property and connect your label from xib. Later in your code you could change it's text as below:-
@IBOutlet var usernameLabel: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    self.usernameTxt?.text = "some text"
}

*You could programmatically create and add it to your view as subView. Code:-
var label = UILabel(frame: CGRectMake(FRAME))
label.text = "some text"
youView.addSubview(label)

A: it will be helpful if you make labels programmatically and add it in your newView.

var subview
   for subview:AnyObject in newView.subviews
   {

    if (subview.isKindOfClass(UILabel) && subview.tag == 0)
    {
     var label=subview as UILabel
     label.text="some text"
    }
   }


text:
Q: Second  in JS not working "Uncaught TypeError: Cannot set properties of null (setting 'onclick')" i wrote a JS code for my Website, which should show a modal and close it, if i click the "close" span. The first time, it worked perfectly. Here is the code:
var modal = document.getElementById("notifications");
var img = document.getElementById("shownotificationbar");
var span = document.getElementsByClassName("close")[0];

img.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

But the second time, the close button just dont work and i get
"Uncaught TypeError: Cannot set properties of null (setting 'onclick')"
Here is the second code piece:
var menu = document.getElementById("startmenu");
var img = document.getElementById("showstartmenu");
var span = document.getElementById("closemenu");

img.onclick = function() {
  menu.style.display = "block";
}

span.onclick = function() {
  menu.style.display = "none";
}

I think i can't use two spans, but what else should i do?
Thank you very much!

A: The second time img is null, so you cannot set img.onclick. The reason it is null is probably that there is no element with id showstartmenu, so when you are trying to get it (document.getElementById("showstartmenu")), you are getting null instead.
Edit:
Sorry, it could also be that span is null, for the same reason. I missed that one.