text:
Q: PHP 5.4 json_decode generates malformed json I do have an odd problem regarding PHP Array to JSON serialization:
I got an array of many layers and to a certain size, it works just fine. But at some point, the closing curly bracket is missing from the returned JSON object.
Here are the returned headers.
Date: Fri, 29 Dec 2017 12:42:39 GMT
Server: Apache/2.2.22 (Debian)
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, userid, dealerid
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
X-Powered-By: PHP/5.4.45
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 8503
X-UA-Compatible: IE=edge
Content-Type: application/json;charset=utf-8

The API is built using the SLIM 3 Framework for simple REST APIs.
Setup on the API:
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
...

public function listFailedOrders(Request $request, Response $response, array $args) {
  $arr = [];

  //algorithm to fill array
  //verified that the array has data that is not malformed in any way!

  $responseData = [];
  $responseData['count'] = count($arr);
  $responseData['data'] = $arr;

  $response = $response->withJson($responseData, 200);
  return $response;

}

Data Returned:

{
 "count": "41",
 "data": [
  {
           .... JSON DATA ....
  },
  {
           .... More JSON Data ....
  }
 ]
//Missing End curly Bracket

I use Insomnia Rest client to inspect this and until this point, my only solution to this problem is to add a closing curly bracket on the receiving end.
TLDR:
I serialize a big (not limit reaching object) to JSON but the trailing curly bracket is trimmed. Where does the problem originate from?

A: The issue was a preset Content Length Header which cut off the last curly bracket.
This was a bad mistake.


text:
Q: PHP mailer does not include body I have this form
<form method="POST" action="mailer.php">

<input type="email" name="email" class="email" placeholder="example@example.com">

</form>

And this PHP
<?php

$email = $_POST['email'];
$to = "test@test.com";
$subject = "ADD THIS EMAIL ADDRESS TO THE MAILING LIST";
$body = "\n\n";
$url = 'http://10.0.1.1/~ewiuf';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo '';
    echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL=' . $url . '">';
} else {
    if (mail($to, $subject, $body)) {
        echo '';
        echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL=' . $url . '">';
    } else {
        echo '';
        echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL=' . $url . '">';
    }
}
?>

Why is the contents of the form, which should be email addresses, not being included in the body of the emails which the script sends? The script sends, verifies, but the email address that the user enters into the form is not sent to me. Please Help, thanks.

A: you need to tell it to send you the email of the user.
try this:
<?php
$email = $_POST['email'];
$to = "test@test.com";
$subject = "ADD THIS EMAIL ADDRESS TO THE MAILING LIST";
$body = "User Email: ".$email;
$url = 'http://10.0.1.1/~ewiuf';
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo '';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
}
else
{
if (mail($to, $subject, $body)) {
echo '';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
 } else {
echo '';
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
 }
}
?>

A: $body = "\n\n"; is the only place you set or change the $body variable, which is the variable you send as the body (third parameter) to the mail function.
In your case, I assume you only want to put the e-mail address in the body, so you should use $body = $email; for that, or just use $email instead of $body as the third parameter to mail.

A: You are sending "\n\n" in $body.
If i get your question right, you might want to add $email to it, like
$body = "\n\n" + $email
hope that helps

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is causing this ArrayOutOfBoundsException in my array list? import java.util.*;
import java.util.ArrayList;

class MyHashTable<K extends Comparable<K>, E> {

    private ArrayList<Entry<K,E>> bucket = new ArrayList<Entry<K,E>>();
    private int bucketSize;
    private int collisionCount = 0;

    // Constructor that takes number of buckets as input
    public MyHashTable( int len )
    {
        this.bucketSize = len;
        for ( int i = 0; i < len; i++ )
        {
            bucket.set( i, null ); //ERROR APPEARS ON THIS LINE
        }
    }

and is evoked when I call from another method :
MyHashTable<MyString, AnimalRecord> linearProbing = new MyHashTable<MyString, AnimalRecord>(59);
linearProbing.put( lion.name, lion );

A: private ArrayList<Entry<K,E>> bucket = new ArrayList<Entry<K,E>>();

Creates an empty arrayList.
The set method

Replaces the element at the specified position in this list with the specified element
  Throws: IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

So
bucket.set( i, null );

tries to set null to the ith element (starting at 0). But the arraylist is empty, and that is why you get the exception.
What you want is the add method:
for ( int i = 0; i < len; i++ )
{
    bucket.add(null);
}

adds null to the end of the ArrayList.

A: You need to add not set at first sight.
Look at the doc of set() method

Throws:
  IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

You met with with the condition  index >= size()

A: Initially, the ArrayList is empty, when you create a new instance of it:
private ArrayList<Entry<K,E>> bucket = new ArrayList<Entry<K,E>>();

When you are calling the set method on the ArrayList, you are trying to replace an existing element, which is not found, because the list is empty.
You should use add, instead of set if adding the element to the list is what you want.

A: You ArrayList (bucket) doesn't have any elements in it - bucket.set replaces an element, it doesn't insert an element.
See http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#set(int,%20E)
Call ArrayList.add() instead as that will append an element to the end of the array.

A: Rather obvious I think, your ArrayList is created with default capacity (10), while you are trying to access indexes above it (up to 58).

A: Take a look at the Java-Documentation for the Class ArrayList and the method you are using:
The method set "Replaces the element at the specified position in this list with the specified element."
At the time of your method call you do not have an ArrayList with an Element 59. The initial size of an ArrayList constructed with ArrayList() Standard-Constructor is 10.
You could use a constructor ArrayList(int initialCapacity)
Find the documentation here:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html


text:
Q: Binding List to a Repeater I have a collection of generated custom controls that extend CompositeControl, defined as:
[PersistChildren(true)]
[ToolboxData("<{0}:ContractControl runat=server></{0}:ContractControl>")]
public class ContractControl : CompositeControl
{
    private int contractID = 0;
    private ContractTileControl tileControl = null;
    private ContractDetailControl detailControl = null;

    private HtmlGenericControl contractMainDiv = null;

    public int ContractID
    {
        get { return this.contractID; }
        set { this.contractID = value; }
    }

    public ContractTileControl TileControl
    {
        get { return this.tileControl; }
        set { this.tileControl = value; }
    }

    public ContractDetailControl DetailControl
    {
        get { return this.detailControl; }
        set { this.detailControl = value; }
    }

    public ContractControl()
    {
        this.contractMainDiv = new HtmlGenericControl("div");
        this.contractMainDiv.ID = "contractMainDiv";
        this.contractMainDiv.Attributes.Add("class", "contractMain");
    }

    #region protected override void OnPreRender(EventArgs e)
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        //CreateChildControls();
    }
    #endregion

    #region protected override void CreateChildControls()
    protected override void CreateChildControls()
    {
        base.CreateChildControls();
        if (tileControl != null)
        {
            this.contractMainDiv.Controls.Add(tileControl);
        }

        if (detailControl != null)
        {
            this.contractMainDiv.Controls.Add(detailControl);
        }
        this.Controls.Add(contractMainDiv);
        //base.CreateChildControls();
    }

    #endregion

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        CreateChildControls();
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnLoad(e);
        EnsureChildControls();
    }
}

Where ContractTileControl and ContractDetailControl are another custom controls derived from CompositeControl.
When I add them to a asp:PlaceHolder control set they render fine, but when I define a repeater like:
<asp:Repeater ID="myRepeater" runat="server" >
    <HeaderTemplate>

    </HeaderTemplate>

    <ItemTemplate>

<easit:ContractControl ID="contractControl" runat="server" />

    </ItemTemplate>
    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>

And bind them to it:
private void FillContractPlaceHolder()
    {

        List<ContractControl> controls = new List<ContractControl>();
        foreach(KeyValuePair<Customer, List<TFSContract>> pair in contractList)
        {
            Label customerNameLbl = new Label();
            customerNameLbl.ID = "customerNameLbl";
            customerNameLbl.CssClass = "customerName";
            customerNameLbl.Text = pair.Key.Name;
            contractListPlaceHolder.Controls.Add(customerNameLbl);

            foreach (TFSContract contract in pair.Value)
            {
                ContractStatusBarControl status = new ContractStatusBarControl();
                status.WidthPercent = GetFillPercent(contract.NumberOfTasks, contract.NumberOfFinishedTasks);

                string[] contractNameParts = Regex.Split(contract.Contract.Name, @"[A-Z]{3}-[0-9|A-Z]{2}-[0-9|A-Z]{2}", RegexOptions.IgnoreCase);

                ContractDetailControl detail = new ContractDetailControl();
                detail.ContractName = contractNameParts.Last();
                detail.DateStarted = contract.StartDate;
                detail.DateFinished = contract.FinishDate;
                detail.StatusBar = status;

                ContractTileControl tile = new ContractTileControl();
                Match match = Regex.Match(contract.Contract.Name, @"[A-Z]{3}-[0-9|A-Z]{2}-[0-9|A-Z]{2}", RegexOptions.IgnoreCase);
                if (match.Value.Length != 0)
                {
                    tile.ContractNumber = match.Value;
                }

                tile.ContractTasksFinished = contract.NumberOfFinishedTasks;
                tile.ContractTasksTotal = contract.NumberOfTasks;

                ContractControl contractControl = new ContractControl();
                contractControl.ContractID = contract.Contract.Id;
                contractControl.TileControl = tile;
                contractControl.DetailControl = detail;
                //contractListPlaceHolder.Controls.Add(contractControl);
                controls.Add(contractControl);
            }

        }

        myRepeater.DataSource = controls;
        myRepeater.DataBind();

    }

The table gets created, but only the non-composite part contractMainDiv of ContractControl gets rendered, as the Repeater insists that both tileControl and detailControl are null, even though they are properly set to instances of their respective types.

A: When the Repeater is data-bound, it creates an instance of the ItemTemplate for each item in the data-source, set its DataItem to the item from the data-source, and data-binds the children.
In this case, the item from the data-source is an instance of your ContractControl, and your ItemTemplate has no data-binding, so you'll end up with a blank instance of the ContractControl for each item you've added to the list.
The quick and dirty solution is to add a handler for the ItemDataBound event of your Repeater, and copy the properties to the real control:
protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   switch (e.Item.ItemType)
   {
      case ListItemType.Item:
      case ListItemType.AlternatingItem:
      case ListItemType.SelectedItem:
      case ListItemType.EditItem:
      {
         var source = (ContractControl)e.Item.DataItem;
         var destination = (ContractControl)e.Item.FindControl("contractControl");
         destination.ContractID = source.ContractID;
         destination.TileControl = source.TileControl;
         destination.DetailControl = source.DetailControl;
         break;
      }
   }
}

A better solution would be to bind your Repeater to a list of TFSContract objects, and moving the code to build the ContractControl into the ItemDataBound event handler.
EDIT
Updated to only process real items, ignoring headers, footers, etc.


