text:
Q: GalaSoft_MvvmLight_Command:EventToCommand on a button on a ListItem? What is the syntax for hooking up a mvvm-light EventToCommand on a line item in a data template?  For an action on the main model, syntax like the below works fine, however if I am doing an operation on a line item in a data template, the binding isn't working, and I need to identify the specific line item to operate on.
Before attempting to hook up the Event to Command I had the line item click hooked to an event handler in the XAML codebehind; the handler extracted the line item data object out of the event args, and then passed the line item data object to a method via the DataContext to the view model and that worked fine, but I wanted to stay consistent with handling across the app.
Runtime error in output:
System.Windows.Data Error: BindingExpression path error: 'EditLineCommand' property not found on 'Model.LineItem'. BindingExpression: Path='EditLineCommand' DataItem='Model.LineItem'; target element is 'System.Windows.Controls.Button' (Name='EditRowButton'); target property is 'DependencyPropertyListener39' (type 'System.Object')..
XAML main layout:
<!-- Line Items -->
<ListBox ItemTemplate="{StaticResource LineItemTemplate}" ItemsSource="{Binding Model.LineItems}"/>

XAML data template:
<DataTemplate x:Key="LineItemTemplate">
<Button>
<Image Source="..." />
<Custom:Interaction.Triggers>
<Custom:EventTrigger EventName="Click">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding EditLineCommand, Mode=OneWay}" />
</Custom:EventTrigger>
</Custom:Interaction.Triggers>
</Button>
</DataTemplate>

Update - I think I'm almost there, @Claus' answer got me most of the way by solving the Command binding problem.  To identify the specific line to operate on, I bind to the LineNumber of the LineItem and then pull that parameter out on the relay command:
<GalaSoft_MvvmLight_Command:EventToCommand
Command="{Binding DataContext.DeleteLineCommand, ElementName=DetailPage}"
CommandParameter="{Binding LineNumber}"
PassEventArgsToCommand="True" />

...
public RelayCommand<int> DeleteLineCommand { get; private set; }

...
DeleteLineCommand = new RelayCommand<int>((ln) => { DeleteLineItem(ln); });

This is a workable solution, but is there a way to bind to the full LineItem rather than just a member?

A: See Bind datagrid to one ViewModel, column / combobox to another for a discussion on how to bind to a property (or command) of a view model from a data template.

A: Magic trick:
<phone:PhoneApplicationPage x:Name="MyPage" ... >
    ...
    <GalaSoft_MvvmLight_Command:EventToCommand
        Command="{Binding DataContext.EditLineCommand, ElementName=MyPage}" />
    ...
</phone:PhoneApplicationPage>

That way, it'll use the Page's DataContext, which usually is your ViewModel.


text:
Q: KMS / Office 2010... please point to documentation Trying to find out how to "modify" KMS to also accept the Office 2010 KMS key. Can anyone point me to some document about this?
Basically - do I have to install an update to KMS? I wand my KMS server to authenticate both, Windows (It currently has a DataCenter R2 KMS key installed) as well as Office 2010. Keys are available ;)
I can not imagine I just ptu it in - would this not overwrite the DataCenter key? I tried the MSDN website, but there is no clear document visible for my question.

A: Self-answer:
I needed to download http://www.microsoft.com/downloads/details.aspx?FamilyID=97b7b710-6831-4ce5-9ff5-fdc21fe8d965&displayLang=en - the Office 2010 KMS Host License Pack.
This modifies KMS to also activate Office, as the stock KMS is not able to ;)

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL accepting local, local network and external connections with bind-address? I'd like to access MySQL internally (localhost), externally (from the machine's external ip), as well as by it's local network address. The idea is that requests from our webserver, which is also apart of the same network, won't have to leave the local network and come back in.
The problem I have is getting MySQL to accept requests to it's local address, as mf.cnf has the "bind-address" option set as the machine's external ip.
I've read that setting bind-address 0.0.0.0 as an option, but is that the most ideal approach? I would probably need to setup iptables to drop any requests to mysql/3306 that don't come from my approved ip's.
That said, a tracert from the web server machine to mysql machine's external ip is only two hops, is it even worth it?

A: As I understand, you just need to accept MySQL connections from all "directions"? bind 0.0.0.0:3306 would be enough. Why do you want to use iptables?