text:
Q: X-editable Datepicker + Bootstrap 3? I am looking at X-editable what looks pretty cool but I am not sure if it is being updated anymore(Nov 2013 was last update).
It apparently does not support the date picker option. I am wondering if anyone knows of an alternative to X-editable or a fork that has a working date picker.

A: You can use Bootstrap 3 datetimepicker for date picker. This is really nice and can also have TIME picker if you want. And is working in all the browsers including IE.


text:
Q: Django UniqueConstraint usecase I have the model users and Address with the Address model containing the user as a Foreign key. Is it possible to handle this use case with constraints that in case of multiple users addresses a user can have one default address? Here is a sample code.
Thank you.
class User(models.Model):
    name = models.CharField(max_length=10)
class Address(models.Model):
    address = models.CharField(max_length=10)
    active=models.BooleanField(default=False)
    user = models.ForeignKey(
    User,
    blank=False,
    null=False,
    related_name="user_address", on_delete=models.CASCADE)
    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['user', 'active'],
                                condition=models.Q(active=True),
                                name='user default address.')
        ]

A: You have to adjust your UniqueConstraint slightly
  constraints = [
            models.UniqueConstraint(fields=['user'],
                                condition=models.Q(active=True),
                                name='unique_active_address')
        ]

EDIT:
Seems you are using MySQL and as documented

The condition argument is ignored with MySQL and MariaDB as neither
supports conditional indexes.

You cannot enforce this on database level with unique Index on MySQL as it does not support conditional indexes


text:
Q: Calling asp net button click event with JS will not call server side event Sorry to post perhaps a silly problem here, but I'm at my wits end with it. I have a hidden field with a button inside an update panel like so:
<asp:UpdateProgress runat="server" ID="updprCompLines" AssociatedUpdatePanelID="updpanCompLines">
        <ProgressTemplate>
             </ProgressTemplate>
        </asp:UpdateProgress>

        <asp:UpdatePanel runat="server" ID="updpanCompLines" UpdateMode="Conditional">

            <%--<Triggers>
                <asp:AsyncPostBackTrigger ControlID="btnFillMembers" />
            </Triggers>--%>

            <ContentTemplate>

                <asp:HiddenField ID="hdnField" runat="server" />
                <asp:Button ID="btnFillMembers" runat="server" style="display:none;"
                    Text="DummyButton" onclick="btnFillMembers_Click"  />

The update panel also contains a gridview and inside my gridview I have a link button:
 <ItemTemplate>
     <asp:LinkButton ID="lkbtBenefName" runat="server" Text='<%#Eval("COMPETENCE_CODE") %>'
      OnClientClick='<%#Eval("COMPETENCE_LINE_ID", "return SelectedCompetence({0})") %>'/>
 </ItemTemplate>

The call is to a JS function that is supposed to call the above button:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" EnablePageMethods="true"/>

Button click event method:
protected void btnFillMembers_Click(object sender, EventArgs e)
{
    lblGvMemError.Text = "";
    lblGvMemError.ForeColor = Color.Red;

    if (hdnField.Value != null || hdnField.Value.ToString() != "")
    {
        try
        {
            int CompLineId = Convert.ToInt32(hdnField.Value);
            GetSelectedCompLineMembers(CompLineId);
        }
        catch (Exception ex)
        {
            lblGvMemError.Text = "Error: " + ex.Message;
        }
    }

    updpanCompLinesMembers.Update();
}

The problem is that while debugging, it never runs the click event and it doesn't give any error messages either. I don't understand, I have a similar form where this works; I don't get why it doesn't here... Any help please?

A: Have you confirmed that SelectedCompetence is being called via an alert or similar?  Additionally, have you made sure that the clickButton variable is being assigned to successfully?
I know this isn't an answer, but don't yet have the reputation to comment, and sometimes it's the easy stuff so maybe this will help! :)


text:
Q: Android multi-touch feature (up to 6 touches) I want to know if it is possible to make an android application that features up to 6 touches simultaneously with the multi-touch option (not just two). Please can u help me to find some relevant literature. I've found some answers here on stackoverflow, but i am afraid that that's not enough.
I would appreciate every help. Thank you all in advance.

A: Devices that support "jazzhands" will handle up to 10 simultaneous touches. Your app can require jazzhands support via the following manifest element:
<uses-feature android:name="android.hardware.touchscreen.multitouch.jazzhand" />

Not all devices will support this -- for example, the Kindle Fire only supports two simultaneous touches IIRC.

A: There is no software difference between 2 or 6 touches (except for the permission), it is hardware related and if you can't use more of 2 fingers then you should try on another device.
Anyway, if you want good multitouch litterature, have a look here:
Making sense of multitouch (android-developers.blogspot.fr)


text:
Q: Register Master Account - incorrect token I am getting the following error trying to register UserFrosting's master account:

Sorry, that configuration token is not correct.

The only thing I managed to capture is
Failed to load resource: the server responded with a status of 403 (Forbidden)

I did see some discussions on this topic, but so far no mention of any solutions.


text:
Q: StreamWriter encoding string incorrectly I'm trying to append a base64 string to an existing file. Here's my code:
StreamWriter output = new StreamWriter(file, true, Encoding.ASCII);
output.WriteLine(output.NewLine + str);

Here file is the file path.
For some reason, there is one particular file (a .cs file, if it matters) where the actual text that gets appended is a string of Chinese characters. It works as expected for all the other files I've tested.

A: Following the multiple suggestions in the comments, I replaced Encoding.ASCII with the file's encoding, which I look up using 2Toad's answer here. That solved the problem.


text:
Q: Intersection of several sets of results corresponding to different events in matlab I have a matrix (5x10000) with the fifth line contains values between 1 and 50 corresponding to different events of an experiment. My goal is to find the columns of the matrix which are the same for different events. In other words, I want the columns results for all possible combinations of different events (subsets of {1,2, .., 50}) (For example: {1,3,7} and {7,1,3} are of course the same combination).
It sounds like a problem of intersection of sets that each contains all possible outcomes for a given event. I hope also that the computation time is reasonable.
example with a matrix (5x20):
A =
20     4     4    74    20    20     3     1     1     4     3     3     3     7     4     1    20     3     3    74
36     1     1    11    36    36     3     3     3     1     3     3     3     9     4     3    36     4     3    11
77     1     1    15    77    77     1     3     3     1     1     1     1    10     3     2    77     4     1    15
 9     4     4    40     9     9     2     4     4     4     2     2     2    40     1     4     9     3     2    40
 3     4     2     6     7     3     4     5     2     7     4     2     7     6     7     2     5     5     1     3

in this case we have seven different events from 1 to 7: line 5
for example:
the intersection of the results of events 3, 5 and 7 is the vector: [20 36 77 9]'
the intersection of the results of events 1, 2, 4 and 7 is the vector: [3 3 1 2]'
the intersection of the results of events 3 and 6 are the vectors: [20 36 77 9]' and [74 11 15 40]'
So what I want is the common columns for a specified number of different events between 1 and 50. For example, how to get the columns common to 20 different events? The problem becomes more complicated for me when I think to find this result for all possible combinations of 20 events in the set {1,2,..., 50}.
I want the common columns for all possible combination for a given number of different events, but I gave the number 20 just as an example on which to base one solution.
I'll rephrase my question that to make it clearer:
the following matrices are sub-matrix of A, each corresponding to a given event:
A1= [3;3;1;2;1]
A1 corresponds to results of the event 1
A2= [4 1 3 1;1 3 3 3;1 3 1 2;4 4 2 4;2 2 2 2]
A2 corresponds to results of the event 2
A3= [20 20 74;36 36 11;77 77 15;9 9 40;3 3 3]
A3 corresponds to results of the event 3
A4= [4 3 3;1 3 3;1 1 1;4 2 2;4 4 4]
A4 corresponds to results of the event 4
A5= [1 20 3;3 36 4;3 77 4;4 9 3;5 5 5]
A5 corresponds to results of the event 5
A6= [74 7;11 9;15 10;40 40;6 ]6
A6 corresponds to results of the event 6
A7= [20 4 3 4 7;36 1 3 4;77 1 1 3;9 4 2 1;7 7 7 7]
A7 corresponds to results of the event
my goal is to find intersection along the columns of the matrix Ai (1:4,:) i = 1,2, ... 7
in other words:
intersection(Ai,Aj)(1:4,:) for i and j different
intersection(Ai,Aj,Ak)(1:4,:) for i,j and k different
intersection(Ai,Aj,Ak,Al)(1:4,:) for i,j,k and l different
intersection(Ai,Aj,Ak,Al,Am)(1:4,:) for i,j,k,l and m different
intersection(Ai,Aj,Ak,Al,Am,An)(1:4,:) for i,j,k,l,m and n different
intersection(Ai,Aj,Ak,Al,Am,An,Ao)(1:4,:) for i,j,k,l,m,n and o different
intersection(Ai,Aj,Ak,Al,Am,An,Ao,Ap)(1:4,:) for i,j,k,l,m,n,o and p different
when I say "intersection (Ai, Aj)(1:4,:) for i and j different," I want the columns common to the matrix Ai(1:4,:) and Aj(1:4,:)
the result for each intersection can be many column vectors, not necessarily one, depending on the columns of the matrix A.
I hope that each result contains the vector column of the matrix Ai(1:4,:) followed by the corresponding values of events, such as: if [3 3 1 2]' is the intersection of A1, A2, A4 and A7, I want to get as a result the vector [3 3 1 2 1 2 4 7]'
for example: intersection(A1,A2,A3,A4)(1:4,:): my goal is to avoid the following loop:
[n1 m1] = size(A1);
[n2 m2] = size(A2);
[n3 m3] = size(A3);
[n4 m4] = size(A4);

k=1;

for i1=1:m1
    for i2=1:m2
        for i3=1:m3
            for i4=1:m4
                if A1(1:4,i1)==A2(1:4,i2) && A2(1:4,i2)==A3(1:4,i3) && A3(1:4,i3)==A4(1:4,i4)
                    intersection1234(:,k) = [A1(1:4,i1);A1(5,i1);A2(5,i2);A3(5,i3);A4(5,i4)];
                    k=k+1;
                end
            end
        end
    end
end

A: Can't tell for certain without an example input and desired output, but I believe this is what you're trying to do:
n = 1e4

tic

% Simulate data
% (Here we've split off the 5th row into a separate variable)
data = randi(5, [4 n]);
exptEvents = randi(50, 1, n);

% Find repeats
[b,i,j] = unique(data', 'rows');

% Organize the indices of the repeated columns into a cell array
reps = arrayfun(@(x) find(j==x), 1:length(i), 'UniformOutput', false);

% Find events corresponding to these repeats
reps_Events = cellfun(@(x) exptEvents(x), reps, 'UniformOutput', false);

toc

Elapsed time is 0.084577 seconds.

A: If I understand correctly, you want to find columns whose events are different. Building on John Colby's answer:
n = 1e3

tic

% Simulate data
% (Here we've split off the 5th row into a separate variable)
data = randi(5, [4 n]);
exptEvents = randi(50, 1, n);

% Find repeats
[b,i,j] = unique(data', 'rows');

% Organize the indices of the repeated columns into a cell array
reps = arrayfun(@(x) find(j==x), 1:length(i), 'UniformOutput', false);

% Find events corresponding to these repeats
reps_Events = cellfun(@(x) exptEvents(x), reps, 'UniformOutput', false);

U = cellfun(@unique, reps_Events, 'UniformOutput', false);
repeat_counts = cellfun(@length, U);
k=20;
rep_data = b(repeat_counts>=k,:);

toc

U in the code above has in every cell a group (or "combination") of unique events. Each cell also corresponds to a unique data column. If you need something else, please give an example. rep_data contains results that repeat in k or more events.


text:
Q: Loop through all h2 elements and add unique id I need to add unique ids to all h2 tags with jquery. I dont know how to add unique ids actually all of my h2 tags get the same when i just use the attr function and i have no idea how to change that.
$('h2').attr("id", "rev3");

A: You may use an implicit function inside jQuerys .each() like this
var id = 0;
$('h2').each(function(){
    $(this).attr("id", "rev" + id);
    id++;
})

.each() loops through all result array elements, while this reffers always to the current element.

A: It is possible with  each. You don't even need a seperate variable to hold the index:
$('h2').each(function(index, element) {
    $(this).attr('id', 'anid' + index);
});


text:
Q: ZEND get email body Below is a function (it's from Magento) and the simple thing is... I want to get the email in a string. But somehow things like: $mailer->getBodyText()->getRawContent() and $mail->getBodyHtml(); don't work...
At the bottom of this piece of code you'll find: $SOMETHING_HERE that is where I would like to get the body of the email.
public function sendNewOrderEmail()
{

    $storeId = $this->getStore()->getId();

    if (!Mage::helper('sales')->canSendNewOrderEmail($storeId)) {
        return $this;
    }
    // Get the destination email addresses to send copies to
    $copyTo = $this->_getEmails(self::XML_PATH_EMAIL_COPY_TO);
    $copyMethod = Mage::getStoreConfig(self::XML_PATH_EMAIL_COPY_METHOD, $storeId);

    // Start store emulation process
    $appEmulation = Mage::getSingleton('core/app_emulation');
    $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId);

    try {
        // Retrieve specified view block from appropriate design package (depends on emulated store)
        $paymentBlock = Mage::helper('payment')->getInfoBlock($this->getPayment())
            ->setIsSecureMode(true);
        $paymentBlock->getMethod()->setStore($storeId);
        $paymentBlockHtml = $paymentBlock->toHtml();
    } catch (Exception $exception) {
        // Stop store emulation process
        $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
        throw $exception;
    }

    // Stop store emulation process
    $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);

    // Retrieve corresponding email template id and customer name
    if ($this->getCustomerIsGuest()) {
        $templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_GUEST_TEMPLATE, $storeId);
        $customerName = $this->getBillingAddress()->getName();
    } else {
        $templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE, $storeId);
        $customerName = $this->getCustomerName();
    }

    $mailer = Mage::getModel('core/email_template_mailer');
    if($storeId!=1){
        $emailInfo = Mage::getModel('core/email_info');
        $emailInfo->addTo($this->getCustomerEmail(), $customerName);
        if ($copyTo && $copyMethod == 'bcc') {
            // Add bcc to customer email
            foreach ($copyTo as $email) {
                $emailInfo->addBcc($email);
            }
        }
        $mailer->addEmailInfo($emailInfo);
    }

    // Email copies are sent as separated emails if their copy method is 'copy'
    if ($copyTo && $copyMethod == 'copy') {
        foreach ($copyTo as $email) {
            $emailInfo = Mage::getModel('core/email_info');
            $emailInfo->addTo($email);
            $mailer->addEmailInfo($emailInfo);
        }
    }

    // Set all required params and send emails
    $mailer->setSender(Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $storeId));
    $mailer->setStoreId($storeId);
    $mailer->setTemplateId($templateId);
    $mailer->setTemplateParams(array(
            'order'        => $this,
            'billing'      => $this->getBillingAddress(),
            'payment_html' => $paymentBlockHtml
        )
    );
    $mailer->send();

    //
    // edit, save to file
    //

    $fp = fopen("/var/www/magento/confirmations/".time().".html","w");
    fwrite($fp, $SOMETHING_HERE);
    fclose($fp);

    $this->setEmailSent(true);
    $this->_getResource()->saveAttribute($this, 'email_sent');

    return $this;
}

A: $mailer->getBodyText(true);

or
$mailer->getBodyHtml(true);

should work.


text:
Q: Changing parent's class static method from a subclass I need to change a Parent's static method from a subclass.
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static I read:

Static method calls are made directly on the class and are not
  callable on instances of the class.