text:
Q: Php mail is erratic: sometimes sends, sometimes doesn't I have a server set up to use postfix to send mail from the server.
When a user registers at my Wordpress site, an email is sent to the administrators, both of whom have gmail addresses.
Sometimes it works and the emails are sent out to the administrators.
Sometimes the mail works fine
    Apr  2 16:39:32 server postfix/cleanup[7279]: 433319E245CB: message-id=<20160402163903.426959E245CC@mail.example.com>
    Apr  2 16:39:32 server postfix/smtpd[7289]: disconnect from localhost.localdomain[127.0.0.1]
    Apr  2 16:39:32 server postfix/qmgr[3806]: 433319E245CB: from=<www-data@example.co.uk>, size=1174, nrcpt=2 (queue active)
    Apr  2 16:39:32 server amavis[19869]: (19869-06) Passed CLEAN {RelayedOpenRelay}, <www-data@example.co.uk> -> <bwisxxxxxx@gmail.com>,<dgcoxxxxxx@gmail.com>, Message-ID: <20160402163903.426959E245CC@mail.example.com>, mail_id: kPBazIRbRnM0, Hits: 1.74, size: 760, queued_as: 433319E245CB, 28866 ms
    Apr  2 16:39:32 server postfix/smtp[7284]: 426959E245CC: to=<bwisxxxxxx@gmail.com>, relay=127.0.0.1[127.0.0.1]:10024, delay=29, delays=0.19/0.05/0.01/29, dsn=2.0.0, status=sent (250 2.0.0 from MTA(smtp:[127.0.0.1]:10025): 250 2.0.0 Ok: queued as 433319E245CB)
    Apr  2 16:39:32 server postfix/smtp[7284]: 426959E245CC: to=<dgcoxxxxxx@gmail.com>, relay=127.0.0.1[127.0.0.1]:10024, delay=29, delays=0.19/0.05/0.01/29, dsn=2.0.0, status=sent (250 2.0.0 from MTA(smtp:[127.0.0.1]:10025): 250 2.0.0 Ok: queued as 433319E245CB)
    Apr  2 16:39:32 server postfix/qmgr[3806]: 426959E245CC: removed
    Apr  2 16:39:32 server postfix/smtp[7292]: 433319E245CB: to=<bwisxxxxxx@gmail.com>, relay=gmail-smtp-in.l.google.com[2a00:1450:4013:c00::1b]:25, delay=0.56, delays=0.01/0.02/0.2/0.33, dsn=5.7.1, status=bounced (host gmail-smtp-in.l.google.com[2a00:1450:4013:c00::1b] said: 550-5.7.1 [2a00:d880:5:87f::4927] Our system has detected that this message does 550-5.7.1 not meet IPv6 sending guidelines regarding PTR records and 550-5.7.1 authentication. Please review 550-5.7.1  https://support.google.com/mail/?p=ipv6_authentication_error for more 550 5.7.1 information. q140si4479035wmg.33 - gsmtp (in reply to end of DATA command))
    Apr  2 16:39:32 server postfix/smtp[7292]: 433319E245CB: to=<dgcoxxxxxx@gmail.com>, relay=gmail-smtp-in.l.google.com[2a00:1450:4013:c00::1b]:25, delay=0.56, delays=0.01/0.02/0.2/0.33, dsn=5.7.1, status=bounced (host gmail-smtp-in.l.google.com[2a00:1450:4013:c00::1b] said: 550-5.7.1 [2a00:d880:5:87f::4927] Our system has detected that this message does 550-5.7.1 not meet IPv6 sending guidelines regarding PTR records and 550-5.7.1 authentication. Please review 550-5.7.1  https://support.google.com/mail/?p=ipv6_authentication_error for more 550 5.7.1 information. q140si4479035wmg.33 - gsmtp (in reply to end of DATA command))

But sometimes the emails are never sent:
    Apr  2 22:04:11 server postfix/pickup[16625]: 5082F9E245EF: uid=33 from=<www-data>
    Apr  2 22:04:11 server postfix/cleanup[18820]: 5082F9E245EF: message-id=<20160402220411.5082F9E245EF@mail.example.com>
    Apr  2 22:04:11 server postfix/qmgr[3806]: 5082F9E245EF: from=<www-data@example.co.uk>, size=761, nrcpt=2 (queue active)
    Apr  2 22:04:11 server postfix/smtp[18824]: connect to 127.0.0.1[127.0.0.1]:10024: Connection refused
    Apr  2 22:04:11 server postfix/smtp[18824]: 5082F9E245EF: to=<bwisxxxxxx@gmail.com>, relay=none, delay=0.07, delays=0.06/0.01/0/0, dsn=4.4.1, status=deferred (connect to 127.0.0.1[127.0.0.1]:10024: Connection refused)
    Apr  2 22:04:11 server postfix/smtp[18824]: 5082F9E245EF: to=<dgcoxxxxxxx@gmail.com>, relay=none, delay=0.07, delays=0.06/0.01/0/0, dsn=4.4.1, status=deferred (connect to 127.0.0.1[127.0.0.1]:10024: Connection refused)

I am at a loss to figure it out
=====Added 6th April 2016=======
Mail has stopped being sent by phpmail. My mail.log has this:
    Apr 6 06:05:16 localhost postfix/pickup[15610]: 4D0879E27098: uid=33 from=<www-data>
    Apr 6 06:05:16 localhost postfix/cleanup[17898]: 4D0879E27098: message-id=<20160406060516.4D0879E27098@example.co.uk>
    Apr 6 06:05:16 localhost postfix/qmgr[29829]: 4D0879E27098: from=<www-data@example.co.uk>, size=793, nrcpt=3 (queue active)
    Apr 6 06:05:16 localhost amavis[18554]: (18554-07) NOTICE: reconnecting in response to: err=2006, HY000, DBD::mysql::st execute failed: MySQL server has gone away at (eval 111) line 170, <GEN38> line 20469.
    Apr 6 06:05:22 localhost postfix/smtpd[17907]: connect from localhost.localdomain[127.0.0.1]
    Apr 6 06:05:22 localhost postfix/smtpd[17907]: A9F9B9E27097: client=localhost.localdomain[127.0.0.1]
    Apr 6 06:05:22 localhost postfix/cleanup[17898]: A9F9B9E27097: message-id=<20160406060516.4D0879E27098@example.co.uk>
    Apr 6 06:05:22 localhost postfix/qmgr[29829]: A9F9B9E27097: from=<www-data@example.co.uk>, size=1210, nrcpt=3 (queue active)
    Apr 6 06:05:22 localhost postfix/smtpd[17907]: disconnect from localhost.localdomain[127.0.0.1]
    Apr 6 06:05:22 localhost amavis[18554]: (18554-07) Passed CLEAN {RelayedOpenRelay}, <www-data@example.co.uk> -> <bwisexxxx@gmail.com>,<dgcxxx@gmail.com>,<dgcxxx@hotmail.co.uk>, Message-ID: <20160406060516.4D0879E27098@example.co.uk>, mail_id: 93X8pKlGq9Sh, Hits: 1.74, size: 792, queued_as: A9F9B9E27097, 6338 ms
    Apr 6 06:05:22 localhost postfix/smtp[17901]: 4D0879E27098: to=<bwisexxxx@gmail.com>, relay=127.0.0.1[127.0.0.1]:10024, delay=6.5, delays=0.08/0.02/0.09/6.3, dsn=2.0.0, status=sent (250 2.0.0 from MTA(smtp:[127.0.0.1]:10025): 250 2.0.0 Ok: queued as A9F9B9E27097)
    Apr 6 06:05:22 localhost postfix/smtp[17901]: 4D0879E27098: to=<dgcxxx@gmail.com>, relay=127.0.0.1[127.0.0.1]:10024, delay=6.5, delays=0.08/0.02/0.09/6.3, dsn=2.0.0, status=sent (250 2.0.0 from MTA(smtp:[127.0.0.1]:10025): 250 2.0.0 Ok: queued as A9F9B9E27097)
    Apr 6 06:05:22 localhost postfix/smtp[17901]: 4D0879E27098: to=<dgcxxx@hotmail.co.uk>, relay=127.0.0.1[127.0.0.1]:10024, delay=6.5, delays=0.08/0.02/0.09/6.3, dsn=2.0.0, status=sent (250 2.0.0 from MTA(smtp:[127.0.0.1]:10025): 250 2.0.0 Ok: queued as A9F9B9E27097)
    Apr 6 06:05:22 localhost postfix/qmgr[29829]: 4D0879E27098: removed
    Apr 6 06:05:23 localhost postfix/smtp[17910]: A9F9B9E27097: to=<bwisexxxx@gmail.com>, relay=gmail-smtp-in.l.google.com[2a00:1450:4013:c01::1b]:25, delay=0.77, delays=0.02/0.03/0.33/0.39, dsn=5.7.1, status=bounced (host gmail-smtp-in.l.google.com[2a00:1450:4013:c01::1b] said: 550-5.7.1 [2a00:d880:5:87f::4927] Our system has detected that this message does 550-5.7.1 not meet IPv6 sending guidelines regarding PTR records and 550-5.7.1 authentication. Please review 550-5.7.1  https://support.google.com/mail/?p=ipv6_authentication_error for more 550 5.7.1 information. k188si1960277wmd.53 - gsmtp (in reply to end of DATA command))
    Apr 6 06:05:23 localhost postfix/smtp[17910]: A9F9B9E27097: to=<dgcxxx@gmail.com>, relay=gmail-smtp-in.l.google.com[2a00:1450:4013:c01::1b]:25, delay=0.77, delays=0.02/0.03/0.33/0.39, dsn=5.7.1, status=bounced (host gmail-smtp-in.l.google.com[2a00:1450:4013:c01::1b] said: 550-5.7.1 [2a00:d880:5:87f::4927] Our system has detected that this message does 550-5.7.1 not meet IPv6 sending guidelines regarding PTR records and 550-5.7.1 authentication. Please review 550-5.7.1  https://support.google.com/mail/?p=ipv6_authentication_error for more 550 5.7.1 information. k188si1960277wmd.53 - gsmtp (in reply to end of DATA command))
    Apr 6 06:05:24 localhost postfix/smtp[17911]: A9F9B9E27097: to=<dgcxxx@hotmail.co.uk>, relay=mx4.hotmail.com[65.55.37.120]:25, delay=1.8, delays=0.02/0.04/1.5/0.19, dsn=5.0.0, status=bounced (host mx4.hotmail.com[65.55.37.120] said: 550 SC-001 (COL004-MC4F18) Unfortunately, messages from xxx.xxx.xxx.xxx weren't sent. Please contact your Internet service provider since part of their network is on our block list. You can also refer your provider to http://mail.live.com/mail/troubleshooting.aspx#errors. (in reply to MAIL FROM command))
    Apr 6 06:05:24 localhost postfix/smtp[17911]: A9F9B9E27097: lost connection with mx4.hotmail.com[65.55.37.120] while sending RCPT TO
    Apr 6 06:05:24 localhost postfix/cleanup[17898]: 7528D9E27099: message-id=<20160406060524.7528D9E27099@example.co.uk>
    Apr 6 06:05:24 localhost postfix/qmgr[29829]: 7528D9E27099: from=<>, size=5791, nrcpt=1 (queue active)
    Apr 6 06:05:24 localhost postfix/bounce[17913]: A9F9B9E27097: sender non-delivery notification: 7528D9E27099
    Apr 6 06:05:24 localhost postfix/qmgr[29829]: A9F9B9E27097: removed
    Apr 6 06:05:24 localhost dovecot: lmtp(17915): Connect from local
    Apr 6 06:05:24 localhost dovecot: auth-worker(17916): mysql(127.0.0.1): Connected to database mailserver
    Apr 6 06:05:24 localhost postfix/lmtp[17914]: 7528D9E27099: to=<www-data@example.co.uk>, relay=example.co.uk[private/dovecot-lmtp], delay=0.06, delays=0/0.01/0.01/0.03, dsn=5.1.1, status=bounced (host example.co.uk[private/dovecot-lmtp] said: 550 5.1.1 <www-data@example.co.uk> User doesn't exist: www-data@example.co.uk (in reply to RCPT TO command))
    Apr 6 06:05:24 localhost dovecot: lmtp(17915): Disconnect from local: Client quit (in reset)
    Apr 6 06:05:24 localhost postfix/qmgr[29829]: 7528D9E27099: removed

A: In your second set of log entries, it appears that amavis is not running, so the mail can't be scanned for viruses, and thus it gets held in queue until such time as someone comes along and restarts amavis.


text:
Q: Canvas a bit too big? In http://onlyabutton.com/, when you press the left and right arrow keys, the window shakes a bit, most likely because of canvas dimensions. How do I fix this? Help would be appreciated!

A: You just have to add:
html, body {
    margin: 0;
}

You set the canvas width to 100% of the window size but forget to subtract the margin of body.


text:
Q: VBA Check if File Exists on Sharepoint Site After some searching I cant find a solution to my issue. I have multiple files that are saved to a sharepoint site with variable names each month.  I have the files saving correctly with the variable name.  I used the "filename" dim as the path for saving so I know that works.
What i am trying to do is have vba check to see if that name is already exists on the sharepoint site to prevent a user from overwritting existing files.  Below is the code I put together from browsing around on the web.  Using F8 to run the vba code line by line, I get error:

Bad file name or number

Any thoughts to get this to run correctly?
    sub test()
    Dim filename As String ''''filename is the sharepoint site and file name
    DirFile = filename
    If Len(Dir(filename)) = 0 Then
    Else
    MsgBox "File already exists on sharepoint site"
    Exit Sub
    End If
    End Sub


text:
Q: Can't get response from json I'm trying to get the response from json but I get a nullpointer error
Here is my retrofit interface
public interface RequestGeo {

@Headers("user-key: mykey")
@GET("geocode?lat=49.195061&lon=16.606836")
Call<JSONResponse> getJSON();
}

On my MainActivity i got this code
private void loadJSON() {
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://developers.zomato.com/api/v2.1/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RequestGeo request = retrofit.create(RequestGeo.class);
    Call<JSONResponse> call = request.getJSON();
    call.enqueue(new Callback<JSONResponse>() {
        @Override
        public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {

            JSONResponse jsonResponse = response.body();
            geoCodeData = new ArrayList<>(Arrays.asList(jsonResponse.getGeocode()));
            adapter = new RestaurantListAdapter(geoCodeData);
            recyclerView.setAdapter(adapter);

        }

        @Override
        public void onFailure(Call<JSONResponse> call, Throwable t) {
            Log.d("Error", t.getMessage());
        }
    });
}

The nullpointerexception error is here
geoCodeData = new ArrayList<>(Arrays.asList(jsonResponse.getGeocode()));

Here is my jsonResponse.java file
public class JSONResponse {

    private Geocode[] geocode;

    public Geocode[] getGeocode(){
        return geocode;
    }
}

UPDATE
Geocode.java class where I write the variables exactly as the json objects I want to get (there are more but i don't want them).
@Entity
public class Geocode {

@NonNull
@PrimaryKey private String title;
private String latitude;
private String longitude;
private String city_name;

public Geocode(String title, String latitude, String longitude, String city_name) {
    this.title = title;
    this.latitude = latitude;
    this.longitude = longitude;
    this.city_name = city_name;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getLatitude() {
    return latitude;
}

public void setLatitude(String latitude) {
    this.latitude = latitude;
}

public String getLongitude() {
    return longitude;
}

public void setLongitude(String longitude) {
    this.longitude = longitude;
}

public String getCity_name() {
    return city_name;
}

public void setCity_name(String city_name) {
    this.city_name = city_name;
}
}


text:
Q: Extract first k characters of string in prolog Well, I'm very new in prolog and I'm trying to solve some simple recursive problems like the following.
Implement firstKCharacters(Str, K, L) function which gets the first K characters of string Str in the result string L. I've figured out the following solution:
firstKCharacters(_, 0, _):- !.
firstKCharacters([X|L1], K, L):- append([X], S1, L),
    X1 is K - 1, firstKCharacters(L1, X1, S1).

I'm confused about result:
?- firstKCharacters([a,b,c,d,e,f,g], 1, X).
X = [a|_1174]

Can someone explain what is the _1174 and why I'm getting a|_1174 isntead of a?

A: Your error is in the terminal version of firstKCharacters/3; writing
firstKCharacters(_, 0, _):- !.

you forget to fix the output list to a empty list; you should write it as follows
firstKCharacters(_, 0, []) :- !.

Without fixing it, remain a variable (the _ in third position) that isn't unified: your _1174.
A (off topic, I suppose) suggestion: avoid append and simply translate X from the left to the right list. I mean: write the other version of firstKCharacters/3 as follows
firstKCharacters([X|L1], K, [X|L]):-
    X1 is K - 1, firstKCharacters(L1, X1, L).

Because I donk like the cut, I propose you a version without it
firstKCharacters(_, 0, []).

firstKCharacters([X|L1], K, [X|L]):-
    K > 0,
    Km1 is K - 1,
    firstKCharacters(L1, Km1, L).


text:
Q: Hidding A button with JQuery with Conditions I have a table called report
and currently im trying to read what is the value in the status column in order to hide or display the retryBtn depending on the value in it.
I have also included the JQuery script by manually copy pasting the code & saving in into a file.
Right now I have wrote a JQuery code that runs on load, but it seems like it wasnt run at all as the log shows nothing. What is the reason that its not running, in the src folder the website is able to detect the JQuery.js script.
Any advice?
Table

            ID
            A
            B
            Status
             C
            D Path
             E
            E Path
             F
            F Path
            G
            G Path

while($row = $statement->fetch(PDO::FETCH_ASSOC)){

            $fullPSPath = $G_Path . $row['GPath'];
            $fullEPath = $E_Path  . $row['EPath'];
            $fullDPath = $D_Path  . $row['DPath'];
            $fullFPath = $F_Path  . $row['FPath'];
            echo "
"
            . "". $row['ID']."	"
                    . $row['A']."	" .$row['B']. "	". $row['Status'] . "	"
                    . $row['D']. "	" . " $fullDPath	"
                    . $row['E']. "	". " $fullEPath	"
                    . $row['F']. "	"
                    . " $fullFPath	"
                    . $row['G']. "	"
                    . " $fullGPath 	"
                    . "<button class='Retry' id='retryBtn'>Retry</button>	";//button here
            echo '
';
        }
        ?>

JQuery


text:
Q: Outlook 2016 macro to edit received email I would like to be able to add notes to received emails so that I can keep track of work I've done or need to do. We just switched from Lotus Notes to Office365 and after doing some research I've figured out how to edit a received email. You have to open the email then go to Actions --> Edit Message.
Those aren't too many steps but a keyboard shortcut or button would make it much faster.
I did some research and learned a bit about Macros. I don't know how to write VB and was wondering if anyone could give me a hand writing it.
These are the steps I would need:

*

*Open the currently selected email

*Make it editable

As a bonus I would like change the font color to red. It just delineates text I've added versus the original email.
Thanks, any help would be appreciated.

A: Thanks @victor, your comment led me to the right place.
This is what I used in case anyone else would like to know:
Sub OpenForEditing()
    ActiveExplorer.Selection(1).Display
    ActiveInspector.CommandBars.ExecuteMso "EditMessage"
End Sub


text:
Q: CSS, two columns - left with dynamic width (input), right with fixed (button) can somebody please point me to a solution for this?
HTML

    <input type="text" class="left" />
    <button class="right">Some button</button>

CSS
.container {
    display: table;
    width: 100%;
    background-color: red;
}

.left, .right {
   display: table-cell;
}

.right { width: 100px; }

Here is code pen sample: http://codepen.io/be-codified/pen/qdRRBY
Input field should be stretchable, button should be fixed positioned on right.
Thank you in advance.
// edit
I can not use table tag because layout needs to be responsive.

A: I gave the input a width of calc(100% - 110px) and the button a float:right which resulted in the following. Is that what you need? The input type you want to use is, as far as I know, not stretchable by the user.
CSS
.container {
  display: table;
  width: 100%;
  background-color: red;
}

.left, .right {
  display: table-cell;
}

.right {
  width: 100px;
  float: right;
}

input.left {
  width: calc(100% - 110px); //This makes sure the input area is as wide as possible, while also leaving space for the button. Play with the exact measurements to get what you need.
}

A: I suggest you to put the form elements into
, so don't change their default display properties, and then set the left input box to 100% width as needed.

.container {
  display: table;
  width: 100%;
  background-color: red;
}
.left, .right {
  display: table-cell;
}
.right {
  width: 100px;
}
.left input {
  width: 100%;
  box-sizing: border-box;
}

<input type="text" />

<button>Some button</button>

In fact, both left and right can have dynamic width, so right column always get the minimum width based on the button length.

.container {
  display: table;
  width: 100%;
  background-color: red;
}
.left, .right {
  display: table-cell;
  white-space: nowrap;
}
.left {
  width: 100%;
}
.left input {
  width: 100%;
  box-sizing: border-box;
}

<input type="text" />

<button>Some button</button>

A: Here is full responsive solution.
HTML

            <form>
                <input type="text" required="required" placeholder="Right Some thing" />
                <button type="submit" class="submit-button">Send</button>
            </form>

CSS
/* RESPONSIVE CSS */
.container{
    width: 100%;
}
.input-flied-box{
    width: 100%;
}
.input-flied-box input{
    padding: 6px 12px 6px 12px;
}
.submit-button{
    top: inherit;
    right: inherit;
    position: relative;
    margin-bottom: 15px;
}
@media (min-width: 768px){
.container{
    width: 750px;
}
.input-flied-box{
    width: 600px;
}
.input-flied-box input{
    padding: 6px 101px 6px 12px;
}
.submit-button{
    top: 14px;
    right: 14px;
    position: absolute;
    margin-bottom: 0;
}
}
@media (min-width: 992px){
.container{
    width: 960px;
}
}
@media (min-width: 1200px){
.container{
    width: 1170px;
}
}
/* RESPONSIVE CSS END */

*:after,
*:before{
box-sizing: border-box;
}
*{
box-sizing: border-box;
}

.container:after,
.container:before{
display: table;
content: " ";
clear: both;
}
.container{
margin-left: auto;
margin-right: auto;
}
.input-flied-box {
background-color: #666666;
margin-left: auto;
margin-right: auto;
padding-left: 15px;
padding-right: 15px;
position: relative;
}
.input-flied-box input {
background-color: #ffffff;
border: 1px solid #cccccc;
height: 40px;
margin-bottom: 15px;
margin-top: 15px;
width: 100%;
border-radius: 4px;
}
.submit-button {
background-color: #fc3850;
border: medium none;
border-radius: 4px;
color: #ffffff;
font-family: Arial;
line-height: 1;
padding: 13px 30px;
text-transform: uppercase;
}

https://jsfiddle.net/bL3wgrv9/


text:
Q: Access alternative through python and sqlite3 is there a way to build a standalone rapid embedded databases with forms as front-end like MS Access, using python and sqlite, by rapid i mean, a WYSIWYG GUI builder for forms (like Access form designer), which should also support subforms,
i search around and it might work with qt designer 4 + python + sqlite,
for the standalone deployment, i heard that you can turn python script to an .exe (for windows) that would rock!!!
my question:
any of you guys tried this? qt designer 4 +python + sqlite, would it replace MS Access?
i know there's Libreoffice base , but it's too big (170~ MB) and requires java -not really a standalone-
I'm pretty good at SQL so i don't care about SQL easy graphical designer
thanks

A: Dabo or Camelot may be what you're looking for, or at least close.


text:
Q: Using FILENAME in awk script #!/usr/bin/awk -f

{if(!FILENAME) {print "<Gasp.sh> <inputfile>"; exit} calc = 0;....}

I am trying to print out a usage statement in my awk script so if the script is run without an input file, it shows the usage. This is my attempt, but I assume I am not using the FILENAME variable correctly. I also tried putting the if statement in a BEGIN and END block but nothing has worked.

A: BEGIN{if (ARGC!=2) {print "<Gasp.sh> <inputfile>"; exit} {calc = 0;....}

A: Use ARGC instead;
BEGIN {
    if(ARGC==1) {
        print "<Gasp.sh> <inputfile>"
        exit
    }
    calc = 0
    # ...
}

Edit: Unfortunately @shaikisiegal deleted his answer so I will add this quote from GNU awk documentation section Built-in Variables here:
FILENAME
    This is the name of the file that awk is currently reading. When no data files are listed on the command line, awk reads from the standard input, and FILENAME is set to "-". FILENAME is changed each time a new file is read (see section Reading Input Files). Inside a BEGIN rule, the value of FILENAME is "", since there are no input files being processed yet.
Some early implementations of Unix awk initialized FILENAME to "-", even if there were data files to be processed. This behavior was incorrect, and should not be relied upon in your programs.


text:
Q: wordpress drag and drop post meta box page builder I am so tired to try to add a custom options to this my taken free source code for drag and drop purpose.
Can any one of you help me to add the custom options to this code.
add_action('admin_enqueue_scripts','enqueue_related_pages_scripts_and_styles');

    //defines the output for our related pages meta box
    function display_related_pages_meta_box($post){
        //create nonce
    wp_nonce_field('pages_meta_box','pages_meta_box_nonce');

    //collect related pages (if we already have some)
    $related_pages = get_post_meta($post->ID,'related_pages',true);

    //collect all pages on the website
    $page_args = array(
            'posts_per_page'    => -1,
            'post_type'         => 'page',
            'post_status'       => 'publish',
            'orderby'           => 'post_date',
            'order'             => 'DESC',
            'fields'            => 'ids'
        );
    $pages = get_posts($page_args);
    //if we have pages to display
    if($pages){
        echo '
';
            //left container (all pages)
            echo '
';
                echo '
 Listed below are the pages of your website.
';
                echo '
Drag these to the other container to add them as related page links
';
                //loop through all pages
                foreach($pages as $page){
                    //collect their id and name and create the page item
                    $page_id = $page;
                    $page_name = get_the_title($page_id);
                    echo '
';
                    echo    '
' . $page_name . '
';
                    echo    '
 Remove
';
                    echo '
';
                }
            echo '
';
            //end left container

            //Right container
    echo '
';
    echo    '
Drag pages from the left container onto this container
';
    //if we have previous saved related pages
    if(!empty($related_pages)){
        $related_pages_array = json_decode($related_pages);
        foreach($related_pages_array as $related_page){
            //page information
            $page_id = $related_page;
            $page_name = get_the_title($page_id);

            echo '
';
            echo    '
' . $page_name . '
';
            echo    '
 Remove
';
            echo    '<input type="hidden" name="related_pages[]" value="' . $page_id . '"/>';
            echo '
';
        }
    }
    echo    '

';
    echo '
';
        echo '

';
        echo '
';
    }
    }

This code is taken from the net. i want to know how to add a custom options to this, instead of default options using query in that above given code.


text:
Q: How to display individual datas in mysql through jquery autocomplete I am having a problem here
I want to display the datas in DB using autocomplete
But when I search in the textbox it is showing everything
for example
c++javaphpcoldfusionjavascriptaspruby

but what I want is
"c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"

here is my code
Controller
 function get_ingredients() {
          $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');

             $this->load->model("save_datas");
        $data["show_ingre"] = $this->save_datas->select_ingredient();
        $this->load->view("view_home", $data);
    }

View
<script>
            $(document).ready(function() {
                $("input#autocomplete").autocomplete({
                    source: ["<?php
foreach ($show_ingre as $ingre) {
    echo "$ingre->ingredient";
}
?>"]

                    });
                });
        </script>

   <?php echo form_open('home/save_input'); ?>
        <input type="text" name="ingredient" id="autocomplete" /><br/>
        <input type="submit" name="submit"/>
        <?php form_close(); ?>

Model
function select_ingredient() {
        $query = $this->db->query("SELECT ingredient FROM ingredients");
        return $query->result();
    }

A: The view file is messed up. Take a look at your pages source code. It should be something like this:
 <script>
 $(document).ready(function() {
     $("input#autocomplete").autocomplete({
         source: ["c++javaphpcoldfusionjavascriptaspruby"]
     });
 });
 </script>

I think you should be able to see the problem here. Anyways, if you didn't, here's the code to fix it:
<script>
$(document).ready(function() {
    $("input#autocomplete").autocomplete({
        source: [<?php
        foreach ($show_ingre as $ingre) {
            echo '"' . $ingre->ingredient . '", ';
        }
        ?>]
    });
});
</script>


text:
Q: How to set a custom object in a JTable row I should tell this first, this is NOT about Rendering a Table cell.
Here is the TableModel that i'm building using a 2D array based on a User object in my DB.
    List<User> userList = userManagerService.getAllUsers();

    /* String[] col_user = {"Username", "Name", "Phone", .... } */
    String[][] data = new String[userList.size()][col_user.length];
    int i = 0;
    for (User user : userList) {
        String[] userdata = new String[col_user.length];
        userdata[0] = user.getUserUsername();
        userdata[1] = user.getUserName();
        userdata[2] = user.getUserPhone();
        userdata[3] = user.getUserNic();
        userdata[4] = user.getUserAddress();
        userdata[5] = user.getUserEmail();

        data[i++] = userdata;
    }

    VstTableItemModel tiModel = new VstTableItemModel(data, col_user);
    dataTable.setModel(tiModel);

My problem is how can i get a User object back, using the selected row in the Table. Note that i can't make a new User object and populate it with the row data. I must get the queried User object(objects in userList). So, is their any way to set a Object with a table row ?
Here is my VstTableItemModel class.
public class VstTableItemModel extends AbstractTableModel {

    ArrayList<Object[]> data;
    String[] header;

    public VstTableItemModel(Object[][] obj, String[] header) {
        this.header = header;
        data = new ArrayList<Object[]>();

        for (int i = 0; i < obj.length; ++i) {
            data.add(obj[i]);
        }
    }

    @Override
    public int getRowCount() {
        return data.size();
    }

    @Override
    public int getColumnCount() {
        return header.length;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return data.get(rowIndex)[columnIndex];
    }

    @Override
    public String getColumnName(int index) {
        return header[index];
    }

}

A: Instead of splitting the User object up before you create the model, add it directly to the model and allow the model to do the work for you...
For example
public class VstTableItemModel extends AbstractTableModel {

    private List<User> users;

    public VstTableItemModel(List<User> users) {

        this.users = new ArrayList<User>(users);

    }

    @Override
    public int getRowCount() {
        return users.size();
    }

    @Override
    public int getColumnCount() {
        return 6;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {

        Object value = "??";
        User user = users.get(rowIndex);
        switch (columnIndex) {
            case 0:
                value = user.getUserUsername();
                break;
            case 1:
                value = user.getUserName();
                break;
            case 2:
                value = user.getUserPhone();
                break;
            case 3:
                value = user.getUserNic();
                break;
            case 4:
                value = user.getUserAddress();
                break;
            case 5:
                value = user.getUserEmail();
                break;
        }

        return value;

    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return // Return the class that best represents the column...
    }

    /* Override this if you want the values to be editable...
    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        //....
    }
    */

    /**
     * This will return the user at the specified row...
     * @param row
     * @return
     */
    public User getUserAt(int row) {
        return users.get(row);
    }

}

This way, you should be able to do something like...
List<User> userList = userManagerService.getAllUsers();
VstTableItemModel tiModel = new VstTableItemModel(userList);

Now when you need to...you can grab a the user that is represent at a specific row...
User user = tiModel.getUserAt(rowIndex);


text:
Q: How to remove the new-line characters from const char * type string I want to remove the new line characters from a string.
So far I am only able to find remove() function but I think begin() and end() is not supporting const char * type of string.
#include <iostream>
#include <algorithm>

using namespace std;

int main(){
    const char *a = "\n remove all \n the new line characters \n";
    cout << a << "\n";
    remove(a.begin(),a.end(),"\n");
    cout << a;
}

Error-
ctest.cpp: In function 'int main()':
ctest.cpp:9:11: error: request for member 'begin' in 'a', which is of non-class type 'const char*'
  remove(a.begin(),a.end(),"\n");
           ^
ctest.cpp:9:21: error: request for member 'end' in 'a', which is of non-class type 'const char*'
  remove(a.begin(),a.end(),"\n");

I also found the remove_if function on internet but it only support "isspace", "isdigit" type of filters. There was no "isnewline" and direct "\n" was throwing errors. I also found some traditional solutions which basically puts a loop on the whole string but I am avoiding those raw solutions as I am very new to this language.

A: First, make a writable by placing it into an array, because you cannot modify the content of const char*. Then use std::begin and std::end non-member functions to obtain the two ends of the sequence:
char a[] = "\n remove all \n the new line characters \n";
cout << a << "\n";
remove(std::begin(a), std::end(a), '\n');
cout << a;

Demo.
Note: It goes without saying that a better way of doing it in C++ would be using std::string.


text:
Q: Unable to Command-Line Build a Mixed Solution (.NET Framework with .NET Standard) Short Version: I've got a VS2017 solution with 2 .NET Standard 2.0 projects, a .NET Framework 4.6.2 class library, and .NET Framework 4.6.2 MVC WebApp.  What are the proper command line build utilities to restore all nuget packages and then build all projects in the solution?
Long Version: I've migrated a solution targeting .NET Framework 4.5 and Visual Studio Pro 2015 to Visual Studio Pro 2017 with some projects targeting .NET Framework 4.6.2 and some targeting .NET Standard 2.0.  According to https://github.com/dotnet/standard/blob/master/docs/versions.md, this specific version combination of Framework/Standard should be compatible.
Here is my solution as it stands today:
WebApp - MVC 5.0 ASP.NET web app project targeting .NET Framework 4.6.2.  This is an MVC web app that was created originally in Visual Studio 2013 and has been upgraded numerous times to keep up with .NET Framework upgrades.
ModelsLibrary - .NET Standard 2.0, targeting both Standard and 4.6.2*.  Contains nothing but plain-old C objects that are used throughout the solution.
LogicLibrary - .NET Standard 2.0, targeting both Standard and 4.6.2*.  Contains business logic that makes changes to our POCOs and/or makes calls to third-party services using data from our POCOs.
ServiceLibrary - .NET Framework 4.6.2 class library project.  Performs CRUD operations for the WebApp.  All objects fetched from, inserted into, or updated in the database are the POCOs from the ModelsLibrary project.  Cannot be updated to .NET Standard as we have heavy reliance upon linq to SQL throughout this project and linq to SQL is not implemented in .NET Standard.
TestsProject - .NET Framework 4.6.2 unit test project using Microsoft.VisualStudio.QualityTools.UnitTestFramework.  Performs basic unit testing on a small number of our key logic operations performed throughout the solution.  This project, if it is the problem, can be removed and a new test project can replace it in time.
*The CSProj files for the ModelsLibrary and LogicLibrary projects have the following lines:
<TargetFrameworks>netstandard2.0;net462</TargetFrameworks>
<TargetFrameworkIdentifier Condition="'$(_ShortFrameworkIdentifier)'=='net'">.NETFramework</TargetFrameworkIdentifier>
<TargetFrameworkIdentifier Condition="'$(_ShortFrameworkIdentifier)'=='netstandard'">.NETStandard</TargetFrameworkIdentifier>

The solution has the following references:
WebApp references LogicLibrary, ModelsLibrary, ServiceLibrary
LogicLibrary has project dependency on ModelsLibrary
ModelsLibrary has no project dependency
ServiceLibrary references ModelsLibrary
TestsProject references WebApp, ServiceLibrary, ModelsLibrary
The solution as a whole builds, runs, and can be published using the Visual Studio 2017 without any build errors or issues.  However, our continuous integration and continuous deployment system is completely inoperable.  To simplify this question, I am only asking how to perform a command-line build of my solution.  Once that is known, I can adapt our CI/CD solution to utilize the given commands.  The server where builds are to take place has VS2017Pro installed, the .NET Framework 4.7.1 targeting pack installed, and all appropriate updates.
Here is my generalized, pseudo-command idea of what I BELIEVE should take place in the build process:
1. pull latest code for the solution from source control
2. restore all nuget packages
3. build all projects in the solution.  My assumption is in this order: ModelsLibrary, LogicLibrary, ServiceLibrary, WebApp.
However, I'm getting tons of errors when I try and use command line tools to build.  Right off the hop:
dotnet restore ModelsLibrary
Errors in c:\MySolutionName\ModelsLibrary\ModelsLibrary.csproj
    Package Microsoft.AspNet.WebUtilities 1.0.0-rc1-final is not compatible with netstandard2.0 (.NETStandard,Version=v2.0). Package Microsoft.AspNet.WebUtilities 1.0.0-rc1-final supports:
      - dotnet5.4 (.NETPlatform,Version=v5.4)
      - net451 (.NETFramework,Version=v4.5.1)
    One or more packages are incompatible with .NETStandard,Version=v2.0.

NuGet Config files used:
    C:\Users\MyUserName\AppData\Roaming\NuGet\NuGet.Config
    C:\Program Files (x86)\NuGet\Config\Microsoft.VisualStudio.Offline.config

Feeds used:
    https://api.nuget.org/v3/index.json
    C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\

Why would this error out on the command line but show no issue whatsoever within Visual Studio 2017?  What is being done differently?  Ok, let's try a restore on the .NET Framework project that uses quite a few NuGet packages:
c:\MySolutionName>dotnet restore ServiceLibrary
  Nothing to do. None of the projects specified contain packages to restore.

But when I use NuGet 4.4.1, the currently recommended version, nuget packages are restored for this project without issue, but NuGet again shows the above error for the ModelsLibrary.
This is not the only issue, just one of many, many issues I encounter when I attempt to perform a command-line build for the solution.  To get around these package issues, I've restored the packages for using VisualStudio itself and then attempted builds with both "dotnet build" and msbuild (from the VisualStudio 2017 directory), and neither command will successfully build the solution.  Nor will using "dotnet build" on specific projects work.  Errors are simply too numerous to list here.
So the question boils down to this:
Why does this solution build fine within Visual Studio 2017 but not through the command line using dotnet/msbuild? What is being done differently in VS that allows a successful build?  What commands, and more importantly, what versions of the utilities, does Visual Studio 2017 Pro use to build a solution like this?

A: Short Version: Lex Li's suggestion was correct.  Starting from scratch did the trick and this crow sure does taste great.
Long version: I created a brand new solution in Visual Studio 2017 and created new versions of each of the projects using .NET Framework 4.7.1 and .NET Standard 2.0.  I then copied in all of the files from the original project and spent a long while resolving all of the nuget and dependency issues.  Once I could get the project to build again in visual studio, building within the command line was fairly simple.  One other glitch I ran into was an issue   Because my actual use case was within team city, here are the command line steps I am able to use to build my solution:
delete all of the files in the packages directory:
del %system.teamcity.build.workingDir%\packages /F /S /Q
rd /s /q %system.teamcity.build.workingDir%\packages

run nuget restore:
C:\TeamCity\buildAgent\tools\NuGet.CommandLine.4.6.1\tools\NuGet.exe restore %system.teamcity.build.workingDir%\MyWebProject\packages.config -PackagesDirectory %system.teamcity.build.workingDir%\packages -NonInteractive
dotnet restore %system.teamcity.build.workingDir%\MyModelsProject
dotnet restore %system.teamcity.build.workingDir%\MyLogicProject

build the solution:
"C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\bin\MSBuild.exe" %system.teamcity.build.workingDir%\MyWebProject.sln /p:Configuration=MyConfiguration /p:DeployOnBuild=true /p:PublishProfile=MyPublishProfile


text:
Q: DropBox file upload using core api https://api-content.dropbox.com/1/files// I am integrating dropbox in my app using OAuth 2.0 and now I want to upload a image using it's core api
https://api-content.dropbox.com/1/files//
my problem is there is no parameter shown for file upload (where i can send NSData)
DropBox documentation link :- https://www.dropbox.com/developers/core/docs  ( /files (POST) )
I don't want to upload file/image using DBRestClient because it requires two time of login one via webView (OAuth 2.0) and another one via it's internal framework and my app require OAuth 2.0 integration.

A: Look closer. The documentation says:
Request body: "The file contents to be uploaded. Since the entire POST body will be treated as the file, any parameters must be passed as part of the request URL. The request URL should be signed just as you would sign any other OAuth request URL."
So you need to upload the actual contents through the message body (where the POST data would go).
However, the documentation also recommends to use /files_put instead.


text:
Q: finditer and findall jumping over substrings I am trying to find all the occurrences of e.g. p='gg' inside s='ggggg'. Based on my count there should be 4 since any position apart from the last one is a substring. For example s[1:2] is 'gg'. However, trying both:
>re.findall('gg','ggggg')
['gg','gg']
>list(re.finditer('gg','ggggg'))
[<_sre.SRE_Match object; span=(0, 2), match='ab'>,
 <_sre.SRE_Match object; span=(6, 8), match='gg'>,
 <_sre.SRE_Match object; span=(8, 10), match='gg'>]

Seems to be skipping over potential matches once it finds some match. Also, as a result, the search for e.g. 'star' or 'start' is equivalent to just looking for start, since I would never find the second because the first is its prefix...
Is this a bug? How can I perform a full substring search ?
example 2:
>re.findall('star|start','starting')
['star']
>list(re.finditer('star|start','starting'))
[<_sre.SRE_Match object; span=(0, 4), match='star'>]

(I am using Python 3, re version 2.2.1)

A: import re
re.findall('gg','ggggg')

result in 2 matches as re.findall does not look for overlapping matches, or as re docs says

Return all non-overlapping matches of pattern in string, as a list of
strings.

So this is not a bug, but behavior compliant with documentation.
If you are allowed to use external modules you might harness regex following way:
import regex
print(re.findall('gg', 'ggggg', overlapped=True))

output:
['gg', 'gg', 'gg', 'gg']

A: The keyword you might searching for is "overlapping". Here is a linked question String count with overlapping occurrences.
From the re documentation.

find_all : Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.

It seem to be a feature not a bug.
You can implement you own search function like:
def my_search(s, substr):
    for i in len(s):
        if s[i:].startswith(substr):
            yield i


text:
Q: Diagonalization of $M=ab^t+ba^t$ Given $a=(a_i)_{i=1}^n$ and $b=(b_i)_{i=1}^n$ vectors in $\mathbb{R}^n$, we define the matrix $M=(m_{ij})_{i,j=1}^n$ as:
$$
m_{ij}=a_ib_j + a_jb_i,
$$
or equivalently
$$
M=ab^t+ba^t.
$$
Note that $a,b$ are also $n\times 1$ matrices, $a^t,b^t$ are $1\times n$ matrices.
What are the eigenvalues and eigenvectors of $M$?

A: We are considering the following two cases:
Case I. $a$, $b$ linearly dependent. Let for example $b=\mu a$, then $M=2\mu\, a a^t$. But the rank of $aa^t$ is 1, as all its columns are multiple of the first column (if the first is nonzero.), and hence its eigenvectors are $a$, with eigenvalue $\lambda= 2\mu\, a^ta$, and $n-1$ eigenvectors corresponding to $\lambda=0$, which constitute a basis of the kernel of $aa^t$.
Case II. If $a$, $b$ linearly independent (and hence ∥a∥,∥b∥≠0). Then
$$
Mx=\lambda x \,\,\Longleftrightarrow\,\, a(b^tx)+b(a^tx)=\lambda x,\tag{1}
$$
thus, if $\lambda\ne0$, then $x$ is a linear combination of $a$ and $b$. Hence $M$ has as eigenvalues $\lambda=0$ with multiplicity $n-2$, and eigenspace
$$
\{x:a^tx=b^tx=0\}.
$$
Also, setting $x=c_1a+c_2b$ in $(1)$ we obtain the system
$$
a^ta c_1+a^tb c_2=\lambda c_1, \quad a^tb c_1+b^tb c_2=\lambda c_2,
$$
which provides another two eigenvalues/eigenvectors. The eigenvalues satisfy the equation
$$
0=\left|
\begin{matrix}a^ta-\lambda & a^tb \\ a^tb & b^tb-\lambda \end{matrix}
\right|=\lambda^2-(|a|^2+|b|^2)\lambda+(|a|^2|b|^2-(a^tb)^2),
$$
and thus
\begin{align}
\lambda_{1,2}&=\frac{|a|^2+|b|^2\pm\sqrt{(|a|^2+|b|^2)^2-4(|a|^2|b|^2-(a^tb)^2)}}{2} \\
&=\frac{|a|^2+|b|^2\pm\sqrt{(|a|^2-|b|^2)^2+4(a^tb)^2}}{2}.
\end{align}

A: Some small notes, since Yiorgos' has done a fairly thorough job:
The key insight here is that $M$ can be written very nicely as the sum of rank-1 matrices.
That is: if we take $a,b$ as vectors in $\mathbb{R}^n$, $ab^T$ gives us the matrix whose entries are $M'_{ij} = a_i b_j$, and $b a^T$ gives us the matrix whose entries are $M''_{ij} = a_j b_i$.  Noting that $M_j = M'_j + M''_j$, it follows that $M = ab^T + ba^T$, and Yiorgos' analysis follows.
Note also that for vectors $u,v \in \mathbb{R}^n$, we can express the dot-product as
$$
u \cdot v = v^T u = u^T v
$$
Hence, the set
$$
\{x:a^Tx=b^Tx=0\}.
$$
is the set of all $x \in \mathbb{R}^n$ that are orthogonal to both $a$ and $b$.

So, suppose that $a,b$ are linearly independent.  We note that we may select $n-2$ eigenvectors corresponding to $\lambda = 0$ by selecting an orthogonal basis for the subspace
$$
\{x:a^Tx = b^Tx = 0\} = [\operatorname{span}(a,b)]^T
$$
The remaining 2 eigenvalues and eigenvectors, we note that because $M$ is symmetric, we may select a set of mutually orthogonal eigenvectors, so that two mutually orthogonal eigenvectors can necessarily be selected from the set
$$
\operatorname{span}(a,b) = \{c_1 a + c_2 b : c_1,c_2 \in \mathbb{R} \}
$$
So, consider any $x$ that can be written as $x = c_1a + c_2 b$, and suppose that $x$ is an eigenvector for some $\lambda$.  We have
$$
a b^T (c_1 a + c_2 b) + b a^T(c_1 a + c_2 b) = \lambda(c_1 a + c_2 b)
$$
We may rearrange the equation to get
$$
[(b^T a - \lambda) c_1 + b^T b c_2] a + [a^T a c_1 + (a^T b - \lambda) c_2] b = 0
$$
Since $a$ and $b$ are linearly independent, this gives us a system of equations for $c_1$ and $c_2$:
$$
(b^T a - \lambda) c_1 + (b^T b) c_2 = 0\\
(a^T a) c_1 + (a^T b - \lambda) c_2 = 0
$$
Or in other words, the set of $(c_1,c_2)$ corresponding to eigenvectors of the original matrix are precisely the eigenvectors of the new matrix
$$
\pmatrix{b^T a & b^Tb\\ a^T a & a^T b}
$$


text:
Q: AutoCompleteTextView Events to continuously create new adapter I am working on autocompleteTextView feature in android. I am trying to give option while the user types, the options are actually coming from a web API (json format).My doubt is:
say, user starts typing,when user types 3 characters, i need to ping the webAPI , get all the options it sends me. i create the ArrayList Adapter. Now i want to continue filtering the options depending on the user input.I want to continously send the input to webAPI and get JSON data, create another adapter and refresh autocomplete option for user.
I am not getting the event i need to capture to do this successfully?
Thanks in Advance.

A:
create ArrayListAdapter

You should not create new adapter over and over again but update the dataset it servers and notify the adapter about the change by calling notifyDataSetChanged()


text:
Q: How can i attach userdata to each item in a listview? C++ Win32 I was thinking i could use the LVITEM structures LPARAM to attach a pointer to my class, but i can't seem to get it to work!
Heres the main parts of my code:
Creating the listview:
hlvQuiz = CreateChild(WC_LISTVIEW, "",
    WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | LVS_ICON | LVS_AUTOARRANGE,
    0, 0, 320, 240, m_hwnd, FontNormal);

Adding items:
if (vQuizes.size() > 0)
{
    LVITEM lvi;
    lvi.mask = LVIF_TEXT | LVIF_PARAM;
    lvi.iItem = 0;
    lvi.iSubItem = 0;
    lvi.cchTextMax = QUIZSTRLEN;

    for (unsigned int i = 0; i < vQuizes.size(); i++)
    {
        lvi.lParam = (LPARAM)&vQuizes[i]; // adding pointer to lparam
        lvi.pszText = vQuizes[i].szName;
        ListView_InsertItem(hlvQuiz, &lvi);
    }
}

Then later when i go to get my class back from the LPARAM:
        LVITEM lvi;
    lvi.iItem = ListView_GetNextItem(hwnd, -1, LVNI_SELECTED);
    lvi.iSubItem = 0;

    if (ListView_GetItem(fm->hlvQuiz, &lvi) == TRUE)
    {
        Quiz* q = (Quiz*)lvi.lParam;
        if (q != NULL) // i get stopped here because my pointer is NULL
            if (Exists(q->szPath) == IS_FILE)
                ShellExecute(NULL, "edit", q->szPath, NULL, NULL, SW_SHOWNORMAL);
    }

Is there anything that i'm doing wrong? the listview creates fine, and the items add, but the pointer to my class which i put in the LPARAM value seems to be ignored, or changed by the time i come to dereference it

A: I haven't worked at this low level before, but I suspect you need to set the mask member of the LVITEM structure to LVIF_PARAM (as well as the appropriate values for anything else you need) for the call to ListView_GetItem.

A: Your code works fine in Debug mode but not in Release mode because
you missed to specify the name of LPARAM in lvi.mask (and the name of any other field you want back).
Try this:
lvi.iItem = ListView_GetNextItem(hlvQuiz, -1, LVNI_SELECTED);
lvi.mask = LVIF_PARAM;

if (ListView_GetItem(fm->hlvQuiz, &lvi) == TRUE) ...

You'll receive a copy of the LPARAM's value you've setted. I think that this little strange behaviour is due to the Debug mode's help that initalize everything for you. The Release mode instead do not.


text:
Q: How to adjust the threshold of typical sk-learn data mining methods to balance to precision and recall? Basically, I am using some data mining algorithms from python sk-learn library to do a classification.
However, I got some very un-balanced results, say, around 0.99 recall rate and less than 0.1 precision rate.
Conceptually classification algorithms rely on some "threshold" to make the decision, which means I should be able to balance the precision and recall rate simply through adjusting this "threshold".
However, I cannot find some APIs in sklearn to help on this, so my question is: How can I manipulate the underlying "threshold" inside sklearn library to balance the precision and recall rate?

A: Ok, if your problem is not about unbalanced data I must refer you to some notes I learnt in Andrew Ng's Machine learning course: http://www.holehouse.org/mlclass/06_Logistic_Regression.html
I chose Logistic Regression here because I don't really know the methods you are using. But the conclusion basically is that a threshold is not an explicit parameter of your learner model. I mean, you can chose afterwards where are you going to cut the classification (in probabilistic models) or you can establish some weighting parameters in some other methods (check this answer: scikit .predict() default threshold).
This thresholds only account for the proportion of false positives/false negatives (precision/recall) and shouldn't be strictly considered as parameters of the learning algorithm.
Side note: in a specific classification problem I found 'empirically' that I needed at least a probability of 0.6 to be right so I used the classifier's method predict_proba instead of predict so it was me who finally decided the returned class. Don't know if that helps.


text:
Q: Checking equality of two Strings in java How to check equality of two String objects independent of the char order?
Examples:
checkEq(A*B'*C,B'*A*C) has to return true
checkEq(A*B'*C,A*B*C) ----> false... etc

A: Sort the string by character and compare:
    char[] a1 = s1.toCharArray();
    Arrays.sort(a1);
    char[] a2 = s2.toCharArray();
    Arrays.sort(a2);
    return Arrays.equals(a1,a2);

A: Try using the java str.split method.  For instance, str.split("*") will give you an array of the elements A,B,C or B,A,C.  And then just sort them and single loop through them once to compare them.
String str1 = "A*B*C";
String str2 = "C*A*B";

// split strings into arrays
String[] array1 = str1.split("*");
String[] array2 = str2.split("*");

// sort each array
Arrays.sort(array1);
Arrays.sort(array2);

// compare arrays
for( i=0; i<array1.length; i++ ){
   if(array1[i] == array2[i]){
       return false;   // OR, do whatever it is you want to do here.
   }
}

A: You could put the individual characters into a Set<Character> or a Map<Character, Integer> (use the latter if you care about multiples of the same character).  Then calculating the set differences both ways will tell you if there are characters in one string that don't appear in the other (thus they are not equal).  For the map, calculate set difference (like above) on the key set, then if equal, the difference of each corresponding value -- if all are 0, the two strings are equal in the question's sense of equality.


text:
Q: Manage azure cloud via PowerShell - access problem In my Azure environment I have MFA configured (MFA enabled using Security Default in Azure AD). I want to connect to Azure using Azure Powershell. I am using cmdlet
Connect-AzAccount -Subscription "SubscriptionID"

I have a Global Administrator role in Azure AD, and Owner role on the subscription level. Before MFA I was able to Connect-AzAccount without any problems. Now when I am trying to Connect-AzAccount I am getting information:
WARNING: To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code XXCCAADDFF to authenticate.

I do recommended steps, using provided link providing code. After around 20 seconds I am getting an error message in the PowerShell console
Connect-AzAccount: The provided account xx.yy@company.com does not have access to subscription ID "SubscriptionID". Please try logging in with different credentials or a different subscription ID.

A: The code XXCCAADDFF mentioned in warning message refers to device code, it may be caused by you enable device login.
You mentioned getting error message The provided account xx.yy@company.com does not have access to subscription ID...., you can use
Connect-AzAccount -TenantId <tenantId> -Subscription <subscriptionId>

instead of
Connect-AzAccount -Subscription <subscriptionId>

For this problem, here is a post related to it. I also test it in my side, just add -TenantId, it will solve the error message.


text:
Q: Efeito hover em JS Estou com um problema que é o seguinte: quero que quando o usuário passe o mouse em determinada imagem um outro local ganhe uma classe para que eu possa a estilizar, poderiam me ajudar?
Estou tentando dessa forma:
var $JQuery2 = jQuery.noConflict()
$JQuery2(function() {
    $JQuery2(".bt_pagamento-facilitado").hover(function(){
                $JQuery2(".bt_criacoes-exclusivas").addClass("redesAl");
    });
});

A: O evento .hover deve ter 2 funções: uma para quando o mouse estiver sobre o elemento e outra para quando sair.

var $JQuery2 = jQuery.noConflict()
$JQuery2(function() {
   $JQuery2(".bt_pagamento-facilitado").hover(
      // função que adiciona a classe
      function(){
         $JQuery2(".bt_criacoes-exclusivas").addClass("redesAl");
      },
      // função que remove a classe
      function(){
         $JQuery2(".bt_criacoes-exclusivas").removeClass("redesAl");
      });
});
.redesAl {
  background: red;
  color: #fff;
  display: inline-block;
}

Passe o mouse sobre a imagem:

Texto texto

Documentação oficial do .hover.

A: Uma opção diferente para o problema é fazer esse efeito direto com CSS usando alguns seletores, que podem ser:
.classe ~ .outraClasse {} #se outraClasse é irmao de classe
.classe + .outraClasse {} #se outraClasse é o proximo elemento
.classe > .outraClasse {} #se outraClasse está direto dentro de classe
.classe ~ .outraClasse {} #se outraClasse está em algum lugar dentro de classe

Exemplo

#imagem {
  background-color: red;
}

#imagem:hover + #alterar {
  background-color: blue;
}

Conteudo da div

A: Veja seu código funcionando...

var $JQuery2 = jQuery.noConflict()
$JQuery2(function() {
    $JQuery2(".bt_pagamento-facilitado").hover(function(){
                $JQuery2(".bt_criacoes-exclusivas").addClass("redesAl");
    });
});
.bt_pagamento-facilitado {
  width: 100px;
  height: 100px;
  background: green;
}
.bt_criacoes-exclusivas {
  width: 100px;
  height: 100px;
  background: yellow;
}
.redesAl {
  background: blue;
}

Talvez você não definiu direito as classes no HTML ou no CSS...


text:
Q: Visual Studio 2012 Breakpoints do not hit I have made a simple visual webpart for SharePoint 2013 in visual studio 2012. The .apsx page only has one label.Then i say deploy and attach to process w3wp and refresh the webpage where i have added the visual webpart.In the code i have put breakpoints at the start on oninit() and pageload() methods. But when i refresh the page i find the label but the code behind does not run and the breakpoints are not hit.
When i hover the break points i get following message.

A: Some ideas.

*

*Make sure it's a debug build and not release

*Turn off optimizations in your project properties if they are on

*Try inserting Debugger.Break() in your code instead of a breakpoint
in VS

*Make sure breakpoints are enabled (Debug->Windows->Breakpoints toolbar), and breakpoint symbol should be solid

*Execute your application. Load Debug->Window->Modules window. Check your assembly to see if symbols are loaded. It may give a relevant status message if not.

Source


text:
Q: Why ng-include causing $digest iterations reached? Receiving data by
$scope.$watch("build.idx", ->
  $http.get("/build/" + $scope.build.idx + ".json").success((data) ->
    $scope.build = data
  )
)

ng-include inside ng-repeat
.build-stage
  .row{ "ng-repeat" => "stage in build.stages" }
    %div{ "ng-include" => "donoting.html" } # donoting.html is blank

first loading page, it's OK. and when changing build.idx, it cause
10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: function (){var a=d.url(),b=h.$$replace;p&&a==h.absUrl()||(p++,c.$evalAsync(function(){c.$broadcast(\"$locationChangeStart\",h.absUrl(),a).defaultPrevented?h.$$parse(a):(d.url(h.absUrl(),b),g(a))}));h.$$replace=!1;return p}; newVal: 8; oldVal: 7"],["fn: function (){var a=d.url(),b=h.$$replace;p&&a==h.absUrl()||(p++,c.$evalAsync(function(){c.$broadcast(\"$locationChangeStart\",h.absUrl(),a).defaultPrevented?h.$$parse(a):(d.url(h.absUrl(),b),g(a))}));h.$$replace=!1;return p}; newVal: 9; oldVal: 8"],["fn: function (){var a=d.url(),b=h.$$replace;p&&a==h.absUrl()||(p++,c.$evalAsync(function(){c.$broadcast(\"$locationChangeStart\",h.absUrl(),a).defaultPrevented?h.$$parse(a):(d.url(h.absUrl(),b),g(a))}));h.$$replace=!1;return p}; newVal: 10; oldVal: 9"],["fn: function (){var a=d.url(),b=h.$$replace;p&&a==h.absUrl()||(p++,c.$evalAsync(function(){c.$broadcast(\"$locationChangeStart\",h.absUrl(),a).defaultPrevented?h.$$parse(a):(d.url(h.absUrl(),b),g(a))}));h.$$replace=!1;return p}; newVal: 11; oldVal: 10"],["fn: function (){var a=d.url(),b=h.$$replace;p&&a==h.absUrl()||(p++,c.$evalAsync(function(){c.$broadcast(\"$locationChangeStart\",h.absUrl(),a).defaultPrevented?h.$$parse(a):(d.url(h.absUrl(),b),g(a))}));h.$$replace=!1;return p}; newVal: 12; oldVal: 11"]]

and when removing ng-include line, it's OK.
I think it's ng-include causes $locationChangeStart fired, but why?

A: Be sure that the path of the template to include in ng-include is correct. If not it causes the 10 $digest() iterations reached error.
If the path is not correct the server will serve the index.html (at least in the case you use html5 mode the server defaults to serve index.html); the index.html will be included and will cause the ng-include directive to run again; the result is an an infinite loop of iteratively included index.html which is terminated with the error message 10 $digest() iterations reached

A: you got your self in a infinite loop right here
$scope.$watch("build.idx", ->
  $http.get("/build/" + $scope.build.idx + ".json").success((data) ->
    $scope.build = data
  )
)

you are watching for build.idx, and if that changes requesting information that will change build which will trigger the request again and again modify the build variable andf go on and on and this will quicly reflect in the digest cycle by constantly changing and angular will throw this exception, because it detected a possible infinite loop


text:
Q: Change element type on change detected in React So I have a list of checkboxes with associated labels and the labels are tooltips and therefore defined as anchor tags. See images:

The way my checkbox list works is that when a checkbox is checked, it toggles an input to be shown to the right as shown above. However, on the last item in these checkbox is one called "Other". For this, is a change event is detected, I want to simply change the "Other" text to a <input ="text" /> and modifying my existing working functions for all of this has me crossed and was hoping on input on how I can do this within the same handleChange10 event as indicated in code below (my code snippets below to show all for this view, but just for the pieces in need of help on)?:
handleChange9() {
    this.setState({
      checked9: !this.state.checked9
    })
}

handleChange10() {
    this.setState({
      checked10: !this.state.checked10
    })
}

toggle9() {
    this.setState({
      tooltipOpen9: !this.state.tooltipOpen9
    });
}

const numberNeeded9 = this.state.checked9
  ? <Input type="text" className="flrt" id="addlInfo9" placeholder="how many" onChange={this.inputNumOfEx}></Input>
  : null;

const numberNeeded10 = this.state.checked10
  ? <Input type="text" className="flrt" id="addlInfo10" placeholder="how many" onChange={this.inputNumOfOth}></Input>
  : null;

<FormGroup check>
  {numberNeeded8}

    <Input type="checkbox" checked={this.state.checked8} onChange={this.handleChange8} />
    Scientists
    <Tooltip placement="right" isOpen={this.state.tooltipOpen8} target="custType8" toggle={this.toggle8}>
      Data, Research
   </Tooltip>

</FormGroup>

<FormGroup check>
  {numberNeeded10}

    <Input type="checkbox" checked={this.state.checked10} onChange={this.handleChange10} />
    Other

</FormGroup>

A: <FormGroup check>
  {numberNeeded10}

    <Input type="checkbox" checked={this.state.checked10} onChange={this.handleChange10} />
    {
      this.state.checked10?
        <input type="text" /> :
        Other
    }

</FormGroup>

But I don't think You should do it this way. You can keep in the state id of selected checkbox, and You will no need handleChange1,2,3,4,5,6,7().


text:
Q: With the "user_status" Facebook permission, can I make an app to show the user their personality? I have an app that analyzes text comments and figures out the personality out of it. I'd like to integrate Facebook in it, but when checking the user_status permission, I read:

*

*(OK) Provide creative content from status updates.

*(OK) Provide value to the user by visibly analyzing the content of their past statuses.

*(Not OK) Non-visible use of this data such as sentiment analysis or
guarding against spam bots.

The app will show the user their personality. It analyzes the content of their past statuses and provide value to the person, they know something more about their personality and, depending on which category they fall, they will see a picture and a brief description of it.
I'm not sure about the last point, does my work count as doing "sentiment analysis"? The use of this data is completely shown to the user.
I was wondering this because I couldn't find any app that do this after the recent changes of last April in Facebook.
Since to request the permission Facebook wants to see everything in action, knowing this is not permitted at all in advance will save me some coding.
Thank you!

A: Not sure how to properly answer my own question, with the answer coming from another website, but I got a very kind feedback from David Doyle on the "Facebook Developer Community" group on Facebook.

We see a lot of apps that do or claim to do similar to what you're looking for. Permissions can be approved in these cases if the content is clearly influenced by the information a permission provides, is clearly visible to people using the app and results vary based on the information provided.
Where some apps might fall down with requests like this is claiming "the answer is custom based on your user_status" but in reality, the answers are always the same - or there's a core set of answers that are rotated and the information provided from login are never used in the app.
Hope this makes things a bit clearer!

Then he added

What I mean by clear visibility is that if I'm a person signing into your app I should know why you're asking me for user_status.
When I get my result, I should know how my status information contributed to it.

Permalink to the discussion, if you're in the Facebook group: link


text:
Q: How can I add response.sendRedirect to my controller I've written my controller to forward all requests and this works fine for nearly all actions that I want to take, but I may need to use response.sendRedirect for a successful login rather than forwarding it to try and implement Tomcat's CSRF prevention filter.
I've tried adding in what I believe is the correct code, but I keep getting errors can anyone tell me if this is possible and if what would be the best action to take.
My controller's login method as it currently stands is (without error code)
public void doPost(HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ServletException {
    String requestURI = request.getRequestURI();
    String url = "";
    // Register a new user
    if (requestURI.endsWith("/subscribeToSite")) {
        url = subscribeToSite(request, response);
    }
    // Login
    if(requestURI.endsWith("/logintosite")){
        url = logintosite(request, response);
    }
   //Change AC password
    if(requestURI.endsWith("/changePwd")){
        url = changePassword(request, response);
    }

    getServletContext()
            .getRequestDispatcher(url)
            .forward(request, response);
}

private String logintosite(HttpServletRequest request,
        HttpServletResponse response) {

    String url;
    String message;
    // get values from form
    String pNum = request.getParameter("phoneNumber");
    String upwd = request.getParameter("password");

    //validate the values to check for empty values in case JS registration check has failed.
    if(pNum.length()==0 ||upwd.length()==0){
        message="You have not filled out the required fields.";
        request.setAttribute("message", message);
        url = "/login.jsp";
        return url;
    }
    //Format the phone number
    String mPNum=UserDB.formatPhoneNumber(pNum);
    //try to  login
    User user = UserDB.loginUser(mPNum, upwd);
    if(user==null){
        url = "/loginerror.jsp";
    }else{
           //HttpSession session = request.getSession();
            HttpSession session = request.getSession();
            session.invalidate();
            session=request.getSession(true);
            session.setAttribute("loggedUsrID", user.getUserID());
            session.setAttribute("loggedUsrFName", user.getFName());
           url="/sched/welcome.jsp";

    }
    return url;
}//EO user login
}

What I need to do is use response.sendRedirect(/sched/welcome.jsp) rather than send the URL just for this method as the other methods in the controller work fine just using forward.


text:
Q: Invoke object method regardless of parameter type I am using a DynamicObject to wrap an internal object and mask generics, however when I try to invoke certain methods on the internal object they require typed paramaters, however I am treating all paramaters as the type Object so the invoke fails.
Code:
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            try
            {
                result = mInternalObject.GetType().InvokeMember(binder.Name, (BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public), null, mInternalObject, args);
                return true;
            }
            catch (Exception)
            {
                return base.TryInvokeMember(binder, args, out result);
            }
        }

So basically, I am wondering how to make it ignore the paramater types and invoke the method with the object anyway, any sugestions?

A: I suspect you want something along the lines of (psuedo code, very simplified):
var mem = internalObject.GetType().GetMember(binder.Name);
if (mem.IsGenericDefinition)
  mem = mem.MakeGeneric(Array.Convert(args, x => x.GetType()));
var result = mem.Invoke(null, internalObject, args);

A: Instead of reflection, since you are using dynamic, you can use really late binding from the open source ImpromptuInterface project. It's faster than reflection and will work on more kinds of objects (such as other dynamic objects) and can infer generics while alternatively letting you specify as well, making everything much simpler.


text:
Q: Invisible element and Col-X elements with Bootstrap 4 I want to make invisible a checkbox input with bootstrap 4 between some cols elements.

      1 of 2

    <input type="checkbox" class="invisible" >
    <input type="text" class="col-10" value="2 of 2">

I used the invisible class and it is not visible, but it has a size of 13px.

How can I use cols elements to fill the row with an hidden element in the middle?
This is an example of what I have:
https://jsfiddle.net/j6h93rve/1/
And this is what I want:
https://jsfiddle.net/fybmkp7e/

A: Probably you have to use d-none instead of invisible class

*

*d-none - display: none

*invisible - visibility: hidden
fiddle

A: Instead of invisible you can use d-none class, will work.


text:
Q: Cross covariance and trace identity This may be a simple answer but I can't find any proof. I know that the following identities are true
$$ E\left \{  \left ( \mathbf{x} - E\left ( \mathbf{x} \right )  \right )^T\mathbf{Q}\left ( \mathbf{x} - E\left ( \mathbf{x}  \right ) \right ) \right \}=tr\left ( \mathbf{Q}cov\left ( \mathbf{x} \right ) \right )$$
$$ E\left \{ \left ( \mathbf{A}\left ( \mathbf{x} - E\left ( \mathbf{x} \right ) \right ) \right )^T\mathbf{Q}\left ( \mathbf{A}\left ( \mathbf{x} - E\left ( \mathbf{x} \right ) \right ) \right ) \right \}=tr\left ( \mathbf{Q}\mathbf{A}cov\left ( \mathbf{x} \right )\mathbf{A}^T \right )=tr\left ( \mathbf{A}^T\mathbf{Q}\mathbf{A}cov\left ( \mathbf{x} \right ) \right ) $$
where $\mathbf{Q}$ is a diagonal matrix, $\mathbf{x}$ is a random column vector, $\mathbf{A}$ is a matrix of appropriate dimensions and $cov$ is the covariance. For the case of two random vectors, are these identities true?
$$ E\left \{  \left ( \mathbf{x} - E\left ( \mathbf{x} \right )  \right )^T\mathbf{Q}\left ( \mathbf{y} - E\left ( \mathbf{y}  \right ) \right ) \right \}=tr\left ( \mathbf{Q}cov\left ( \mathbf{x,y} \right ) \right )$$
$$ E\left \{ \left ( \mathbf{A}\left ( \mathbf{x} - E\left ( \mathbf{x} \right ) \right ) \right )^T\mathbf{Q}\left ( \mathbf{B}\left ( \mathbf{y} - E\left ( \mathbf{y} \right ) \right ) \right ) \right \}=tr\left ( \mathbf{Q}\mathbf{A}cov\left ( \mathbf{x,y} \right )\mathbf{B}^T \right )=tr\left ( \mathbf{A}^T\mathbf{Q}\mathbf{B}cov\left ( \mathbf{x,y} \right ) \right ) $$
Thanks

A: The answer to both is yes.
For the first one, let $\mathbf{c}=\mathbf{x}-E\left ( \mathbf{x} \right)$, $\mathbf{d}=\mathbf{y}-E\left ( \mathbf{y} \right)$ and $Q=\text{diag}(q_1,\ldots,q_n)$, then you can easily check
$$ E\left[ \mathbf{c}^TQ\mathbf{d}\right]=E\left[\sum_i q_i\mathbf{c}_i \mathbf{d}_i\right]=\sum_i q_iE\left[\mathbf{c}_i \mathbf{d}_i\right].$$
Since $\left(cov(\mathbf{x},\mathbf{y})\right)_{ij}=\left(E\left[\mathbf{c}\mathbf{d}^T\right]\right)_{ij}=E\left[\mathbf{c}_i\mathbf{d}_j\right]$, the $i$-th diagonal element of $Qcov\left ( \mathbf{x},\mathbf{y} \right )$ is $q_iE\left[\mathbf{c}_i\mathbf{d}_i\right]$ and thus the first equality follows.
For the second equality, an important fact to keep in mind is that $E\left[A\mathbf{x}\right]=AE\left[\mathbf{x}\right]$. So $A\mathbf{c}=A\left( \mathbf{x} - E\left ( \mathbf{x} \right )\right )=\left ( A\mathbf{x} - E\left ( A\mathbf{x} \right )\right )$ and we can apply the first equation to obtain
$$  E\left [  \left( A\left ( \mathbf{x} - E\left ( \mathbf{x} \right )  \right )\right )^T\mathbf{Q}\left( B\left ( \mathbf{y} - E\left ( \mathbf{y} \right )  \right )\right ) \right ]=tr\left ( \mathbf{Q}cov\left ( \mathbf{Ax},\mathbf{By} \right ) \right ). $$
To complete the proof, note that
$$ cov(A\mathbf{x},B\mathbf{y})= E\left[ A\mathbf{c}\left(B\mathbf{d}\right)^T\right]=E\left[ A\mathbf{c}\mathbf{d}^TB^T\right]=A E\left[ \mathbf{c}\mathbf{d}^T\right]B^T=A cov(\mathbf{x},\mathbf{y})B^T  $$


text:
Q: How do I get and set a Svelte store value from a web page where I injected a Svelte app? I built a Svelte app which includes a stores.js file containing a writable store value called sSchool. I inject the app in my html page this way.

I'd like to be able to get and set the store value sSchool from JavaScript snippets inside this webpage. How can I achieve this? Thanks.

A: The 1st thing you need to figure out is how to get the reference of your sSchool store.

1 suggestion would be to expose it the same way you expose the app class, which i believe you are doing something like this somewhere?
import App from './App.svelte';
window.app = App;

maybe you could have
import sStore from './store.js';
window.sStore = sStore;

with that, you could get the value of the store by subscribing to it
sStore.subscribe(value => {
  console.log('store value:', value);
});

and setting the value of the store
sStore.set(newValue);

Another approach would be to define component methods in your app component:

then in your script,

References

*

*Watch my video "How to call functions inside a component" https://youtu.be/EA0EX3tbNNM, which explained how to call functions inside a component


text:
Q: Dynamic query based on specified columns I have a big table with ~20 fields. Can I return a List elements based on a query with let's say id, created_on, temperature without creating constructors in class T for every possible combination of fields?
Let's say something like this:
Query q = em.createQuery("SELECT id, created_on, temperature FROM Table");
result = (List<T>) q.setMaxResults(300).getResultList();

Does it work if I don't have a constructor for this specific case? Do I get a list of T objects?

A: It would be cleaner to use projections, but if you intend to have many different combinations of your 20 columns, selecting them separately gives you a return type of Object[], with column values in their respective indices.
So no, you don't get a List<T>, you get a List<Object[]>.


text:
Q: Unix tail script with grep Can you help me with a shell script, which tail on live every new file in folder and reads lines in the file that coming and grep specific lines and write it to the file. For example:
Find latest file in folder
then unix read it like cat command that newest file, then grep it out specific lines like grep -A3 "some word" and those lines will be saved in file like >>someother file.

A: To detect file-system changes, you might want to have a look at inotify.


text:
Q: ¿Cómo sé el languaje, y el software de la petición ( navegador ) en Express? Cuando hacen una petición a mi servidor creador en Express, y intento saber el languaje, y el software de el navegador, con req.language y req.software me da undefined
mi código actual es:
app.get('/api/whoami',  (req, res, next)=> {

    let json = {"ipaddress": req.ip, "language": req.language, "software":  req.software}

    res.json(json)

    next()
})

para ver a más a detalle el código completo visite https://replit.com/@Michael-Liendo/boilerplate-project-headerparser

A: Usando  req.get('') para obtener la información requerida.
para obtener el languaje: req.get('Accept-Language')
y el el software (User Agent): req.get('User-Agent')


text:
Q: PHP post variable showning in DOM but not on page? i have two files first is a.php and second is b.php (popup)
in a.php i am posting data via ajax
    $.post("b.php",{cat:"hello"},function(result){
        console.log(result);
    });

and in b.php i am using
$cat = $_POST['cat'];
echo $cat;

In DOM of a.php, "hello" is showing, but in b.php it is blank. why???
In a.php i am using
$('div#showrqmt').on('click',function(){

    $.post("b.php",{cat:"hello"},function(result){
        console.log(result);
    });
});

Show Requirments
 (this will popup     b.php)

In response text of ajax the post data ("hello") is showing but not in php
in b.php i have used
$cat = $_REQUEST['cat']; // not working
$cat = $POST['cat']; //not working
echo $cat // for both case not working...

A: If you mean you are visiting b.php in your browser then it will be blank because you are making a GET request not a POST request.
You could change $cat = $_REQUEST['cat']; which will then echo the cat if you provide it in the URL e.g. b.php?cat=hello but if you want to keep it as a POST request then you won't be able to do this from your browser alone.
See HTTP Methods: GET vs. POST

A: Try to add dataType - text. See http://api.jquery.com/jquery.post/


text:
Q: Array to string conversion with nusoap client I sent request to webservice like this :
 $transaction = new Transaction();
    $transaction->amount = $amount;
    $transaction->order_id = $orderId;
    $transaction->status = 0;
    $transaction->additional_data = $additionalData;
    $transaction->type = 1;
    $transaction->ip = Request::getClientIp();
    $transaction->save();
    $soap = new nusoap_client(self::$request_url);
    $fields = array(
        'terminalId' => self::$terminalId,
        'userName' => self::$username,
        'userPassword' => self::$password,
        'orderId' => $transaction->order_id,
        'amount' => $amount,
        'localDate' => date('Ymd'),
        'localTime' => date('His'),
        'additionalData' => $additionalData,
        'callBackUrl' => self::$callBackUrl,
        'payerId' => 0,
    );
    $response = $soap->call('bpPayRequest', $fields, 'http://interfaces.core.sw.bps.com/');

but i get exception in line 2125 in nusoap.php :

Array to string conversion

exception thrown from :
    // TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE
    foreach(curl_getinfo($this->ch) as $k => $v){
        $err .= "$k: $v<br>";
    }
    $this->debug($err);


text:
Q: How to join counts dependent on outer groups I have a table that looks like so:
id | mid | oid
 1 | 400 | 1
 2 | 400 | NULL
 3 | 401 | 1
 4 | 403 | NULL

I am trying to return the MID, number of records with null OID's and number of records with NOT null oid's
Currently I am using this:
SELECT
(SELECT COUNT(id) FROM drp_ledger WHERE oid IS NULL) AS que,
(SELECT COUNT(id) FROM drp_ledger WHERE oid IS NOT NULL) AS finished,
`mid` FROM drp_ledger GROUP BY `mid`

However this returns the ENTIRE count of NULL and NOT NULL oid's.
So I then attempted to use a JOIN I feel like I am close but I just cant get it to work.
SELECT l.`mid`, que, finished FROM drp_ledger AS l
JOIN (SELECT COUNT(id) AS que FROM drp_ledger WHERE oid IS NULL GROUP BY `mid`) AS q ON q.`mid` =  l.`mid`
JOIN (SELECT COUNT(id) AS finished FROM drp_ledger WHERE oid IS NOT NULL GROUP BY `mid`) AS f ON f.`mid` = l.`mid`

I would like to return:
mid | que | finished
400 |  1  |   1
401 |  0  |   1
403 |  1  |   0

A: No need for a join!
SELECT
  mid,
  SUM(IF(oid IS NULL,1,0)) AS oid_null,
  SUM(IF(oid IS NOT NULL,1,0)) AS oid_not_null
FROM tablename
GROUP BY mid

A: You're close, but you forgot to select the mid in your subqueries.


text:
Q: MPMoviePlayerController not showing controls until video is loaded I've an application based on iOS4, with a:
MPMoviePlayerController

and this settings:
moviePlayerController.movieSourceType = MPMovieSourceTypeStreaming;
moviePlayerController.controlStyle = MPMovieControlStyleDefault;

Everything is working good, except that, when I present the MPMoviePlayerController view, it doesn't display controls until the video is pre-loaded.
I know in previous version of iOS (3.x), controls are displayed as soon as MPMoviePlayer is presented. Any chance to have this working in ioS4?

A: You have to use MPMoviePlayerViewController instead of MPMoviePlayerController.

A: I'm working on a video player for iPad and I'm experiencing the same behavior. However, I don't think it's much of a problem since you can't control the video until it's loaded anyway.
What you can do is fake the existence of those controls, by setting the background view.
Here's what I do:
moviePlayerController.backgroundView.backgroundColor = [UIColor blackColor];

That just makes the background view black, but you could imagine adding a UIImageView as background view that shows disabled controls, or build real controls that actually do something.


text:
Q: Finding the 'optimal distribution' with one unknown variable I am trying to find the optimal distribution (of ingredients) with one unknown parameter (skillset).
Example, when baking a bread the ingredients are flour,salt,yeast and water. When I ask 100 bakers to bake a bread lets asume I get 100 different distributions for the ingredients (for example baker 1 used: 25% flour, 25% salt 25% yeast and 25% water). After rating the queality of the bread and inspecting the distribution of the ingredients I will get a pretty good idea of the average distribution used. However the skillset of the baker is probably more important then the exact distribution. And the skillset is unknown to me.
There are pretty hight correlations between the ingredients. Flour (.6) salt (-.2) etc and the rating of the bread. This leads me te believe that adding more flour and less salt is the 'secret' to baking the perfect bread even though a skilled baker probably made a 'better rated' bread with a less optimal distribution of ingredients.
My question: are there known solutions for finding the best distribution and if so, what are they called?


text:
Q: Rethinkdb Use existing value if branch evaluates to false Using branch update logic in rethinkdb. I am needing to update a value based on wether another value matches and then set the appropriate value. If the values are the same it should use the existing value.
r.db('testdb').table('great_table').get(1).update(source => {
  return r.branch(source('some_other_id').eq(1), {read: false}, /* use existing value */);
})

Tried the following:
r.db('testdb').table('great_table').get(1).update(source => {
  return r.branch(source('some_other_id').eq(1), {read: false}, source('checked'));
})

The error I received when I tried this is:
{
  "deleted": 0 ,
  "errors": 1 ,
  "first_error":  "Inserted value must be an OBJECT (got BOOL): false" ,
  "inserted": 0 ,
  "replaced": 0 ,
  "skipped": 0 ,
  "unchanged": 0
}

A: In your query you are trying to pass bool where Rethink expecting object.
So, your query should look like this (depends in which field you want save source('checked') value):
r.db('testdb').table('great_table').get(1).update(source => {
  return r.branch(source('some_other_id').eq(1), {read: false}, {read: source('checked')});
})


text:
Q: Parsing -D command line arguments java What is the best way to parse this command line arguments in java?
$ ant run -Dfilename=(filename_value) -Dmemory_size=(memory_size) -Dk=(k_value)

I am not actually using ant but my project will be evaluated on this command line.
Therefore, I am trying to test this on netbeans by adding this example arguments in run configurations.
-Dfilename="C:\\Users\\y_guz_000\\Dropbox\\active projects\\ExternalSort2\\resources\\input.xml" -Dmemory_size="3"
-Dk="2"

I am outputting the result with:
System.out.println(System.getProperty("filename"));
System.out.println(System.getProperty("memory_size"));
System.out.println(System.getProperty("k"));

However the result is
null
null
null

A: You are not passing the system variables to your java program, you are passing them to ant, so this is as expected.  Googling "ant run set system properties" this looks to be the information you need:  http://ideoplex.com/id/372/setting-java-system-properties-with-ant

A: assuming that you have a standard Netbeans Java SE or Maven Java app project:
In Netbeans "Projects" tree on the left, right click on your project icon. Select "Run" list item for the "Categories" list, and you have textfields there to input your program and VM arguments (-D here).


text:
Q: axios does not work with while fetch does i want to get data (array) from /{url} and i tried this code
// Fetch the list on first mount
componentDidMount() {
this.getList();
}

// Retrieves the list of items from the Express app
getList = () => {

fetch('/main')
.then(res => res.json())
.then(list => this.setState({ list }))
}

this is working fine but then i decided to switch to axios and tried literally same code
  // Fetch the list on first mount
componentDidMount() {
this.getList();
}

 // Retrieves the list of items from the Express app
 getList = () => {
 axios.get('/main')
.then(res=> res.json())
.then(list => this.setState({list}))

}

but it did not worked and gave me error in this line:  .then(res=> res.json())
so i do not know what is problem if anyone knows the clue i will be glad if you tell me

A: It is because axios has different response, instead of res.json() return data already like : return res.data or pass it to state directly something like
getList = () => {
 axios.get('/main')
   .then(res=> this.setState({list: res.data}))

A: // Fetch the list on first mount
componentDidMount() {
  this.getList();
}

// Retrieves the list of items from the Express app
getList = () => {
 axios.get('/main')
 .then(res=> res.data)
 .then(list => this.setState({list}))
 .catch(error => this.setState({error: error.message}))
}

A: i would recommend some changes in your design, as im using axios successfully in many projects, its not a requirement but it helps and is working very reliable:
Create a service like api.js

import axios from 'axios';

export default axios.create({
  baseURL: `http://my.api.url/`
});

Then you can use it like this

import API from '../Services/api'; // this is your service you created before

LoadStats = async event => {
    try {
        var response = await API.get('api/targetroute');
        if (response.data != null) {
            this.setState({
                stats: {
                    mydata: response.data
                }
            });
            console.log('Receiving result: '+JSON.stringify(response.data));
        }
    } catch (error) {
        console.log('ERROR: '+error)
    }
}


text:
Q: What am i missing from my interface or assemblies? I have this following interface IQueueClient implements AZureBus class;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Management.ServiceBus;

namespace MessageQueueApp
{
    public class AZBus:IQueueService
    {
        public string ConnectionString { get; set; }
        public string QueueName { get; set; }

        private static IQueueClient queueClient;
        public void Send(string payload)
        {
            queueClient = new QueueClient(ConnectionString, QueueName);
            var message = new Message(Encoding.UTF8.GetBytes(payload));
            queueClient.SendAsync(message).Wait();
        }

    }
}

I am getting an error on my new object name QueueClient() with argument types ConnectionString, QueueName. As well my SendAsync(message).Wait(); What am i missing from this code? Please help and show me guidance to this, thanks.

A: You are missing a using statement:
using Microsoft.Azure.ServiceBus;


text:
Q: What's wrong with this Jade data binding? What's wrong with this Jade? Thanks.
input#a
h1= document.getElementById('a').value

The error given is blank.

A: As Amberlamps suggests, you have to wait until the DOM is ready.
input#a
h1

//- presuming you are using jQuery
script
    $(function() {
        $('h1').html($('input#a').val());
    });