In the example below, I have a Parent class with a foo() method which calls the bar() method (both static). I would need to change bar from Child subclass so that calling Child.foo() will call the modified bar method and not the original one.
Is there a possibility (maybe something in the Child's constructor)?
class Parent {

  static foo() {
    Parent.bar();
  }

  static bar() {
    console.log("HERE I AM");
  }

}

class Child extends Parent {

  static bar() {
    super.bar(); // maybe not what I want?
    console.log(", FELLAS!");
  }
}

Parent.foo(); // HERE I AM
Child.foo(); // HERE I AM, FELLAS! (need this!)

A: Your problem is that foo directly calls Parent.bar(), not this.bar(). By explicitly referring to Parent, it doesn't consider the overwritten method in Child at all. It doesn't matter how Child.bar is written and whether it calls super.bar or not.
class Parent {
  static foo() {
    this.bar();
//  ^^^^
  }
  static bar() {
    return "HERE I AM";
  }
}

class Child extends Parent {
  static bar() {
    return super.bar() + ", FELLAS!";
  }
}

console.log(Parent.foo()); // HERE I AM
console.log(Child.foo()); // HERE I AM, FELLAS!

The this keyword in the static bar() method now refers to the Child class in the Child.foo() call, and calls its overridden bar method.
The only alternative (if you cannot modify Parent) would be to overwrite the foo method as well, duplicating the Parent code but calling Child.bar() explicitly there.

A: If you want to modify the Parent from the child just do it.  Parent is an object with properties, static is syntactic sugar.  Replacing a method is a simple as setting a property.  Probably not something you want to do in production code.

class Parent {
  static foo() {
    Parent.bar();
  }

  static bar() {
    console.log("HERE I AM");
  }
}

class Child extends Parent {
  static unhack() {
      if (Parent.hack) {
          Parent.bar = Parent.hack
          delete Parent.hack
      }
  }

  static hack() {
    if (!Parent.hack) {
       Parent.hack = Parent.bar
       Parent.bar = Child.bar
    }
  }

  static foo() {
      Child.hack()
      Parent.foo()
      Child.unhack()
  }

  static bar() {
    if (super.hack) {
      super.hack(); // Call the "shadowed" Parent.bar()
    }
    console.log(", FELLAS!"); // Call the additional code
  }
}

Parent.foo(); // HERE I AM
Child.foo(); // HERE I AM, FELLAS! (need this!)
Parent.bar(); // HERE I AM
Child.bar(); // Probably don't want to do this


text:
Q: How to use sns message filter to send to particular email? Is it possible to send different message to different email endpoints having different subscription ARN.If possible suggest some way using message filtering.
All emails subscribed to same Topic .But requirement is to send rewards points balance based on email which is being fetched from a query either rest or dynamodb query.

A: It is not possible to customize Amazon SNS messages per-user. All recipients will receive the same message.
Yes, you can use Amazon SNS filtering to control which recipients get each message, but that isn't really a good idea for sending single messages.
I would recommend that you investigate Amazon Pinpoint:

Amazon Pinpoint is an AWS service that you can use to engage with your customers across multiple messaging channels. You can use Amazon Pinpoint to send push notifications, emails, SMS text messages, and voice messages.

It might be a better way to engage with your customers.


text:
Q: spring-RabbitMQ manually listen to queue I'm new in rabbitmq.I'm using spring-amqp to implement the feature.
As we know spring provide @RabbitListener to register a listener to queue when the app initialization.
I want to design a function when I click some button, a new consumer will be created and listen to a specified queue.
Java base provide channel.basicConsume() method to consume a queue.
Is spring provide such function ?
I want to implement like :
producer keep sending messages to a fanout exchange.
when a consume wants to join, call function1 -> create queue and binding to exchange -> consume messages.
when a consume wants leave, call function2 -> disconnect

A: There are a few options.

*

*Use one of the RabbitTemplate.receive() or convertAndReceive() methods to get messages one-at-a-time, you can set a receiveTimeout in case there are no messages.

*RabbitTemplate.execute() with a callback that gets a channel that you can call basicConsume() on. This is a lower-level option and won't do any conversion for you.

*Create a SimpleMessageListenerContainer (or DirectMessageListenerContainer) dynamically and start/stop it as needed.

*...
In all cases, you can use a RabbitAdmin to create/bind the queue, for all except option 1, it would probably an auto-delete queue that will be removed when the consumer is cancelled. With option 1, you would have to use a non-auto-delete queue and remove it with the RabbitAdmin.
I would suggest that #3 is the most efficient using pure Spring AMQP.
You could also use Spring Integration with an inbound channel adapter and a publish-subscribe channel; that way you only need one queue (per application instance) and then subscribe a new MessageHandler to the channel for each user.


text:
Q: Syncronisation tool for dropbox replacement I have several Linux-PCs I want to be synced. I have a server exporting a filesystem via nfs, ftp or sshfs. I mount them to ~/syncenc. With encfs they are mounted to ~/sync. Working directly in this directory is fine as long as the computer is online. But some are Laptops that should keep their home directory local, but sync when online. Both the local as the remote data can change, of course. Also I a file is moved one side it has be move on the other as well, same for dirs. The software should be FOSS.
I'm looking for a software that can do that.
So far i found: https://secure.wikimedia.org/wikipedia/en/wiki/Comparison_of_file_synchronization_software but the table is rather incomplete.

*

*rsync - does not work bidirectional does it?

*unisono - cannot exclude files, there for useless (you cant sync a/b with a recursivly, obviously) also it cannot detect rename/move operations.

*Dir Sync Pro - Cannot detect rename/move operations, not suitable.

*iFolder - Wikipedia says something about P2P. ?? Also it seems to depend on a special Serversoftware.

A: Since you seem to be on Linux, you might look at http://www.sparkleshare.org ... seems to be maturing well and has good Linux / Mac / Android support. Windows and iOS are lagging for now, but if you don't need them it might do the trick for you.


text:
Q: How to call Javascript in Blazor package? This is a blazor project.The Javascipt code is for button in razor. The code is for button group which is when people click button in group 1 and group 2 it change color but in the group 1 will not be deselected.
I try to call my javascript function in C# but did'nt work.

export function switch_to_green(el) {

    //Check clicked button is on the same group
    if (el.parentElement.getAttribute("data-group") == 1) {
        //Get all buttons of group 1
        let g1_buttons = document.querySelectorAll('#group1 .btn');
        for (let i = 0; i < g1_buttons.length; i++) {
            //Remove green color from unselected buttons
            g1_buttons[i].classList.remove('green');
        }
    } else {
        //Get all buttons of group 2
        let g2_buttons = document.querySelectorAll('#group2 .btn');
        for (let i = 0; i < g2_buttons.length; i++) {
            //Remove green color from unselected buttons
            g2_buttons[i].classList.remove('green');
        }
    }
    //Add green color to the only selected one
    el.classList.add('green');

}
.show {
    display: block;
}

.btn-group {
    margin-top: 20px;
    overflow: hidden;
}

.btn {
    font-weight: bold;
    color: white;
    border: none;
    outline: none;
    padding: 12px 16px;
    /*blue*/
    background-color: #2c75ff;
    cursor: pointer;
}

    .btn:hover {
        font-weight: bold;
        color: white;
        /*green*/
        background-color: #85c995;
    }
    .btn.green {
        color: white;
        /*green*/
        background-color: #85c995;
    }
@page "/Test"
@inject IJSRuntime JSRuntime;
public

Hello, world!

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

            <button type="button" class="btn btn-primary" style="outline-color:red; " @onclick="LoadFile">Sunday</button>
            <button type="button" class="btn btn-primary" @onclick="LoadFile">Tuesday</button>
            <button type="button" class="btn btn-primary" @onclick="LoadFile">Friday</button>

            <button type="button" class="btn btn-primary" @onclick="LoadFile">9 am</button>
            <button type="button" class="btn btn-primary" @onclick="LoadFile">2 pm</button>
            <button type="button" class="btn btn-primary" @onclick="LoadFile">5 pm</button>
            <button type="button" class="btn btn-primary" @onclick="LoadFile">8 pm</button>

@code{
    string name = string.Empty;
    IJSObjectReference module;

    async Task LoadFile()
    {
        module = await JSRuntime.InvokeAsync< IJSObjectReference>("import","./Script/btn.js");
        }
}

What I have tried:
Javascript Isolataion
Blazor JavaScript isolation and object references
Solved Result
Result

A: You can use @ref and pass ElementReference to LoadFile,and module = await JSRuntime.InvokeAsync< IJSObjectReference>("import","./Script/btn.js"); will only load js,you need to call the function switch_to_green.Here is a demo:
@inject IJSRuntime JSRuntime;

                <button @ref=button1 type="button" class="btn btn-primary" style="outline-color:red; " @onclick="@(()=>LoadFile(@button1))">Sunday</button>
                <button @ref=button2 type="button" class="btn btn-primary" @onclick="@(()=>LoadFile(@button2))">Tuesday</button>
                <button @ref=button3 type="button" class="btn btn-primary" @onclick="@(()=>LoadFile(@button3))">Friday</button>

                <button @ref=button4 type="button" class="btn btn-primary" @onclick="@(()=>LoadFile(@button4))">9 am</button>
                <button @ref=button5 type="button" class="btn btn-primary" @onclick="@(()=>LoadFile(@button5))">2 pm</button>
                <button @ref=button6 type="button" class="btn btn-primary" @onclick="@(()=>LoadFile(@button6))">5 pm</button>
                <button @ref=button7 type="button" class="btn btn-primary" @onclick="@(()=>LoadFile(@button7))">8 pm</button>

@code{
    string name = string.Empty;
    IJSObjectReference module;
    private ElementReference button1;
    private ElementReference button2;
    private ElementReference button3;
    private ElementReference button4;
    private ElementReference button5;
    private ElementReference button6;
    private ElementReference button7;

    async Task LoadFile(ElementReference element)
    {
        module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./Script/btn.js");
        await module.InvokeVoidAsync("switch_to_green", element);
    }
}

result:

A: I know this doesn't answer the question, but you don't need any Javascript to change the color of your buttons.  You can use variables for either an object's class or its style attributes directly in Blazor.

A: Try something like the following.  It doesn't save much effort in this simple example, but hopefully it will give a good idea about how to move forward from here.  IMO you can much more easily adapt Blazor than JavaScript if you want to change anything else.

            @foreach (string day in DayChoices)
            {
                string color = (day == SelectedDay) ? "green" : "";
                   // If above is confusing, google "C# ternary operator"
                <button type="button" class="btn btn-primary @color" @onclick="()=>SetDay(day)">@day</button>
                   // Using lambda above lets you pass variables to your method easily //
            }

            @foreach (string time in TimeChoices)
            {
                string color = (time == SelectedTime) ? "green" : "";
                <button type="button" class="btn btn-primary @color" @onclick="()=>SetTime(time)">@time</button>
            }

Appointment Time: @SelectedDay @SelectedTime

@code {
    string[] DayChoices = new string[] { "Sunday", "Tuesday", "Friday" };
    string[] TimeChoices = new string[] { "9 am", "2 pm", "5 pm", "8 pm" };
    string SelectedDay { get; set; } = "";
    string SelectedTime { get; set; } = "";

    void SetDay (string Day)
    {
        SelectedDay = Day;
    }
    void SetTime (string Time)
    {
        SelectedTime = Time;
    }
}


text:
Q: Change property of multiple divs at once I have a function which changes the width for seven divs. Right now it looks like this.
 document.getElementById('monday7').style.width = "76";
 document.getElementById('tuesday7').style.width = "76";
 document.getElementById('wednesday7').style.width = "76";
 document.getElementById('thursday7').style.width = "76";
 document.getElementById('friday7').style.width = "76";
 document.getElementById('saturday7').style.width = "76";
 document.getElementById('sunday7').style.width = "76";

This works flawlessly but I need to repeat similar code like the one above like 20 times.
So I have the following questions.

*

*How do I change all the seven div widths at once? I mean something similar to this:
document.querySelectorAll('monday7, tuesday7').style.width = "76";

(Which didn't work).

*Will this speed up the loading time, having one row like the one above compared to   having seven rows of code?

Thanks in advance

A: You could give them all a class then do
var elements = document.getElementsByClassName("CLASSNAME");
for(var i = 0; i<elements.length; i++){
    elements[i].style.width = "76";
}

elements is an array of all of the elements then you just loop through it and set them all. It requires minor changes to the HTML but will save you lots of space in the JS.
I dont know about loading time though might be slightly slower or around the same.

A: jQuery also makes this fairly simple. I'd suggest adding a class first though so all your elements can be accessed with one selector. So it would look like:

...

Then your jQuery would look like:
$('.widthChange').css('width', '76px');

Concise.


text:
Q: javascript onload reset timestamp loop woes I normally develop with VBA and MySQL, but have been tasked with creating a live dashboard to be put on screens around my office. For this I'm using PHP and javascript. The dashboard contains two main sections, one calls website traffic data through the google analytics API, the other calls sales data from our internal DB.
I have the seperate halves written in PHP in seperate modules that I'm calling with the code below from the dashboard webpage, using a loop to refresh each module independently every ten seconds. The problem is that I'd like to include two timers on the screen counting upwards in seconds from the last time each of the modules was loaded, I'm using the following code to try and reset a variable with the current time to facilitate this when each document is loaded.
var sales_string_unix = 0;
var sales_string_google = 0;

setInterval(function(){

    $(document).ready(function() {
        $('#google_data').load('fetch_google_data.php');
        sales_string_unix = new Date().getTime();
    });

 }, 10000);

setInterval(function(){

    $(document).ready(function() {
        $('#sales_data').load('fetch_sales_data.php');
        sales_string_google = new Date().getTime();
     });

}, 10000);

My problem is that the timestamp variables reset every ten seconds when the loops execute, rather than when the modules are refreshed. So far 6hrs of Google has returned nothing useful and I expect I'm probably missing something simple thats just outside of my experience. Any help would be appreciated, thanks in advance.

A: You need to put the timestamp update code in the callback function of the load() which runs when the AJAX call has completed. You also don't need the document.ready handler inside each function. Try this:
var sales_string_unix = 0;
var sales_string_google = 0;

setInterval(function(){
    $('#google_data').load('fetch_google_data.php', function() {
        sales_string_unix = new Date().getTime();
    });
}, 10000);

setInterval(function() {
    $('#sales_data').load('fetch_sales_data.php', function() {
        sales_string_google = new Date().getTime(););
    });
}, 10000);

Be aware however, that those variables will only be filled once the AJAX call has completed, so you cannot use them directly after the AJAX calls themselves. You would need to run or call the code which relies on the timestamps from within the callback function itself.

A: You don't need the $(document).ready() within the functions, just put it once on the outside
var sales_string_unix = 0;
var sales_string_google = 0;
$(document).ready(function() {
    setInterval(function(){
        $('#google_data').load('fetch_google_data.php');
        sales_string_unix = new Date().getTime();
    }, 10000);

    setInterval(function(){
        $('#sales_data').load('fetch_sales_data.php');
        sales_string_google = new Date().getTime();
    }, 10000);
});


text:
Q: How to count time for members connected to my discord I'm currently trying to count time for active members of my discord with discord bot in python. I write name of member and timedelta to the file.
My question is how can I read this timedelta from a file? I know that datetime.datetime has strptime method but there is none for datetime.timedelta.
Any ideas apart from slicing and passing this as arguments to timedelta constructor?
for a in self.members:
        if not a.bot:
            self.member_timers[a.name] = {}
            self.member_timers[a.name]['Time'] = None
            self.member_timers[a.name]['Stop'] = None
            self.member_timers[a.name]['Start'] = None
    self.read()

def read(self):
    lines = []
    with open(f'logi', 'r') as f:
        lines = f.readlines()
        f.close()
    print(lines)
    line = lines[0].split()

def write(self):
    with open(f'logi', 'w') as f:
        for mem in self.members:
            if not mem.bot and self.member_timers[mem.name]['Time'] != None:
                f.write("{} {}\n".format(mem.name, self.member_timers[mem.name]['Time']))

def start_timer(self, member):
    if self.member_timers[member.name]['Start'] == None:
        self.member_timers[member.name]['Start'] = datetime.datetime.now()
    else:
        #policz mu czas zeby nie stracic
        self.count_time(member.name)
        self.member_timers[member.name]['Start'] = datetime.datetime.now()
        pass

def stop_timer(self, member):
    if self.member_timers[member.name]['Start'] != None:
        self.member_timers[member.name]['Stop'] = datetime.datetime.now()
        self.count_time(member.name)

def count_time(self, name):
    if self.member_timers[name]['Start'] != None and self.member_timers[name]['Stop'] != None:
        if self.member_timers[name]['Time'] == None:
            self.member_timers[name]['Time'] = self.member_timers[name]['Stop'] - self.member_timers[name]['Start']
        else:
            self.member_timers[name]['Time'] += self.member_timers[name]['Stop'] - self.member_timers[name]['Start']
        self.member_timers[name]['Start'] = None
        self.member_timers[name]['Stop'] = None

So when reading from file I want to create timedelta object for member so I can later compare if it's bigger than any role timedelta I have assigned.

A: I think you should consider storing the timestamp instead of storing timedelta object.
You can use ts = datetime.datetime.timestamp(datetime.datetime.now()) to get a float (you can convert it to an int if you are only interested in seconds) that you store in your dictionnary.
To read it, you can use datetime.datetime.fromtimestamp(ts) and this will give you a datetime.datetime object corresponding to the timestamp you created above
References:
https://docs.python.org/3/library/datetime.html?highlight=timestamp#datetime.datetime.timestamp
https://docs.python.org/3/library/datetime.html?highlight=fromtimestamp#datetime.datetime.fromtimestamp


text:
Q: How can i revert a git commit --amend -m without losing my original hashcode and the code i supposed to commit? I need to revert a wrong git commit --amend -m

*

*did git commit without -m

*did git commit --amend -m "commit message"

*git commit --amend -m "commit message" changed my previous commit instead of the one i supposed to commit.

is it possible to revert to before the step 1 without losing my original hashcode or the code i supposed to commit?
commit is not pushed yet btw

A: git reset --soft "HEAD@{1}"
git commit -m "commit message"

HEAD@{1} means "find where HEAD was before the current commit". You can verify it's really the previous (unmodified) commit using git reflog and git show "HEAD@{1}".


text:
Q: JSONEncoder not handling lists I have a deeply nested data structure with extensive lists.  I want to count the lists instead of displaying all the contents.
class SummaryJSONEncoder(json.JSONEncoder):
    """
    Simple extension to JSON encoder to handle date or datetime objects
    """
    def default(self, obj):
        func = inspect.currentframe().f_code
        logger.info("%s in %s:%i" % (
            func.co_name,
            func.co_filename,
            func.co_firstlineno
        ))
        logger.info('default %s', type(obj))
        if isinstance(obj, (datetime.datetime, datetime.date,)):
            return obj.isoformat()
        if isinstance(obj, (list, tuple, set,)):
            return "count(%s)" % len(obj)
        else:
            logger.info('Falling back for %s', type(obj))
            return super(SummaryJSONEncoder, self).default(obj)
    def encode(self, obj):
        func = inspect.currentframe().f_code
        logger.info("%s in %s:%i" % (
            func.co_name,
            func.co_filename,
            func.co_firstlineno
        ))
        return super(SummaryJSONEncoder, self).encode(obj)

The sets seem to encode properly, but lists and tuples will not bend to my will.
 >>> json.dumps({'hello': set([]), 'world': [1,2,3], 'snot': (1,2,3,), 'time': datetime.datetime.now()}, indent=4, cls=SummaryJSONEncoder)
2016-10-05 14:07:42,786 (9296) __main__ INFO - encode in <pyshell#56>:20
2016-10-05 14:07:42,789 (9296) __main__ INFO - default in <pyshell#56>:5
2016-10-05 14:07:42,792 (9296) __main__ INFO - default <type 'set'>
2016-10-05 14:07:42,793 (9296) __main__ INFO - default in <pyshell#56>:5
2016-10-05 14:07:42,796 (9296) __main__ INFO - default <type 'datetime.datetime'>
'{\n    "world": [\n        1, \n        2, \n        3\n    ], \n    "hello": "count(0)", \n    "snot": [\n        1, \n        2, \n        3\n    ], \n    "time": "2016-10-05T14:07:42.786000"\n}'
>>>

I cannot tell, but it looks like lists and tuples are handled elsewhere and not passed to the default method.  Has anyone needed to do this before?

A: This seems to work
class SummaryJSONEncoder(json.JSONEncoder):
"""
Simple extension to JSON encoder to handle date or datetime objects
"""
def default(self, obj):
    if isinstance(obj, (datetime.datetime, datetime.date,)):
        return obj.isoformat()
    if isinstance(obj, (list, tuple, set,)):
        return "count(%s)" % len(obj)
    else:
        return super(SummaryJSONEncoder, self).default(obj)
def _iterencode_list(self, obj, x):
    if isinstance(obj, (list, tuple, set,)):
        return self.default(obj)
    return super(SummaryJSONEncoder, self)._iterencode_list(obj, x)

The code trace is.
json.dumps({'hello': set([]), 'world': [1,2,3], 'snot': (1,2,3,), 'time': datetime.datetime.now()}, indent=4, cls=SummaryJSONEncoder)
2016-10-05 14:50:10,785 (9296) __main__ INFO - default in <pyshell#73>:5
2016-10-05 14:50:10,788 (9296) __main__ INFO - default <type 'list'>
2016-10-05 14:50:10,792 (9296) __main__ INFO - default in <pyshell#73>:5
2016-10-05 14:50:10,796 (9296) __main__ INFO - default <type 'set'>
2016-10-05 14:50:10,799 (9296) __main__ INFO - default in <pyshell#73>:5
2016-10-05 14:50:10,802 (9296) __main__ INFO - default <type 'tuple'>
2016-10-05 14:50:10,806 (9296) __main__ INFO - default in <pyshell#73>:5
2016-10-05 14:50:10,811 (9296) __main__ INFO - default <type 'datetime.datetime'>
'{\n    "world": count(3), \n    "hello": "count(0)", \n    "snot": count(3), \n    "time": "2016-10-05T14:50:10.785000"\n}'

I hope this helps someone :-)


text:
Q: PHP SOAP: Communication to a C++ application I have a C++ SOAP client using gSOAP and am trying to construct a very simple PHP server (Apache2/PHP5 on Debian) the client can talk to. Unfortunately, I don't understand how I can work with the complex types my web service is using within PHP.
I have a .wsdl that looks like this:
<definitions name="NumOps"
    targetNamespace="http://192.168.2.113/numops.wsdl"
    xmlns:tns="http://192.168.2.113/numops.wsdl"
    xmlns:xsd1="http://192.168.2.113/testtypes.xsd"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns="http://schemas.xmlsoap.org/wsdl/">

<types>
    <schema targetNamespace="http://192.168.2.113/testtypes.xsd"
        xmlns="http://www.w3.org/2001/XMLSchema">
        <element name="AddValRequest">
            <complexType>
                <all>
                    <element name="fVal1" type="float"/>
                    <element name="fVal2" type="float"/>
                </all>
            </complexType>
        </element>
        <element name="AddValResponse">
            <complexType>
                <all>
                    <element name="fResult" type="float"/>
                </all>
            </complexType>
        </element>
    </schema>
</types>

<message name="AddValInput">
    <part name="body" element="xsd1:AddValRequest"/>
</message>
<message name="AddValOutput">
    <part name="body" element="xsd1:AddValResponse"/>
</message>

<portType name="NumOpsPortType">
    <operation name="AddVal">
        <input message="tns:AddValInput"/>
        <output message="tns:AddValOutput"/>
    </operation>
</portType>

<binding name="NumOpsSoapProxy" type="tns:NumOpsPortType">
    <soap:binding style="document"
        transport="http://schemas.xmlsoap.org/soap/http"/>
    <operation name="AddVal">
        <soap:operation soapAction="http://192.168.2.113/"/>
        <input>
            <soap:body use="literal"/>
        </input>
        <output>
            <soap:body use="literal"/>
        </output>
    </operation>
</binding>

<service name="NumOpsService">
    <port name="NumOpsPort" binding="tns:NumOpsSoapProxy">
        <soap:address location="http://192.168.2.113/"/>
    </port>
</service>

</definitions>

My current approach looks like this:
<?php

function AddVal($AddValRequest) {
    // How to create a AddValResponse?!
}

$server = new SoapServer(NULL, array("uri"=>"http://192.168.2.113/"));
$server->addFunction("AddVal");
$server->handle();

?>

The problem here is that I couldn't anything to get me started on this, and I probably won't solve this guessing. Does anyone know where I could find material to dig into this matter?

A: This works:

class AddValRequest {
    public $fVal1;
    public $fVal2;
}

class AddValResponse {
    public $fResult;
}

function AddVal(AddValRequest $request) {
    $response = new AddValResponse();
    $response->fResult = $request->fVal1 + $request->fVal2;
    return $response;
}

$server = new SoapServer("numops.wsdl");
$server->addFunction("AddVal");
$server->handle();

?>

and should be sufficient to get someone having the same problem started.


text:
Q: Can we use control the source formats/layout in DMExpress using environment variables? I am using DMExpress tasks to do taransformations on my business data. These business data come in multiple format/layout. I need to be able to use single task for transformation on multiple source layouts. Any DMExpress experts here??

A: One way that I found out for doing transformation on multiple source layouts with the help of single task was by using the Dmexpress SDK to write the script for the task rather than building the tasks using the GUI task editor. SDK gives lot more flexibility compared to the GUI editor.
But if you are bound to GUI then there is a way around for this specific purpose. You should define a common name for the source layout. Only the source layout name is binded to the task but not the actual layout definition. So you can alter the layout definition while keeping the layout name constant to get a generic task.

A: FYI- DMExpress is now called DMX (Syncsort changed the name about a year ago).
Do you have multiple different record types within a single file or is each type of record in a separate file?  Your question is not clear on this.
If they are in separate files, this is very easy, but you will need to create a separate DMX task for each file.  In each of these tasks, define one of the files as the source and create a record layout that matches the format of that file.
If they are in the SAME file, it is only a little more difficult.  You can split them into separate files by creating multiple targets and defining a named condition for each target using the SourceName() function (this function returns the name of the file that the current record came from).  Then you can process them as separate files (see above).  This works UNLESS you have a parent-child relationship going on between the different types of records in that single file.  If that is the case, please post some sample data and I can advise on how to handle it.


text:
Q: Among the various subgraphs of $K_5$, how many are cycles? Among the various subgraphs of $K_5$, how many are cycles?
I know the answer is $37$ because the number of $3$-cycles is $10$, the number of $4$-cycles is $15$, and $5$-cycles is $12$. Could anyone explain in detail how these numbers are reached?

A: First notice that any $n \in \{3,4,5\}$ vertices you choose from $K_5$, you can make a cycle out of them. When you are counting the $n$-cycles, you need to count the number of ways you can choose $n$ vertices out the given $5$ vertices, and for each of those choices you need to count how many ways those $n$ vertices can be arranged into a cycle.
So when counting the $3$-cycles, since there is only one way to have a cycles with $3$ vertices it would be
$$
  \binom{5}{3} \times (1) = 10 \times (1) = 10
$$
The cases for $4$ and $5$ vertices is done similarly. You've just got to figure out how to count the number of ways $4$ and $5$ vertices can be connected into a cycles. Can you take it from here?


text:
Q: IM message indicator in gnome-shell I'm trying to use instant messaging with Gnome Shell with the current Ubuntu 11.10 but up to now this is a total disaster. I have these problems:

*

*When I want to write someone a message I have to manually start empathy with a right click and selecting "New window" because otherwise it only focuses an already open chat window instead of opening the roster. Alternative is searching for the name in the just-type search, clicking the found user and then clicking the chat button. This is all to complicated. In previous gnome versions I could simply click the IM icon in the tray to open the roster. What is the supposed way to do this now in gnome shell?

*When someone writes me a message then this message is shortly displayed at the bottom of the screen. That's nice when I'm in front of the screen and notice it. But when I don't notice this notification then it is minimized into this notification area which isn't visible by default. So I have to check manually if a new message has arrived. In previous gnome versions I had a blinking IM icon in the tray which CONSTANTLY notified me about a new message. How is that supposed to work in gnome shell now?
Unity has a message indicator which displays a colored icon when a unread message is waiting. This isn't ideal but better than nothing. It also allows me to open the roster window in the context menu. How can I achieve something similar with Gnome shell?

A: For your first question, you have a few options. First, you can open a new instance of any application by middle clicking. It will open in a new workspace, and once you close it you'll land back where you were.
If you install the application called gnome-contacts, you can search for your contacts from the overview. (Unfortunately, gnome-contacts doesn't sort by status at the moment, so that isn't ideal).
For your second question, you can get Empathy to always open chats in new windows. Open Empathy, go to Edit›Preferences in the menu and uncheck "Display incoming events in the notification area." It's a little counter-intuitive, but what that does is your new messages will still appear in the message tray but their corresponding windows will open immediately.

A: You can find the "short popup messages" for chat and apps requests at the bottom of right corner (tray).


text:
Q: Change system z-order of BrowserWindow in electron, possible? I need to control main window z-order so to say. Always on top is not my case. I want to put my window behind all others and above desktop. Is it possible? Is there analogue to C++ SetWindowPos function? Or maybe some workaround?

A: First you should send the window to the back/bottom of the z-index stack, then disable z-index changing for the window.
I tried getting this working in my project, and eventually succeeded, as shown below.
However, note that some of my code comments might not be accurate. I don't understand node-ffi very well, and only got it working through trial and error; my code comments are just my attempt at trying to "make sense" of the behavior I observed.
import ffi from "ffi";
import ref from "ref";
import Struct from "ref-struct";

const HWND_BOTTOM = 1;
export let SetWindowPos_Flags = {
    NOSIZE: 0x0001,
    NOMOVE: 0x0002,
    NOACTIVATE: 0x0010,
}

export var user32 = new ffi.Library("user32", {
    // return, handle, handleInsertAfter, x, y, cx, cy, flags
    SetWindowPos: ["bool", ["int32", "int32", "int32", "int32", "int32", "int32", "uint32"]],
});

export function SendWindowToBack(handle: number) {
    user32.SetWindowPos(handle, HWND_BOTTOM, 0, 0, 0, 0, SetWindowPos_Flags.NOMOVE | SetWindowPos_Flags.NOSIZE | SetWindowPos_Flags.NOACTIVATE);
}

export const WM_WINDOWPOSCHANGING = 0x0046;
export const SWP_NOZORDER = 0x0004;
let WINDOWPOS = Struct({
    hwndInsertAfter: ffi.types.int32,
    hwnd: ffi.types.int32,
    x: ffi.types.int32,
    y: ffi.types.int32,
    cx: ffi.types.int32,
    cy: ffi.types.int32,
    flags: ffi.types.uint32,
});
export function AddHook(window: Electron.BrowserWindow, disableZIndexChanging = false) {
    window.hookWindowMessage(WM_WINDOWPOSCHANGING, (wParam: Buffer, lParam: Buffer)=> {
        // The "lParam" buffer holds the address to a place in unmanaged memory, which itself holds the address to the actual (unmanaged) struct-data.
        // Thus: js-pseudo-pointer (8-bytes; the lParam Buffer) -> c-pointer (8-bytes, unmanaged) -> struct-data (28-bytes, unmanaged)
        // However, the lParam buffer does not realize it is/could-be a "pseudo-pointer" -- all it knows is that it's holding some random numbers.
        // To access the unmanaged struct-data, we have to tell the js-side that the contents of lParam are actually the address explained above.
        // Then we'll be able to use the Buffer.deref() function to correctly obtain the final struct-data.

        // To do this, we:
        // 1) Create a new js-pseudo-pointer (using the modified Buffer class), whose contents/what-it-points-to is marked as of type "pointer to a pointer" (ie. the c-pointer entry above)
        let lParam2 = Buffer.alloc(8);
        lParam2["type"] = ref.refType(WINDOWPOS);

        // 2) Fill the js-pseudo-pointer with the actual address to that c-pointer (just copy this address from the unmarked lParam Buffer)
        lParam.copy(lParam2);

        // 3) Dereference our js-pseudo-pointer, retrieving the actual struct-data bytes
        let actualStructDataBuffer = lParam2["deref"]() as Buffer;

        // 4) Convert the struct-data bytes into a regular JavaScript object
        let windowPos = actualStructDataBuffer["deref"]() as {hwndInsertAfter: number, hwnd: number, x: number, y: number, cx: number, cy: number, flags: number};

        // 5) Modify the 7th integer (the flags field) in the (unmanaged) struct-data, to include the new SWP_NOZORDER flag
        if (disableZIndexChanging) {
            //lParam.flags |= SWP_NOZORDER;
            let newFlags = windowPos.flags | SWP_NOZORDER;
            actualStructDataBuffer.writeUInt32LE(newFlags, 6);
        }
    });
}

// This is the function you actually call from the rest of your program.
export function SendElectronWindowToBackAndKeepItThere(window: Electron.BrowserWindow) {
    let handleAsBuffer = window.getNativeWindowHandle();
    let handleAsNumber = ref.types.int64.get(handleAsBuffer, 0);
    SendWindowToBack(handleAsNumber);
    AddHook(window, true);
}

A: If it's not something you can accomplish with parent/child windows then you could call SetWindowPos() via node-ffi (or write a native Node module/addon). To get the HWND for a BrowserWindow call getNativeWindowHandle(). I have no idea how you'd do this natively on macOS or Ubuntu.

A: You can call .blur() on the window. It will make it go below other windows.


text:
Q: Removing non unique Objects from a List (identifiable by a property) I am capturing events from a stream, each event is a Device Object. The way the stream work is that it is on a timer, so it picks up the same device multiple times and adds to the stream.
I am putting all theres is a List<Device> and putting that into another stream.
I have create a StreamTransformer in the attempt to remove duplicate  from the list and then add the unique list back into the stream.
This transform code below, I have tried to add to set and back to list, but this hasn't worked I assume due to the fact they are objects not strings.
  //Transform Stream List by removing duplicate objects
  final deviceList = StreamTransformer<List<Device>, List<Device>>.fromHandlers(
      handleData: (list, sink) {
      List<Device> distinctList = list.toSet().toList();
      sink.add(distinctList);
  });

I have attempted to use .where and other libraries but to no avail and am hoping for some guidance.

Device Object contains unique id and name that could be used to filter
  out duplicates
Question: How can I remove duplicate objects from a List in Dart?

Thanks in advance.

A: First of all you would need to define by which criteria the objects are supposed to be unique. Is there an identifying property for example? If that is the case the following options should work.
The most efficient way is probably to make the approach with a set working. For that you would need to turn your objects into data objects, meaning have them identify for equality by property values. For that you would override the equality operator and hashCode getter. However this changes how your objects behave on every equality operation, so you would have to judge if that is suitable. See this article.
Another option is to just filter manually using a Map:
class MyObj {
  String val;

  MyObj(this.val);
}

TestListFiltering(){
  List<MyObj> l = [
    MyObj("a"),
    MyObj("a"),
    MyObj("b"),
  ];
  // filter list l for duplicate values of MyObj.val property
  Map<String, MyObj> mp = {};
  for (var item in l) {
    mp[item.val] = item;
  }
  var filteredList = mp.values.toList();
}


text:
Q: headerDelegate QML tableView - text not visible import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.1
import QtGraphicalEffects 1.0

Window {
    visible: true
    width: 640
    height: 480

    color:"#292a38"

    TableView
    {
        width: 580

        headerDelegate: Rectangle
                        {
                            id: header1
                            height: 20;
                            color: "#343848"
                        }

        rowDelegate: Rectangle
                    {
                        height: 30

                      }
        TableViewColumn
        {
            role: "selectall"
            title: ""
            width: 40

            delegate:
                    Rectangle
                    {
                        height: 120
                        width: 120
                        color: "#24253c"
                    }
        }

        TableViewColumn
        {
            role: "name"
            title: "Name"
            width: 145

            delegate:
                Rectangle
                {
                    height: 120
                    width: 120
                    color: "#24253c"

                    RowLayout
                    {
                        spacing: 10
                        height: 20
                        width: 20
                        Image
                        {
                            height: 20
                            width: 20
                        }

                        Text
                        {
                            color: "lightgray"
                            text: "something"
                        }
                    }
                }
        }

        TableViewColumn
        {
            role: "size"
            title: "Size"
            width: 100

            delegate: Rectangle
            {
                height: 120
                width: 120
                color: "#24253c"
            }
        }

        TableViewColumn
        {
            role: "last_updated"
            title: "Last Updated"
            width: 300
            delegate: Component
                        {
                            Rectangle
                            {
                                height: 100
                                width: 150
                                id: head
                                color: "#24253c"

                                RowLayout
                                {
                                    spacing: 10
                                    height: parent.height
                                    width: parent.width

                                    Text {
                                        id: name
                                        text: Date().toLocaleString()
                                        color: "lightgray"
                                    }

                                    Image
                                    {
                                        height: 20
                                        width: 20
                                        MouseArea
                                        {
                                            anchors.fill: parent
                                            onClicked: parent.color = "grey"
                                        }
                                    }
                                }
                            }
                        }

        }

        model: ListModel
                {
                    id: mymodel
                    ListElement { text: "Banana" }
                    ListElement { text: "Apple" }
                    ListElement { text: "Coconut" }
                }
    }

}

This results in:

As you can see the titles of the header are not visible. Please help.

A: Header delegates are to be written inside TableViewStyle with style property and then we are supposed to use styleData.value to get the value of individual column titles in the header.
TableView
{
    width: 580

    style: TableViewStyle
    {
        headerDelegate: Rectangle
                        {
                            height: 20
                            color: "lightsteelblue"
                            Text {
                                width: parent.width
                                text: styleData.value // <---
                                elide: Text.ElideMiddle
                            }
                        }

        itemDelegate: Rectangle
                      {
                         color: "red"
                         Text {
                             width: parent.width // <---
                             text: styleData.value
                             elide: Text.ElideMiddle
                         }
                      }

        rowDelegate: Rectangle
                        {
                            color: "blue"
                            height: 30
                        }

    }

    TableViewColumn
    {
            role: "selectall"
            title: "XYZ"
            width: 40

    }
}


text:
Q: Explain the below Array Of consecutive Number I have the below example which prints a 2 dimensional array of consecutive numbers.
My Question is how should i determine the number that is multiplied by i
in the below example ( Which is 3 in this case) in order to print an array of consecutive numbers.
It always seems to be i * [length of the second dimension of the array] + j.
If more explanation is needed please tell me
    public class test
{

    static void Main(string[] args)
    {
        populate();
        Console.ReadKey();
    }

    public static void populate()
    {
        int[,] matrix = new int[4, 3];

        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                matrix[i, j] = i * 3 + j;
            }
        }

        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                System.Console.WriteLine(matrix[i, j]);
            }
        }
    }

}

A: So, presumably the idea is to end up with:
        | 0   1   2  <-- j
        ------------
      0 | 0,  1,  2
i ->  1 | 3,  4,  5
      2 | 6,  7,  8
      3 | 9, 10, 11

So this is simple math. Your columns are j and your rows are i. j is going to run 0,1,2. So in your first row (where i == 0) you need:
0 * 3 + 0 = 0,  0 * 3 + 1 = 1,  0 * 3 + 2 = 2

Now for your next row (i==1), you need to start at 3 and then add j to it. So you get:
1 * 3 + 0 = 3,  1 * 3 + 1 = 4,  1 * 3 + 2 = 5

For the third row (i==2) you are going to need to start at 6 which is simply the row ordinal (2) times the width of each row (3), so you get:
2 * 3 + 0 = 6,  2 * 3 + 1 = 7,  2 * 3 + 2 = 8

Now if your table was wider, and you needed, for example:
0,  1,  2,  3
4,  5,  6,  7
...

I hope it's pretty obvious now that your formula would need to be:
i * 4 + j

So, yes, the number you are multiplying by is the width of each row. And that will be the same as the length of your second array dimension. So you could make your formula be:
i * matrix.GetLength(1) * j


text:
Q: ZeroMQ On Android Java ( Android Studio ) I'm trying to program ZeroMQ on my android device and I know how to use ZeroMQ (From C++, Php, .Net , I'm all the time using it.) If I list what I've done until now :

*

*From Dependencies in Android Studio, I added org.zeromq:jeromq:0.3.5 from maven central search.

*After that, I put a code like the following :

try
{
    ZMQ.Context context = ZMQ.context(1);

    //  Socket to talk to server
    System.out.println("Connecting to hello world server...");

    ZMQ.Socket requester = context.socket(ZMQ.REQ);
    requester.connect("tcp://192.168.2.127:5555");

    for (int requestNbr = 0; requestNbr != 10; requestNbr++) {
        String request = "Hello";
        System.out.println("Sending Hello " + requestNbr);
        requester.send(request.getBytes(), 0);

        byte[] reply = requester.recv(0);
        System.out.println("Received " + new String(reply) + " " + requestNbr);
    }
    requester.close();
    context.term();

}
catch (Exception e)
{
   Log.e("Error", "Exception : " + e.getMessage());
}

When I run this, I got an exception like the following :
01-03 02:20:55.200 12562-12562/mia.face.id.zeromq E/dalvikvm: Could not find class 'android.os.PersistableBundle', referenced from method mia.face.id.zeromq.MainActivity.access$super
01-03 02:20:55.200 12562-12562/mia.face.id.zeromq E/dalvikvm: Could not find class 'android.os.PersistableBundle', referenced from method mia.face.id.zeromq.MainActivity.access$super
01-03 02:20:55.200 12562-12562/mia.face.id.zeromq E/dalvikvm: Could not find class 'android.media.session.MediaController', referenced from method mia.face.id.zeromq.MainActivity.access$super
01-03 02:20:55.210 12562-12562/mia.face.id.zeromq E/dalvikvm: Could not find class 'android.widget.Toolbar', referenced from method mia.face.id.zeromq.MainActivity.access$super
01-03 02:20:55.220 12562-12562/mia.face.id.zeromq E/dalvikvm: Could not find class 'android.app.ActivityManager$TaskDescription', referenced from method mia.face.id.zeromq.MainActivity.access$super
01-03 02:20:55.230 12562-12562/mia.face.id.zeromq E/dalvikvm: Could not find class 'android.app.SharedElementCallback', referenced from method mia.face.id.zeromq.MainActivity.access$super
01-03 02:20:55.230 12562-12562/mia.face.id.zeromq E/dalvikvm: Could not find class 'android.os.PersistableBundle', referenced from method mia.face.id.zeromq.MainActivity.access$super
01-03 02:20:55.240 12562-12562/mia.face.id.zeromq E/dalvikvm: Could not find class 'android.app.SharedElementCallback', referenced from method mia.face.id.zeromq.MainActivity.access$super
01-03 02:20:55.250 12562-12562/mia.face.id.zeromq E/dalvikvm: Could not find class 'android.app.assist.AssistContent', referenced from method mia.face.id.zeromq.MainActivity.access$super
01-03 02:20:55.260 12562-12562/mia.face.id.zeromq E/dalvikvm: Could not find class 'android.view.SearchEvent', referenced from method mia.face.id.zeromq.MainActivity.access$super
01-03 02:20:55.270 12562-12562/mia.face.id.zeromq E/dalvikvm: Could not find class 'android.os.PersistableBundle', referenced from method mia.face.id.zeromq.MainActivity.access$super
01-03 02:21:08.080 12562-12562/mia.face.id.zeromq E/Error: Exception : null

I'm actually not new in programming but in Android/Java stuffs. I cannot figure it out how to solve this problem. I searched on the internet however couldnt find something.
If you can help me, I'll be very pleased.
Thanks in advance.
(Addtion, I forget to include this one : )
01-03 03:12:58.430 1374-1374/mia.face.id.zmqtestest E/Error: Exception
                                                         android.os.NetworkOnMainThreadException
                                                             at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
                                                             at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:168)
                                                             at libcore.io.IoBridge.sendto(IoBridge.java:490)
                                                             at java.nio.SocketChannelImpl.writeImpl(SocketChannelImpl.java:391)
                                                             at java.nio.SocketChannelImpl.write(SocketChannelImpl.java:349)
                                                             at java.nio.PipeImpl$PipeSinkChannel.write(PipeImpl.java:114)
                                                             at zmq.Signaler.send(Signaler.java:121)
                                                             at zmq.Mailbox.send(Mailbox.java:85)
                                                             at zmq.Ctx.sendCommand(Ctx.java:388)
                                                             at zmq.ZObject.sendCommand(ZObject.java:362)
                                                             at zmq.ZObject.sendPlug(ZObject.java:171)
                                                             at zmq.ZObject.sendPlug(ZObject.java:161)
                                                             at zmq.Own.launchChild(Own.java:126)
                                                             at zmq.SocketBase.addEndpoint(SocketBase.java:550)
                                                             at zmq.SocketBase.connect(SocketBase.java:542)
                                                             at org.zeromq.ZMQ$Socket.connect(ZMQ.java:1246)
                                                             at mia.face.id.zmqtestest.MainActivity$1.onClick(MainActivity.java:34)
                                                             at android.view.View.performClick(View.java:4438)
                                                             at android.view.View$PerformClick.run(View.java:18422)
                                                             at android.os.Handler.handleCallback(Handler.java:733)
                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                             at android.os.Looper.loop(Looper.java:136)
                                                             at android.app.ActivityThread.main(ActivityThread.java:5017)
                                                             at java.lang.reflect.Method.invokeNative(Native Method)
                                                             at java.lang.reflect.Method.invoke(Method.java:515)
                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:813)
                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
                                                             at dalvik.system.NativeStart.main(Native Method)

A: Android HttpGet android.os.NetworkOnMainThreadException
From here, I found the answer, actually the methodology which is about network operation should be in background task.
Maybe this will help for others to shorten the time they are spending for research.
Regards.


text:
Q: Cross derivatives using finite differences I am numerically calculating the derivatives of a scalar function u(x,y) in a domain defined in a 2D-Cartesian grid (x,y) implementing finite differences. I have been using a centred scheme so far, but would now like to account for the possibility that my domain may have holes. For example, u(x+1,y) may not be assigned a value and thus cannot be used to compute u(x,y) or u(x+2,y).
For the first derivatives, I replace the centered scheme for a one-sided scheme as needed (and set it to 0 if both relevant neighbours are missing). For the second derivative, I can rewrite:
dudx2 = (u[x - 1][y] + u[x + 1][y] - 2 * u[x][y]) / (dx*dx);
as
dudx2 = (isdomain[x-1][y]*(u[x-1][y]-u[x][y]) + isdomain[x+1][y]*(u[x+1][y]-u[x][y])) / (dx*dx);
I am struggling to write the cross-derivative in an appropriate format. Before, I had:
dudxdy = (u[x + 1][y + 1] + u[x - 1][y - 1] - u[x + 1][y - 1] - u[x - 1][y + 1])/(4*dx*dx);
By expanding u[x+1][y+1] and u[x-1][y-1] as a Taylor series, it seems to be I should be able to write:
dudxdy = (isdomain[x-1][y-1]*(u[x-1][y-1]-u[x][y]) + isdomain[x+1][y+1]*(u[x+1][y+1]-u[x][y])) / (2*dx2) - 0.5*(dudx2+dudy2);
But some quick numerical tests tell me this is not right. (Why not?)
Do you have any suggestions on how I can get round this problem? The context is the numerical solution of an anisotropic reaction-diffusion equation in this perforated domain.
Many thanks!
Marta

A: For the first derivative, you are right. You can either use
$$\frac{\partial u(x)}{\partial x} = \frac{1}{2dx}(u[x+1] - u[x-1]) + O(dx^2)$$
or
$$\frac{\partial u(x)}{\partial x} = \frac{1}{dx}(u[x+1] - u[x]) + O(dx)$$
(The first version is generally preferred due to the smaller error term). Note that in both cases you need to evaluate $u$ at exactly two points (though more could be used to improve accuracy, but thats not the point here).
Now for the second derivative, you will always need do evalue (at least) three points. The best numerical accuracy will be achieved with the symmetric formula
$$ \frac{\partial^2u(x)}{\partial x^2} = \frac{1}{dx^2}(u[x+1]-2u[x]+u[x-1]) + O(dx^2)$$
But in principle any three points can be used (if they are too far away from $x$, the accuracy will be very bad). For example at a border you might use
$$ \frac{\partial^2u(x)}{\partial x^2} = \frac{1}{dx^2}(u[x+2]-2u[x+1]+u[x]) + O(dx)$$
This means that you formula for the second derivative is wrong (even in the 1-dimensional case). It is impossible to estimate the second derivative using only two points.
EDIT 1 (cross-derivative):
Your cross-derivative formula is incorrect even without any holes. The commenly used symmetric one is
$$\frac{\partial^2 u(x,y)}{\partial x\partial y} = \frac{\partial}{\partial y}\frac{\partial u(x,y)}{\partial x}\\=\frac{\partial}{\partial y}\left(\frac{1}{2dx}(u[x+1][y] - u[x-1][y])\right) = \frac{1}{4dx dy}\left(u[x+1][y+1] - u[x+1][y-1] - u[x-1][y+1] + u[x-1][y-1]\right) + \text{error-terms}$$
(You might note that these are four terms. Theoretically, a version with three terms is possible, but on a rectangular grid this would always be asymmetric and thus have bad accuracy)
EDIT 2 (your intuition about Neumann-Boundary):
There is another basic approach to dealing with holes: removing them by giving them a value and then use the nice symmetric formulas for derivatives. There are multiple approaches of doing so, for example:

*

*just set $u[x] = 0$ (Dirichlet boundary)

*set it equal to a neighbour $u[x] = u[x+1]$ (Neumann boundary, which you effectively did)

*interpolation (if you have values on both sides of the hole): $u[x] = \frac{1}{2} (u[x+1]+u[x-1])$
If you know which one of these is sensible for your problem, go ahead and use it. But this depends very much on the physical problem you are trying to model. I.e. what does a hole in your system mean? Should the physical sytem actually have a hole there, or is just the simulation missing a point? (I dont know your problem well enough to answer this)


text:
Q: PHP CURL requests gets force redirected to "www", direct request doesnt For some reason, when I am making a CURL call to a test URL on my server, the request gets forcefully kicked off to a URL with "www". VirtualHost does not have any settings to modify the URL, htaccess does not seem to either. When making a direct request to 'http://sub.domain.com/test.html' in the browser, I get actual page contents.
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://sub.domain.com/test.html');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);

$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close ($ch);

return varDumpToString($info);

This returns:
array(22) {
    ["url"]=>
    string(37) "http://sub.domain.com/test.html"
    ["content_type"]=>
    string(29) "text/html; charset=iso-8859-1"
    ["http_code"]=>
    int(301)
    ["header_size"]=>
    int(311)
    ["request_size"]=>
    int(68)
    ["filetime"]=>
    int(-1)
    ["ssl_verify_result"]=>
    int(0)
    ["redirect_count"]=>
    int(0)
    ["total_time"]=>
    float(0.003001)
    ["namelookup_time"]=>
    float(0.000552)
    ["connect_time"]=>
    float(0.002219)
    ["pretransfer_time"]=>
    float(0.002226)
    ["size_upload"]=>
    float(0)
    ["size_download"]=>
    float(331)
    ["speed_download"]=>
    float(110296)
    ["speed_upload"]=>
    float(0)
    ["download_content_length"]=>
    float(331)
    ["upload_content_length"]=>
    float(0)
    ["starttransfer_time"]=>
    float(0.002958)
    ["redirect_time"]=>
    float(0)
    ["certinfo"]=>
    array(0) {
    }
    ["redirect_url"]=>
    string(41) "http://www.sub.domain.com/test.html"
}

Any help? Thanks.


text:
Q: How can the trivial representation not be in some $R\otimes R$? Where do I foul up?
In (e.g.) $SU(3)=A_2$ the tensor product $(1,0)\otimes (1,0)=(2,0)+(0,1)$. No $(0,0)$.
But on the other hand still $(1,0)\otimes (0,0)=(1,0)$. This immediately begs
the question

*

*what happened to Schur's lemma and

*imagine some 6j symbol $(ABC|DEF)$ where $A=B=(1,0)$, $C=(0,0)$. Is $ABC$ no admissible triangle and the 6j vanishes?

My only idea is that the Dynkin diagram is symmetric and you first
must symmetrize/antisymmetrize over the reps to get the correct ones,
i.e. the proper irreps in this case would be $((1,0)+(0,1))/V2$ and
$((1,0)-(0,1))/V2$. (And what does this do to the dimensions? Same as
$(1,0)$ and $(0,1)$, I think.)

A: The trivial representation lies in the tensor product of two irreducible representations $A\otimes B$ if and only if $B$ is the dual representation to $A$. For this group, $R$ is not self-dual, so we would expect the trivial to appear in $(1,0)\otimes (0,1)$, and it does: $(1,0)\otimes (0,1)=(1,1)\oplus (0,0)$.


text:
Q: PHP system() not working on Laravel Forge Locally, I have a class created that creates zip files with no issues.
When pushed up to the server however it is having issues. Its a Laravel Spark app, on Laravel Forge servers.
I've tried to debug normally returning the system() method gives some response, on the server I get nothing output when retuning this method.
The issue is that i'm calling a response download method for the zip file that should have been created. However I am getting file not found and I can only link it to the system() method.
Heres the code i'm using to create the zip:
 echo system('zip -j -P ' .$this->password. ' ' .$this->getZipStoragePath(). ' ' .storage_path('app/').$this->getFilePath());

Is there any chance that the server might not allow me to use the system method? Its all I can debug it to right now?

A: You most probably get an error from the function. To capture it, run the function with the stream redirection operator 2>&1 appended to your command:
$output = system('zip -j -P ' . $this->password . ' ' . $this->getZipStoragePath() . ' ' . storage_path('app/') . $this->getFilePath() . ' 2>&1');

var_dump($output);

It could also be worth to check out whether the function is enabled at all on your server.
In your php.ini file, look for the disable_functions directive. It might look like this:
disable_functions=show_source, system, shell_exec

A: Solved this one by trying to run 'zip' on the server but received:
The program 'zip' is currently not installed. You can install it by typing: sudo apt install zip

Running this allowed the zip feature to work.


text:
Q: Lua - Download via http and https (Lua 5.1 embedded) I'm sure this is not a unique question about Lua 5.1 (especially an embedded instance, where you can't install modules, your only options is pure Lua files/reference, therefore I can't install something like luacurl ). I've seen this matter referred to in various SO places, and tried them, but I can't seem to find a fix to make an https file download request work in this particular Lua environment..
To give you an example, the code below aims to download 2 different files, the http call works fine, returning a 200 code, but the https one doesn't, it doesn't return anything ?
Both targets can be access directly via the browser..
Please could some highlight what I'm missing in the https call to make it work?
print("--------DOWNLOAD http---------")

local http = require("socket.http")
local body, code = http.request("http://pbs.twimg.com/media/CCROQ8vUEAEgFke.jpg")
print(code)
if not body then error(code) end
local f = assert(io.open('mnt/nas/webtest1.jpg', 'wb')) -- open in "binary" mode
f:write(body)
f:close()

print("--------DOWNLOAD https---------")

local https = require "ssl.https" --luasec
local body, code = https.request("https://u.cubeupload.com/jbcooper/16146313918060.jpg")
print(code)
if not body then error(code) end
local f = assert(io.open('mnt/nas/webtest2.jpg', 'wb')) -- open in "binary" mode
f:write(body)
f:close()

As requested, the following returns nothing at all..
local https = require "ssl.https" --luasec
print(https.request("https://u.cubeupload.com/jbcooper/16146313918060.jpg"))

If it helps, if I run the following it returns 0.4
local https     = require("ssl.https")
local httpsVersion = string.sub(https._VERSION,1,3)
print (httpsVersion)


text:
Q: Pandas import error when debugging using PVTS I am dealing with a very silly error, and wondering if any of you have the same problem. When I try to import pandas using import pandas as pd I get an error in copy.py. I debugged into the pamdas imports, and I found that the copy error is thrown when pandas tries to import this:  from pandas.io.html import read_html

The exception that is throwns is:
un(shallow)copyable object of type <type 'Element'>
I do not get this error if I try to straight up run the code and not use the PVTS debugger. I am using the python 2.7 interpreter, pandas version 0.12 which came with the python xy 2.7.5.1 distro and MS Visual Studio 2012.
Any help would be appreciated. Thanks!

A: This is a limitation of the way PTVS detects unhandled exceptions - it can't see the except-block that's going to catch this exception because it is in the code that is eval'd from a string. See the bug in the tracker for more details.
As a workaround, disable "Debug standard library" checked in Tools -> Options -> Python Tools -> Debugging - this should cause the exception to be ignored.

A: I had the same problem for a while,  disabling "Debug standard library" didn't help, then I downloaded the latest version of Python (3.4), pip installed the libs (for example NLTK), and it worked!

A: I had a system crash while developing a PTVS app and then ran into this problem, re-running the Intellisense 'refresh DB' cleared it.

A: I faced the same issue, but just hitting 'Continue' will cause it to be ignored and the code execution will proceed in the usual way.
Or you could uncheck the "Break when this exception type is user-handled" option that comes up in the dialog box displaying the error.


text:
Q: How close do you have to be to someone to have a Room Match with them in Pokemon Duel? In Pokemon Duel, when I try to go into the Room Match module, I sometimes get a message telling me that the game could not read my GPS location.
In Version 3.0.6 for Android, the current version as of April 15, 2017, the message is:

Your location could not be established. Please check your device's GPS settings and ensure they are set to ON.

How does location factor into Room Matches? Is there a maximum distance that you can be from someone before you are unable to have a Room Match with them? Considering that I am almost always able to find at least a dozen other available players ready to duel, it would seem that the requirement for physical proximity is rather loose, if it even exists at all.

A: To join a Room Match, you need to know the room number and also the room code(if there is one). It doesn't depend on distance. You can even join a room match with someone on the other side of the planet.


text:
Q: How can i set a background image like that? Have a look at this website: http://www.omnomburger.at/. As you can, see when scroling down it looks like the background image is fixed. And one of those pages is like a window, through which you can see the background image. How can i create this effect?

A: This is what you might wanna do
body {
        background-image: url(path to img);
        background-repeat: no-repeat;
        background-attachment: fixed;
    }


text:
Q: Insert an image into a BIRT report with a secured URL I wanted to load an image in my report with an URL.
The following stackoverflow question answers that.
How to insert an image into a BIRT report with an URL properly?
However, my URL is not public and requires authentication to access. Like, adding an Authorization token in the header.
How can I intercept the request to insert Authorization token?

A: You could add a new "Scripted Data Source" and write your request in JavaScript with the required authorization token to load the Image data into your Data Source.
Then you add a data Set to get the data from the scripted data source. Afterwards you add the Image as "Dynamic image" and load the data from the Data Set that gets the data from your scripted data source. This is a bit complicated, but it should be possible.
Please search for tutorials for creating a scripted data source by yourself. This is a complex field but opens up a lot of possibilities.