text:
Q: Sokhotski–Plemelj theorem let me repeat my question that I asked here https://physics.stackexchange.com/questions/319298/sokhotski-plemelj-theorem
The question is : " What is the value of $\int_{-\infty}^{\infty} \frac{1}{x + i0}$ ?"
On the one hand, Sokhotski formula says that $\frac{1}{x + i0} = \text{P} \frac 1 x - i \pi \delta(x)$. Therefore, $\int_{-\infty}^{\infty} \frac{1}{x + i0} = - i \pi$. On the other hand, we seemingly can compute this integral using the residue theorem. We can regularise it by adding $\lim_{\varepsilon \rightarrow 0} e^{- i \varepsilon x}$, so we can close the contour in the lower half plane and get $- 2 \pi i$
Integral regularization is certainly quite artificial trick. However, it is commonly and successfully used in quantum mechanics as well as Sokhotski formula. If I just put $\int_{-\infty}^{\infty} \frac{1}{x + i0}$ into Mathematica, I get $- 2 \pi i$. So, I can't see how to resolve this contradiction.

A: You need to calculate the large circular boundary.
$$\int_{boundary} \frac{dz}{z}= \lim_{r\rightarrow\infty}\int_{0}^{-\pi}\frac{r e^{i \theta} i d\theta}{re^{i\theta}}=-i\pi$$
The boundary contribution is $-i \pi$. The total circle is the residue which is $-2i \pi$. So use the contour the result is still the $-i\pi$.

A: I just came up with this question myself yesterday! Nice timing. Not sure if what I'm going to say here suffices as an answer but it doesn't fit in a comment so I'll put it here since I'm interested to hear more on this question as well.
It strikes me that you are taking two limits.
$$\lim_{a \rightarrow 0} \lim_{b \rightarrow 0} \int_C \frac{e^{-ibx}}{x+ia}dx$$ where $C=C_1+C_2$ is the contour of integration with $C_1$ along the real line and $C_2$ closing in the lower half plane.
The Sokhotski  formula tells us the value of the integral on $C_1$ is $-i\pi$ as we take the $a$ limit and presumably doesn't care much about the presence of $b$ (since $\text{Im}(x)$ is small there). so the question is whether the integral on $C_2$ is zero or non-zero. As you have pointed out, for the case that $b>0$ we can argue that the integral on $C_2$ is zero. However, when $b$ is actually equal to zero then none of the theorems for that integral vanishing apply and it is clear that the value of the integral on $C_2$ must be non-zero. In fact, the result of your analysis would say the value of the integral on $C_2$ must balance the difference between the Shokhotski result and the residue theorem result so it must be $-i\pi$.
In other words, it seems like the value of the integral on $C_2$ is not a continuous function of $b$, it does not equal its limit as $b\rightarrow 0$ so maybe this tells us that for this function, the type of regularization you have chosen should not be expected to give us a well-behaved answer.
Also I'm not sure how you put $\int_{-\infty}^{+\infty} \frac{1}{x+i0}dx$ into mathematica. In mathematica I was able to find
$$\int_{-x_0}^{+x_0} \frac{1}{x+i\epsilon} dx = log(x_0+i\epsilon) - log(-x_0+i\epsilon)$$
which equals $-i\pi$ in the limit that $x_0\rightarrow \infty$.
Like I said before, I'm not sure if this is a complete answer to the question but I would like to hear other's thoughts.


text:
Q: Bower, Mondernizr and Gulp I am trying to set up an new website environment in a Visual Studio 2015 project. Ive got everything working; NPM, Bower, Gulp. It is generating and minifying all my js and css, except Modernizr, which I seem to be stuck on.
I added modernizr to my bower.json file and VS created the bower_components folder. However there is no modernizr.js in the directory. I found another post on here suggesting doing a "bower cache clean" but that didn't seem to improve the situation at all.
Any ideas?

A: @ahmad-alfy is correct, in that there is no modernizr.js file that is included.
however you do not need to run npm install. You can npm / bower install any of the Modernizr URLs.
e.g. npm install --save https://modernizr.com/download?setclasses-emoji-ambientlight

A: Since Modernizr 3.0 there is no longer an already built file in the bower package. You have to build it yourself by running npm install inside bower_components\modernizr
Source: github issue

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display timezone name in locale Java I have this piece of code in Java
public static void main(String[] args) {
    TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
    System.out.println(tz.getDisplayName(new Locale("ja-JP")));
}

It displays the output "Pacific Standard Time". I would think, it should display this timezone in Japanese? Is this not how this library is supposed to behave?

A: Use Java's japanese Locale, not your own
System.out.println(tz.getDisplayName(Locale.forLanguageTag("ja-JP")));

or better yet
System.out.println(tz.getDisplayName(Locale.JAPAN));

See here for supported locales in Java 8.


text:
Q: Ubuntu / linux - Set permissions recursively through a folder where files/dirs have certain permissions My title probably sounds more cryptic than it needs to.
I'm using ubuntu 12.04 and want to be able to change permissions on files and folders recursively to 755 but only where the permissions are currently set to 777.
Does anybody know how to do this through the terminal?

A: Try doing this :
cd /the/dir
find . -perm 777 -exec chmod 755 {} +


text:
Q: create union function that returns type of set I am having trouble completing a function, currently does not let my program use cout when I am calling it in main. I am trying to find an alternative way to create a function definition for:
set<int> Union(const set<int> & s0, const set<int> & s1);

which creates and returns a set that is the union of two other sets (s0 and s1). What I have written (a function trying to use set_union method from #include ) and desired output is down below:
Desired output:
Given set s0 has {1,2,3,4} and set s1 has {4,5,6,7}, a new set must be created (s3 that has {1,2,3,4,5,6,7}).
All help is appreciated.
#include <iostream>
#include <string>
#include <set>
#include <cassert>
#include <algorithm>
using namespace std;
set<int> Union(const set<int> & s0, const set<int> & s1);
int main(){
set<int> s0{1,2,3,4};
set<int> s1{4,5,6,7};
cout << Union(s0,s1) << endl;
}
set<int> Union(const set<int> & s0, const set<int> & s1) {
    set<int> s;
    set_union(s0.begin(), s0.end(),
        s1.begin(), s1.end(),
        s, s.begin());
    return s;
}

A: If you can use C++17, there is std::set::merge for you. Note that this member function mutates both the object it belongs to and the function argument. Hence, changing the function signature of Union such that both sets are copied makes sense for an implementation that uses the merge function:
std::set<int> Union(std::set<int> s0, std::set<int> s1) {
   s0.merge(std::move(s1));

   return s0;
}

A: You have to use std::set_union with std::inserter like this:
std::set<int> Union(const std::set<int> & s0, const std::set<int> & s1) {
    std::set<int> s;
    std::set_union(s0.begin(), s0.end(),
        s1.begin(), s1.end(),
        std::inserter(s,s.begin()));

    return s;
}

And you will also have to define output stream operator for std::set.
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::set<T>& v)
{
    os << "[";
    for (auto it : v) {
        os << it;
        if (it != *v.rbegin())
            os << ", ";
    }
    os << "]\n";
    return os;
}

See demo here.
Note: For MSVC compiler, <iterator> header should be included to use std::inserter.


text:
Q: Fetching data from related objects (master-detail link) with standard controllers? I have a simple datatable which fetches records from my Service Orders object, I have a Service History table which is linked via forigen key to Service Order ID. I would like to know how I can fetch this data using the standard controller?
It should be noted that there could be many records related to any given Service Order, so I need to get the most recent one (either via ID dsc or Date Created dsc)
Apex:
<apex:page showHeader="false" title="My Orders" standardController="Service_Order__c" recordSetVar="orders">
  <apex:composition template="{!$Site.Template}">
    <apex:define name="body">

My Orders

    <apex:dataTable value="{!orders}" var="so" width="100%">
        <apex:column >
            <apex:facet name="header">Name</apex:facet>
            <apex:outputText value="{!so.Name}"/>
        </apex:column>

        <apex:column >
            <apex:facet name="header">Status</apex:facet>
            <apex:outputText value="{!Status_History__c.Name}"/>
        </apex:column>

    </apex:dataTable>

    </apex:define>
  </apex:composition>
</apex:page>

A: If you want to use the datatable as you have started, you just need to assign it to the proper related list name as the value. This is usually the plural version of the object name with __r at the end. You can confirm this in the definition of the master-detail field on the Service History object. Your datatable tag will look like
<apex:datatable value="{!Service_Order__c.Service_Histories__r}" var="so" >
</apex:datatable>

A simpler way: If the Related List defined on your page layout has the columns you need, you can just insert that related list directly into your VF page in place of your datatable:
<apex:relatedList list="Service_Histories__r" pageSize="20" />

https://www.salesforce.com/us/developer/docs/pages/Content/pages_compref_relatedList.htm
Make sure the Related List is defined as sorting by CreatedDate descending on the page layout.

A: There is an idea on the IdeaExchange to be able to sort using the standard controller, but as of now you would need to use an extension or I also found an example of Javascript sorting on a similar question/answer here. Only other workaround, without code, I could think of trying is to rollup the max of created date from the child object and render if child created date = the parent rollup field.


text:
Q: How do I create a temporary file in memory? I need to create some (small) temporary files in my zsh scripts, and I want them to live on RAM so as to avoid disk IO.
What are the idiomatic ways of doing this? I want it to work on Linux and macOS, though, of course, I can just handle them with a conditional.
The best solution I have found thus far is creating a ramfs (https://stackoverflow.com/questions/46224103/create-apfs-ram-disk-on-macos-high-sierra). This works, but needs setup on the machine which I prefer to avoid.
PS: The only usecase I have in mind currently is capturing stdout and stdin in different variables, but I believe I'll find other use cases as well in time.

A: You could use named pipes.  They behave like files, but are created in RAM, iirc.
They are created using the mkfifo-command.


text:
Q: How can I use E-Mailrelay to implement DKIM? I am trying to add DKIM to an existing windows server which is currently using IIS SMTP for outgoing mail.
It seems like this could be done by using E-Mailrelay. Unfortunately I could not find any reference on how exactly to configure DKIM in E-Mailrelay.
Is there something I missed in the docs or perhaps some third party tutorial that describes how to do this?

A: I implemented a simple command line app with C# / NET 6 to act as a filter in E-MailRelay:
using System.IO;
using System.Text;
using MimeKit;
using MimeKit.Cryptography;

namespace E_MailRelay.DKIM.Filter;

/// <summary>
/// Reads an e-mail message, adds a Hardcoded DKIM signature and and writes
the updated message back to disk
/// Note that this requires the installation MailKit to work.
/// </summary>

internal class Program
{
private const string DKIMSelector = "ENTER_YOUR_DKIM_SELECTOR_HERE";
private const string _DKIMDomain = "ENTER_YOUR_DOMAIN_NAME_HERE";
private const string DKIMPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n"
                                      + @"ENTER_YOUR_PRIVATE_KEY_HERE"
                                      + "\r\n-----END RSA PRIVATE KEY-----";

private static int Main(string[] args)
{
    LoadSignAndRewriteMail(args);
    return 102;
}

private static void LoadSignAndRewriteMail(string[] args)
{
    var emailMessage = MimeMessage.Load(args[0]);
    if (!emailMessage.Headers.Contains(HeaderId.DkimSignature)
        && !emailMessage.Headers.Contains(HeaderId.DomainKeySignature))
    {
        SignMail(emailMessage);
    }

    emailMessage.WriteTo(args[0]);
}

private static void SignMail(MimeMessage emailMessage)
{
    var pk = DKIMPrivateKey;
    MemoryStream stream = new(Encoding.UTF8.GetBytes(pk));
    {
        stream.Position = 0;
    }

    var dkimSigner = new DkimSigner(stream, _DKIMDomain, DKIMSelector);

    HeaderId[] dkimSignHeaders =
    {
        HeaderId.To, HeaderId.Cc, HeaderId.Subject, HeaderId.From, HeaderId.Date, HeaderId.MessageId, HeaderId.Body,
        HeaderId.Date, HeaderId.MimeVersion, HeaderId.Sender, HeaderId.ReplyTo, HeaderId.ContentTransferEncoding,
        HeaderId.ContentId, HeaderId.ContentDescription, HeaderId.ResentDate, HeaderId.ResentFrom,
        HeaderId.ResentSender, HeaderId.ResentTo, HeaderId.ResentCc, HeaderId.ResentMessageId, HeaderId.InReplyTo,
        HeaderId.References
    };

    dkimSigner.Sign(FormatOptions.Default, emailMessage, dkimSignHeaders);
}
}


text:
Q: how to make sorting by meta_key in wordpress in my search page wordpress sorting post by date.
But i want  sorting to meta_key in my template - imic_date (date of event).
I need to modify the search query, but where?
code that should work. But... where I add it?
$args = array(
    'post_type' => array('custom-post-type'),
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'meta_key' => 'imic_date'
    );
$loop = new WP_Query($args);

(sorry for my english) :D
edit:
my search.php file:
    <?php get_header(); ?>

        <?php
            if (have_posts()) :
                while (have_posts()):the_post();
                    echo'

';
                    if (has_post_thumbnail()):
                        echo '

                        ';
                        the_post_thumbnail('600x400', array('class' => "img-thumbnail"));
                        echo'
';
                    endif;
                    echo '
';
                    echo '
' . get_the_title() . '
';
                    echo '
                            ' . get_the_time(get_option('date_format')) . '
Time:
Date:
Price:
Venue:
Category:
'.imic_custom_taxonomies_terms_links().' ';
                    comments_popup_link(''.__('No comments yet','framework'), '1', '%', 'comments-link',__(' ','framework'));
                    echo'';
                    //echo imic_excerpt(50);
                    echo '
' . __('More ', 'framework') . '
';
                    echo '

';
                    echo '
';
                endwhile;
            else:
                echo '
';
                if (current_user_can('edit_posts')) :
                    ?>

<?php _e('NOT', 'framework'); ?>

<?php printf(__('NOT', 'framework'), admin_url('post-new.php')); ?>

                <?php else : ?>

<?php _e('NOT', 'framework'); ?>

<?php printf(__('NOT', 'framework')); ?>

                    <?php
                    echo '
';
                endif;
                ?>
            <?php
            endif; // end have_posts() check
            pagination();
            ?>

        <?php
            echo '
';
            dynamic_sidebar('sidebar');
            echo '
';
         ?>

<?php get_footer(); ?>

A: Try this code.
$args = array(
    'post_type' => array('custom-post-type'),
    'order_by' => array('imic_date'),
    'order' => 'ASC',
);
$loop = new WP_Query($args);

edit,
modify your code like this,
$args = array(
    'post_type' => array('custom-post-type'),
    'order_by' => array('imic_date'),
    'order' => 'ASC',
);
$loop = new WP_Query($args);
if ($loop->have_posts()) :
            while ($loop->have_posts()):$loop->the_post();
/** and then your code as used in original file */

Edit,
use the code bellow, it works ( I tested )
<?php $args = array(
'post_type' => 'event',
'orderby' => 'meta_value',
'meta_query' => array(array('key' => 'imic_date')),
'order' => 'desc',
'paged'=>$paged,
);
$loop = new WP_Query($args);
if ($loop->have_posts()) :
while ($loop->have_posts()):$loop->the_post(); ?>
<?php the_title(); ?>

and your rest of the code here..

A: global $wpdb;
$tb_posts = $wpdb->prefix . 'posts';
$tb_postmeta = $wpdb->prefix . 'postmeta';
$query = $wpdb->get_results("SELECT $colums
                                FROM $tb_posts
                                INNER JOIN $tb_postmeta
                                ON  $tb_posts.ID =  $tb_postmeta.post_id
                                WHERE $tb_postmeta.meta_key IN ('your_meta_key')
                                AND $tb_posts.post_status = 'publish'
                                ORDER BY post_date DESC
                                LIMIT 1
                                "
                                );
return $query;


text:
Q: ajax json Post to Spring mvc Controller "415 Unsupported Media Type" Hi so I am having problems with getting the JSON from my form to my work with spring mvc. My form is dynamic and the JSON comes back as a list of the criteria that the user filled out on the form. Ideally I would like to be able to get the JSON to come over as a Criterias object which contains a list of Criteria objects. (Like my model classes below) I dont know if this is possible or if there is a different way to go about it but any advice would be much appreciated.
**Currently I am receiving a 415 unsupported Media Type from the ajax post.
CONTROLLER
@RestController
public class Controller {
@RequestMapping(value-"/test",method=RequestMethod.GET
public ModelAndView getTest(){

ModelAndView model = new ModelAndView("test");

}
@RequestMapping(value-"/query",method=RequestMethod.POST
public ModelAndView submitTest(@RequestBody Criterias criterias){

//do stuff....
ModelAndView model = new ModelAndView("results");

}

MODEL
public class Criterias{
private List<Criteria> criteria = new ArrayList<Criteria>();
getter setter...
}

public class Criteria{
private String field;
private String filter;
private String operator;
private String criteria;

getters setters...
}

TEST.JSP

$(document).ready(function() {
  $("#theButton").click(function() {
    $('#myTable').append("
<select name = 'operator'><option>AND</option><option>OR</option></select>	Field:<select name='field'><option>a</option><option>b</option> <option>c</option> <option>d</option> </select> 	  <select name='filter'>  <option>Contains</option> <option>Does Not Contain</option> <option>Equals</option> <option>Does Not Equal</option> </select> 	  <input name='criteria' type='text'> 	<button type ='button' class ='rm' title = 'Remove Row'/>
")
  });
  $("#myTable").on('click', '.rm', function() {
    $(this).parent().parent().remove();
  });
});

function post() {

  $.ajax({
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    url: "query",
    data: JSON.stringify($('form').serializeArray())

  })

};

<form>

    <tbod>

        Field:
          <select name='field'>
            <option>a</option>
            <option>b</option>
            <option>c</option>
            <option>d</option>
          </select>

          <select name='filter'>
            <option>Contains</option>
            <option>Does Not Contain</option>
            <option>Equals</option>
            <option>Does Not Equal</option>
          </select>

          <input name='criteria' type='text'>

    </tbod>

  <input type="button" value="search" onclick="return post();">
  <input type="button" id="theButton" value="Add Criteria">

</form>

UPDATE
I attempted to do something a little simpler to narrow down the issue and from what I have looked up it seems to be a problem with the jackson mapping. The following code produces 415 error as well.
Controller
@RestController
public class Rest{
@RequestMapping(value="/testModel",method=RequestMethod.GET)
public ModelAndView getTestModel(){
   return new ModelAndView("testModel");
}

 @RequestMapping(value="/sendTestModel",method=RequestMethod.POST)
 public String submiteTestModel(@RequestBody TestModel test){
   return test.getName();
 }
 }

MODEL
public class TestModel{

private String id;
private String name;

//getters setters....
}

testModel.jsp

function post() {

    $.ajax({
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          type: "POST",
          contentType: 'application/json;,
    dataType: '
          json ',
    url: "sendTestModel",
    data: JSON.stringify({id:"1",name:"Bob"})

  })

};

<input type="button" value="search" onclick="return post();"/>

A: Calling JSON.stringify($('form').serializeArray()) will give you the following String
[{"name":"field","value":"a"},{"name":"filter","value":"Contains"},{"name":"criteria","value":""}]
Here is the documentation for serializeArray()
Clearly, this is not acceptable for a @RestController that expects JSON representation of Criterias object. Your JSON string should look like
{"criteria":[{"field":"a","filter":"Contains"},{"field":"Some other field value","filter":"Some other filter value"}]}
I have made a simple function to do it for you :
function convertCriterias(json){
    var o = new Object();
    var criterias = [];
    var c = new Object();

    for(var i = 0; i < json.length; i++){
        c[json[i].name] = json[i].value;
    }

    criterias[0] = c;

    o.criteria = criterias;

    return JSON.stringify(o);
}

Just replace JSON.stringify($('form').serializeArray()) with convertCriterias($('form').serializeArray())
EDIT
I believe you meant to use input type="button" instead of  input type="submit" for doing an AJAX post to your @RestController. And you meant to call return work() and not return post in the onclick event of the button.

A: Try the following options:

*

*Add in your controller's RequestMapping the content-type you want to get produced. Take a look at the Producible Media Types documentation for more information.
@ResponseBody @RequestMapping(value="/query", method=RequestMethod.POST, produces="application/json")

*Explicitly specify the Accept request header not just the Content-Type header in your jQuery Ajax call:
$.ajax({
          headers: {
                 Accept : "application/json; charset=utf-8",
                "Content-Type": "application/json; charset=utf-8"
  },.. })


text:
Q: Nodejs body-parser or request sending stream of compressed json Is it wise to send stream of zlib stream directly to rest api created in nodejs should we encode it before sending?
secondly I am not able to find any code sample to inflate compressed stream to rest api can body-parser does that but we hv multiple endpoints some accept json and some compressed json
app.use(bodyParser.json({limit: '50mb'}));

what needs to be done server file?


text:
Q: Firebase Real-time alert email notification when user submit data Android In firebase rule how to get an email notification to my own email when user submit dataFirebase rules.
From firebase rules side..
mail notification sent coding not done in the app

A: There is no way to trigger sending an email from Firebase security rules.
If you want to send an email when data is entered into the database, consider using a solution like Cloud Functions that can be triggered on such a database write operation. A similar (not same) scenario is shown in the example on notifying the user when something interesting happens.
Also see:

*

*Send email when Firebase database gets new data

*I want connect my firebase information with my mail

*Send data from Realtime Database using Firebase Functions to email

*Sending automated emails from Firebase through Google Cloud Platform (no third parties)


text:
Q: Matrix singular values distribution As a part of my project I had sliced short B&W video in frames, then denoting each frame as a matrix I reshaped 3D matrix ([frame]x[vertical_pixels]x[horizontal_pixels]) into 2D matrix - [frame]x(vertical_pixels * horizontal_pixels). After that I applied singular value decomposition (SVD) and sorted $\Sigma$ main diagonal elements in descending order. Plotting all that singular values got me a following graph (Log scale): .
And now I'm confused by min/max values being detached from the main trend. Do you have any ideas why it is happening?
EXTRA: It is CCTV recording, the road is being recorder and several people are passing by.


text:
Q: Include recurring appointments I am trying to get all appointments from client outlook with python and win32com. client, I just want to get all appointments from 2019 so that I could restrict the appointment Items, but when I restrict them I don't get the recurring appointments.
I already tried to enable recurring items with appointments.IncludeRecurrences = "True", but that didn't help.
import win32com.client
import time
import datetime
import os

f=open("mem.txt", "w")
counter=0
outlook= win32com.client.Dispatch("Outlook.Application")
namespace=outlook.GetNamespace("MAPI")
recipient = namespace.createRecipient("Some Calender")
resolved = recipient.Resolve()
sharedCalendar = namespace.GetSharedDefaultFolder(recipient, 9)
appointments = sharedCalendar.Items

# Restrict items
begin = datetime.date(2019, 1, 1)
end = datetime.date(2019, 12, 30)
restriction = "[Start] >= '" + begin.strftime("%m/%d/%Y") + "' AND [End] <= '" +end.strftime("%m/%d/%Y") + "'"
restrictedItems = appointments.Restrict(restriction)
appointments.IncludeRecurrences = "True"

# Iterate through restricted AppointmentItems
for appointmentItem in restrictedItems:
    month= appointmentItem.Start
    month=str(month)[5:-18] #just trim the month out of the date
    if month=='08': #need appointments from specific
        #mystuff
        #the code works but I want the recurring appointments too
print(counter)
f.close()

A: Did you try setting IncludeRecurrences to True before Restricting your items ?
Basically switching those two lines :
restrictedItems = appointments.Restrict(restriction)
appointments.IncludeRecurrences = "True"

A: Firstly, to retrieve all Outlook appointment items from the folder that meets the predefined condition, you need to sort the items in ascending order and set the IncludeRecurrences to true. You will not catch recurrent appointments if you don't do this before using the Restrict method!
    folderItems = folder.Items;
    folderItems.IncludeRecurrences = true;
    folderItems.Sort("[Start]");
    resultItems = folderItems.Restrict(restrictCriteria);

You may find the following articles helpful:

*

*How To: Use Restrict method in Outlook to get calendar items

*How To: Retrieve Outlook calendar items using Find and FindNext methods


text:
Q: How to create a pivot table uing python pandas with column entries pivoted to column heading and a new column for blank entries? I have a table in DataFrame taken from excel:
col A      ColB  colC  colD
123451      a     w     p
123452      b     x     q
123453      c     y     r
123454      a     x
123454      a     w     p

And I want something like this using pandas.pivot_table:
colC   p  q  r  "unassigned" "total"
 w     2  0  0      0           2
 x     0  1  0      1           2
 y     0  0  1      0           1

A: You can use crosstab for first columns and then check missing values with isna and aggregate by agg for count by sum and total by size, last join togehter by DataFrame.join:
df1 = pd.crosstab(df.colC, df.colD)
print (df1)
colD  p  q  r
colC
w     2  0  0
x     0  1  0
y     0  0  1

df2 = (df['colD'].isna()
                 .astype(int)
                 .groupby(df['colC'])
                 .agg([('unassigned','sum'),('total','size')]))
print (df2)
      unassigned  total
colC
w              0      2
x              1      2
y              0      1

df = df1.join(df2).reset_index()
print (df)
  colC  p  q  r  unassigned  total
0    w  2  0  0           0      2
1    x  0  1  0           1      2
2    y  0  0  1           0      1

A: You can replace all the None with 'unassigned'. Then use crosstab to get respective counts. Use sum  with proper axis for total count.
Following is the code for doing this
df1 = df[['colC', 'colD']].fillna('unassigned')
df1 = pd.crosstab(df1.colD, df1.colD)
df1['total'] = df1.sum(axis=1)

Following is the output for the code
D   p   q   r   unassigned  total
C
w   2   0   0    0           2
x   0   1   0    1           2
y   0   0   1    0           1


text:
Q: how to use Firefox but pretend that I am using iPhone (to use Firebug to examine the page design) Is there a way to use Firefox and Firebug but pretend it is iPhone's Safari by faking the User Agent string?  I want to use Firefox to examine the Amazon or Gmail sites and see how the page is laid out for iPhone... just for fun and for experiment.  Is there a way?  thanks?

A: You can fake the user agent string using the instructions great_llama provided, but remember that Firefox is not Safari and it probably won't lay out the page identically.  If you're on a Windows or OS X machine you can use Safari to see how it will look with a higher degree of accuracy.

A: Here are some instructions on how to do it.

A: Go to the emulator and you can run your dev version. You can then use firebug on the emulator frame


text:
Q: Cannot hide and show What I intend is:
When phone button is clicked, phone no. appears and email, if shown, disappears.
When email button is clicked, phone no., if shown, disappears and email is shown.
Here is my jsfiddle https://jsfiddle.net/adzk6tnv/.
When I do not hide the email id initially, it works fine. When I click on phone button, the email id disappears and phone no. appears, but the same does not happen when both are hidden initially.
Please can someone help me out?

Name

Designation

+91 8888888888

something@gmail.com

            phone

            email

A: Here's a simplified version.
It slides up the unwanted data.  (If not visible, it does nothing.)
When complete, it toggles the wanted data:

$(document).ready(function() {
  $('.no, .email').hide();

  $('.phone').click(function() {
    $('.email').slideUp(function() {
      $('.no').slideToggle();
    });
  });

  $('.mail').click(function() {
    $('.no').slideUp(function() {
      $('.email').slideToggle();
    });
  });
});

Name

Designation

+91 8888888888

something@gmail.com

phone

email

A: The problem is because you are only binding the click handler for .phone if .email is visible:
if($(".email").is(":visible")){

    $(".phone").click(function(){
    $(".email").slideToggle(function(){
        $(".no").fadeIn();

    })})
}

Since .email starts out hidden, you never bind the handler so clicking it does nothing.

A: Along the same lines as Rich Hitchcock's answer, I've produced the results you wanted.  The slideUp timing is not as succinct and defined but it does showcase more control with timing as well as your original intent of setting the conditional is(':visible') statement.
jQuery
//Show Hide onClick functionality - Alexander Dixon 2015
//http://stackoverflow.com/questions/31710666/promblem-in-hide-and-show
//http://codebeautify.org/htmlviewer/
var $phoneEmail = $('li > a'),
    $emailLink = $('li a.mail'),
    $phoneLink = $('li a.phone'),
    $viewPhone = $('p.no'),
    $viewEmail = $('p.email');

//Initially hide the phone and email fields function declaration
function hideBoth() {
    $viewPhone.hide();
    $viewEmail.hide();
}

//Run the function to hide the fields
hideBoth();

//Prevent the link from behaving like a link
$phoneEmail.on('click', function(e) {
    e.preventDefault();
});

//Bind a mouse down (very similar to a click) event to the email link that will slide show email view in 300 milliseconds
$emailLink.on('mousedown', function() {
    if($viewPhone.is(':visible')) {
        $viewPhone.slideUp(205);
    }
    $viewEmail.slideToggle();
});

//Bind a mouse down (very similar to a click) event to the phone link that will slide show phone view in 300 milliseconds
$phoneLink.on('mousedown', function() {
    if($viewEmail.is(':visible')) {
        $viewEmail.slideUp(205);
    }
    $viewPhone.slideToggle();
});

HTML

Name

Designation

+91 8888888888

something@gmail.com

            Phone

            Email


text:
Q: Select All across Paging and Display Results per page, whilst Disabling and Enabling a Button using JQuery I have a Select All option, with a button. On load the button is disabled. if you choose the select all or two or more select items in the list the button is disabled. However, I have paging and a display for a number of items to show in the table. Is there a way I can persist it so that it works across paging, and when the display number is changed?
Here is my code:
//Disable Top Verify Button if two or more checkboxes are selected.
    $(document)('.verifyshipment-btn').prop('disabled', true);
    $(document).on(".individual").on("click", function () {
        if ($(".individual:checked").length > 1) {
            $('.verifyshipment-btn').prop('disabled', false);
        }
        else {
            $('.verifyshipment-btn').prop('disabled', true);
        }
    });

    //Select All
    $('.verifyshipment-btn').prop('disabled', true);
    $(document).on(".selectall").click(function () {
        if ($(".individual:checked").length > 1) {
            $('.verifyshipment-btn').prop('disabled', false);
        }
        else {
            $('.verifyshipment-btn').prop('disabled', true);
        }
    });

Paging and Display options
$(document).on("click",
        "#indexPager a",
        function() {
            if ($(this).parent().hasClass('disabled') || $(this).parent().hasClass('active'))
                return false;
            $.ajax({
                url: $(this).attr("href"),
                type: 'GET',
                cache: false,
                success: function(result) {
                    $('#tableContainer').html(result);
                    addBootstrapTooltips("#tableContainer");
                }
            });
            return false;
        });
    $(document).on("change",
        "#pageSizeSelector",
        function() {
            var selectedValue = $(this).val();
            $.ajax({
                url: selectedValue,
                type: 'GET',
                cache: false,
                success: function(result) {
                    $('#tableContainer').html(result);
                    addBootstrapTooltips("#tableContainer");
                }
            });
        });

A: As the previous commenters have pointed out, you really have two options:
(1) Saving the data on your application server (via something like a session cookie) and then making your client query the server for that information when it needs it.
(2) Saving the data in the session/local storage of your browser and retrieving it from there when you need it.
If you need this option to persist across devices (i.e., user switches computers in the middle of the interaction flow you have presented), then the best way to do it would be (1). However, adding additional data to the backend can be a pain if you are not a backend developer (e.g., do you know how / have permission to create / manipulate databases and create new api endpoints?).
For everything else, I would recommend using (2), specifically session storage which will automatically garbage collect the data when the user session is over (survives reloads but gets deleted when browser is closed). If you need more manual data management you can use the local storage of the browser.


text:
Q: Affix hide top when active I have a navbar and wanted to apply affix, but only to half of that navbar. The whole thing is 1 solid block. I figured that when affix is active I could try to set the top attribute to a negative number and get rid of that upper part of navbar. I just don't know how to do this. Any suggestion is welcomed.
So this is what I tried:

The CSS for this is:
.row1{
padding-top: 10px;
}

.row2 {
    padding-bottom: 20px;
}

.affix {
    top: -10px;
    width: 100%;
}

#header-nav.affix {
    position: absolute;
    top: -50px;
}

But apparently top doesn't seem to change anything at all.

A: It actually works just putting margin-top: -50px; in .affix class. The problem was that the G.Chrome decides to use the old CSS than the new one sometimes. I just ran it from inspect element->network with "Disable cache" checked.
Only this is needed in CSS:
.affix {
    margin-top: -50px;
    width: 100%;
}


text:
Q: Far Cry doesn't start I downloaded uplay and I redeemed a Far Cry 4 code.  When the download was finished I pressed play and this happened:

What can I do?

A: Far Cry has a horrible rating of "Garbage" on Wine HQ and will not run on Ubuntu
Unfortunately, gaming on Linux has always been a bit lacking due to lack of Linux releases. Sometimes, no matter how hard we try, we just can't get some things to work.


text:
Q: Laravel 9: Why does sail up not end? I have problem to install a laravel app according to the Getting Started guide for laravel 9.
After starting the sail up command (./vendor/bin/sail up) it runs now for over 3 hours. the last logs are:
my-app-meilisearch-1   | [2022-03-04T23:43:26Z INFO  actix_web::middleware::logger] 127.0.0.1:55080 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000061

my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:43:56Z INFO  actix_web::middleware::logger] 127.0.0.1:55084 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000055
my-app-meilisearch-1   | [2022-03-04T23:44:27Z INFO  actix_web::middleware::logger] 127.0.0.1:55088 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000053
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:44:57Z INFO  actix_web::middleware::logger] 127.0.0.1:55092 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000054
my-app-meilisearch-1   | [2022-03-04T23:45:27Z INFO  actix_web::middleware::logger] 127.0.0.1:55096 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000101
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:45:57Z INFO  actix_web::middleware::logger] 127.0.0.1:55100 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000063
my-app-meilisearch-1   | [2022-03-04T23:46:27Z INFO  actix_web::middleware::logger] 127.0.0.1:55104 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000068
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:46:57Z INFO  actix_web::middleware::logger] 127.0.0.1:55108 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000066
my-app-meilisearch-1   | [2022-03-04T23:47:27Z INFO  actix_web::middleware::logger] 127.0.0.1:55112 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000069
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:47:58Z INFO  actix_web::middleware::logger] 127.0.0.1:55116 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000050
my-app-meilisearch-1   | [2022-03-04T23:48:28Z INFO  actix_web::middleware::logger] 127.0.0.1:55120 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000044
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:48:58Z INFO  actix_web::middleware::logger] 127.0.0.1:55124 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000048
my-app-meilisearch-1   | [2022-03-04T23:49:28Z INFO  actix_web::middleware::logger] 127.0.0.1:55128 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000072
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:49:58Z INFO  actix_web::middleware::logger] 127.0.0.1:55132 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000038
my-app-meilisearch-1   | [2022-03-04T23:50:29Z INFO  actix_web::middleware::logger] 127.0.0.1:55136 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000048
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:50:59Z INFO  actix_web::middleware::logger] 127.0.0.1:55140 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000046
my-app-meilisearch-1   | [2022-03-04T23:51:29Z INFO  actix_web::middleware::logger] 127.0.0.1:55144 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000040
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:51:59Z INFO  actix_web::middleware::logger] 127.0.0.1:55148 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000039
my-app-laravel.test-1  | [Fri Mar  4 23:52:12 2022] 172.18.0.1:41200 Accepted
my-app-laravel.test-1  | [Fri Mar  4 23:52:17 2022] 172.18.0.1:41200 Closing
my-app-laravel.test-1  | [Fri Mar  4 23:52:17 2022] 172.18.0.1:41204 Accepted
my-app-laravel.test-1  | [Fri Mar  4 23:52:17 2022] 172.18.0.1:41204 [200]: GET /favicon.ico
my-app-laravel.test-1  | [Fri Mar  4 23:52:17 2022] 172.18.0.1:41204 Closing
my-app-meilisearch-1   | [2022-03-04T23:52:30Z INFO  actix_web::middleware::logger] 127.0.0.1:55160 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000064
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:53:01Z INFO  actix_web::middleware::logger] 127.0.0.1:55164 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000066
my-app-meilisearch-1   | [2022-03-04T23:53:31Z INFO  actix_web::middleware::logger] 127.0.0.1:55168 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000049
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:54:01Z INFO  actix_web::middleware::logger] 127.0.0.1:55172 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000038
my-app-meilisearch-1   | [2022-03-04T23:54:31Z INFO  actix_web::middleware::logger] 127.0.0.1:55176 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000040
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:55:01Z INFO  actix_web::middleware::logger] 127.0.0.1:55180 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000041
my-app-meilisearch-1   | [2022-03-04T23:55:32Z INFO  actix_web::middleware::logger] 127.0.0.1:55184 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000042
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:56:02Z INFO  actix_web::middleware::logger] 127.0.0.1:55188 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000046
my-app-meilisearch-1   | [2022-03-04T23:56:32Z INFO  actix_web::middleware::logger] 127.0.0.1:55192 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000043
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:57:02Z INFO  actix_web::middleware::logger] 127.0.0.1:55196 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000110
my-app-meilisearch-1   | [2022-03-04T23:57:32Z INFO  actix_web::middleware::logger] 127.0.0.1:55200 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000044
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:58:02Z INFO  actix_web::middleware::logger] 127.0.0.1:55204 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000039
my-app-meilisearch-1   | [2022-03-04T23:58:33Z INFO  actix_web::middleware::logger] 127.0.0.1:55208 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000038
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-04T23:59:03Z INFO  actix_web::middleware::logger] 127.0.0.1:55212 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000108
my-app-meilisearch-1   | [2022-03-04T23:59:34Z INFO  actix_web::middleware::logger] 127.0.0.1:55216 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000048
my-app-mailhog-1       | [APIv1] KEEPALIVE /api/v1/events
my-app-meilisearch-1   | [2022-03-05T00:00:05Z INFO  actix_web::middleware::logger] 127.0.0.1:55220 "GET /health HTTP/1.1" 200 22 "-" "Wget" 0.000057

All the messages are repeating again and again. Is this a normal duration for the script?

A: You are running the docker container with Sail cli
The missing part is

-d

(Docker detached mode) which is used to run the container in the background
docker up -d

In your case ./vendor/bin/sail up -d
Just google
Docker detached mode

A: Just run it with -d flag for detached. Sail aliased docker-compose command.
i.e. ./vendor/bin/sail up -d
See the full list of options here.
https://docs.docker.com/engine/reference/commandline/compose_up/


text:
Q: Android Grdiview not displaying correctly We have built an online shopping app.
We have two layouts for gridview.
The first one:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
android:paddingBottom="0dp"
tools:context=".HomeActivity">
<GridView
     android:id="@+id/gridView"
     android:numColumns="3"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
</RelativeLayout>

And the second one for each gridview cell:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/singleCell"
android:layout_width="345px"
android:layout_height="400px"
android:background="#E6E6E6">

 <ImageView
    android:contentDescription="@string/hello_world"
    android:id="@+id/profileImg"
    android:layout_width="fill_parent"
    android:layout_height="330px"
    android:scaleType="fitXY"
    android:layout_marginLeft="1px"
    android:layout_marginTop="2px"/>

<TextView
    android:id="@+id/friend_name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="Name"
    android:textColor="#000000"
    android:textStyle="bold"
    android:layout_marginTop="340px"
    android:layout_marginLeft="20px"
    android:textSize="13sp">
</TextView>

</FrameLayout>

The problem is that in some devices the gridview is displayed correctly like this and the ratio is ok.
gridview is displayed correctly on some devices
but in several other devices, the images height and ratio changes and the image is displayed incorrectly.
gridview is displayed incorrectly on some devices
We would be happy if you give us a solution and help us. This is a critical problem as the gridcell image height changes and gets longer in some devices.

A: You can try with changing the scale type of Imageview. Write this line
android:scaleType="centerCrop"

instead of
android:scaleType="fitXY"

A: @nazmul-hasan-masum, Thanks. I used your solution but at first the problem didn't get solved so I changed the imageview and text unit from px to the equivalent dp and everything is ok right now.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/singleCell"
    android:layout_width="345px"
    android:layout_height="400px"
    android:background="#E6E6E6">

     <ImageView
        android:contentDescription="@string/hello_world"
        android:id="@+id/profileImg"
        android:layout_width="fill_parent"
        android:layout_height="128dp"
        android:scaleType="centerCrop"
        android:layout_marginLeft="1px"
        android:layout_marginRight="1px"
        android:layout_marginTop="2px"/>

    <TextView
        android:id="@+id/friend_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Name"
        android:textColor="#000000"
        android:textStyle="bold"
        android:layout_marginTop="130dp"
        android:layout_marginLeft="20px"
        android:textSize="13sp">
    </TextView>

</FrameLayout>


text:
Q: wxPython childframes interaction I've created a simple program that consists from one mainframe(Frame) and two childframes (ChildFrame1 and ChildFrame2). Mainframe has two buttons one will check if the ChildFrame1 is already created and create the same if not and the other will check if the ChildFrame2 is already created and create the same if not. Now the tricky part (at least tricky for me), ChildFrame1 has a button that needs to check if the ChildFrame2 is already created from mainframe and if not create it. In my code this button just creates another ChildFrame2 alongside previously created ChildFrame2 from mainframe. How can I make this to work? Basically I have two buttons on two frames but one event.
Code
import wx

class Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY,'Parent')
        panel = wx.Panel(self, -1)

        sizer = wx.BoxSizer(wx.VERTICAL)
        button = wx.Button(panel, -1, 'Open Child1')
        button2 = wx.Button(panel, -1, 'Open Child2')

        sizer.Add(button, 0, wx.CENTER|wx.ALL, 5)
        sizer.Add(button2, 0, wx.CENTER|wx.ALL, 5)

        panel.SetSizer(sizer)

        self.Bind(wx.EVT_BUTTON, self.onButton,  button)
        self.Bind(wx.EVT_BUTTON, self.onButton2,  button2)

    def onButton(self, e):
        try:
            self.ChildF.Show()
        except:
            self.ChildF = ChildFrame1()
            self.ChildF.Show()

        self.ChildF.SetFocus()

    def onButton2(self, e):
        try:
            self.ChildF2.Show()
        except:
            self.ChildF2 = ChildFrame2()
            self.ChildF2.Show()

        self.ChildF2.SetFocus()

class ChildFrame1(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, wx.GetApp().TopWindow, wx.ID_ANY, 'Child1')
        panel = wx.Panel(self, -1)

        sizer = wx.BoxSizer(wx.VERTICAL)
        button = wx.Button(panel, -1, 'Open Child2')
        sizer.Add(button, 0, wx.CENTER|wx.ALL, 5)

        panel.SetSizer(sizer)

        self.Bind(wx.EVT_BUTTON, self.OnButton, button)

    def OnButton(self,e):
        try:
            self.ChildF.Show()
        except:
            self.ChildF = ChildFrame2()
            self.ChildF.Show()

        self.ChildF.SetFocus()

class ChildFrame2(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, wx.GetApp().TopWindow, wx.ID_ANY, 'Child2')

if __name__ == '__main__':
    app = wx.App()
    frame = Frame().Show()
    app.MainLoop()

A: You could Bind ChildFrame1's button handler to the parent frames method for opening/showing ChildFrame2.
import wx

class Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, 'Parent')
        panel = wx.Panel(self, -1)

        sizer = wx.BoxSizer(wx.VERTICAL)
        button = wx.Button(panel, -1, 'Open Child1')
        button2 = wx.Button(panel, -1, 'Open Child2')

        sizer.Add(button, 0, wx.CENTER | wx.ALL, 5)
        sizer.Add(button2, 0, wx.CENTER | wx.ALL, 5)

        panel.SetSizer(sizer)

        self.Bind(wx.EVT_BUTTON, self.onButton, button)
        self.Bind(wx.EVT_BUTTON, self.onButton2, button2)

    def onButton(self, e):
        try:
            self.ChildF.Show()
        except:
            self.ChildF = ChildFrame1()
            self.ChildF.Show()

        self.ChildF.SetFocus()

    def onButton2(self, e):
        try:
            self.ChildF2.Show()
        except:
            self.ChildF2 = ChildFrame2()
            self.ChildF2.Show()

        self.ChildF2.SetFocus()

class ChildFrame1(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, wx.GetApp().TopWindow, wx.ID_ANY, 'Child1')
        panel = wx.Panel(self, -1)

        sizer = wx.BoxSizer(wx.VERTICAL)
        button = wx.Button(panel, -1, 'Open Child2')
        sizer.Add(button, 0, wx.CENTER | wx.ALL, 5)

        panel.SetSizer(sizer)

        self.Bind(wx.EVT_BUTTON, self.GetParent().onButton2, button)

class ChildFrame2(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, wx.GetApp().TopWindow, wx.ID_ANY, 'Child2')

if __name__ == '__main__':
    app = wx.App()
    frame = Frame().Show()
    app.MainLoop()


text:
Q: How can I use literal list in Django template file? From a Django template file I want to check if my variable myVar is "A" or "B" (or "C" or "D", etc..).
So I would like to do something like this:
{% if myVar in ["A", "B"] %}
    Hello
{% else %}
    World
{% endif %}

But this gives me a syntax error in the first line.
How then can I use a literal list in the Django template file?

A: you can't define a list directly in the template. You could pass a list to the template  using a view in views. py and a url in urls. py
ex:In views. py
def view_name(request):
    list_name=['A', 'B', 'C'];
    render(request, 'directory/template_name.html'
    {'list_name':list_name})

In urls. py
urlpatterns = [
               path('index/', views.view_name, name='main-view'),
 ]

In template
{% if myVar in list_name%}
Hello
{% else %}
World
{% endif %}

A: The answer can be found here: check for presence in a list django template
This question is essentially a duplicate.


text:
Q: how to run a command on background on command line and how to rerun it automatically I have an windows server and I run a command on cmd with ffmpeg . I restream an hls with it . everything is good but sometimes because of source stream this command get stop . I want to know if there is any solution to run this command and when it stop it run again automatically . what should I do ?
this is my ffmpeg code :
ffmpeg -i http://test.m3u8 -c copy -segment_list_flags +live -hls_time 10 -hls_list_size 6 -hls_wrap 10 -segment_list_type m3u8 -map 0:0 -map 0:1 -segment_time 10 output.m3u8

I think I should  use bat file . but I don't know how I should do this and integrate it with ffmpeg . Can someone help me on this case ? If you think my question is not correct  please don't give me a negative point.


text:
Q: Using a jquery datatable with php mysql data - developing further I've been exploring jquery datatables and flexigrid plug ins to display data from a mysql database.
I have both versions displaying data from the database which comes from a php script. So all ok there.
However I want to add a form to enable a search to made on criteria eg from and to dates, types etc. multiple critieria. Flexi grid has a basic filter - i've not delved too deeply with datatable.
I can do this without using a plug in but I would like my results to be displayed in the chosen datagrid and then use that tables functionality. I'm just not sure of the workflow on how to do this.
How do I initiate the creation of a flexigrid or datatable from the call back of a form submission with the results from that call back? Do I save the results in a variable and pass that to the plug ins?
I hope my question makes sense. I know what I would like to do, just not sure how to do it
I'm ok with php - newsih to javascript
Thanks

A: Flexigrid
You can create a form (e.g. call it searchForm) and then serialize this data and pass it into the Flexigrid search parameters.
You can then add form data to a Flexigrid implementation on the click of the button:
$(function () {
    $('#btnSearch').click(function () {
        addFormData();

        // Reload the grid from the URL, passing in search parameters from addFormData
        $('#flexGrid').flexOptions({ url: '/search/here/' }).flexReload();
    });
});

And the addFormData function just serializes the data from the form and adds it to the parameters of the Flexigrid call back to the server:
function addFormData() {
    //Retrieve all input data from the searchForm
    var allSearchParams = $('#searchform').serializeArray();
    //Add the parameters to Flexigrid, so when it reloads, it will use them to filter the data
    $("#flexGrid").flexOptions({ params: allSearchParams });
    return true;
}

DataTables
DataTables has handy plugins like the Column Filter which has server-side filtering to do all this work for you, or I would recommend reading up on DataTables server-side processing.


text:
Q: When exactly does a called function end? From a textbook I was reading, it is said that for functions with a return value, the return value is used to initialize a temporary at the call site.
What I want to know is does that happen before or after the called function exits? In other words, if I have a variable(say, an int) defined inside the called function, will it get destroy before or after the temporary is initialized?

A: This is the technical view. This might not be interesting to language-lawyers, but for other people, it might me instructive.

A function ends precisely with the branch instruction that transfers control back to the caller. Before this point, the callee has full control, after this point, the caller has full control over what the CPU does. Generally, there is precisely one CPU instruction that is used for this control transfer. On X86-64, that's the ret instruction, PowerPC used blr, other CPUs have other names for the same thing. The name does not matter, though.
Anything, that's within the responsibility of the function itself must happen before this instruction, anything that's none of the callee's business happens somewhere else.
As the caller does not know which variables a function creates, it cannot be the callers responsibility to destruct them. More generally, the callee has to release any stack space that it allocated for its own purposes. As such, the callee must perform such cleanup itself before exiting by issuing the ret instruction. This means, that any local variables must vanish before the function exits.
Things are a bit more complicated when it comes to returning a result from a function: This requires both caller and callee to collaborate. The details differ between the different calling conventions, but there are generally two cases:

*

*The return value is passed in a register.
In this case, the callee will load the return value into a well-known register, and the caller will use that same register to access the return value.

*The return value is passed on the stack.
In this case, the callee will place the data that is to be returned at a defined position within the callers stack frame, and the caller will examine that same memory region for the functions result after the call has returned.
TL;DR: If something is a functions responsibility, it must happen before the function returns (= executes the ret instruction). Freeing stack space and returning data to the caller are such responsibilities.

A: Before
For functions returning by value, the temporary at the call site will be initialized before the scope of the function exits. Otherwise, any return value would be destroyed before it could be passed to the call site.

A: The Function ends after a return statement
the variables that are declared in that scope will go out of scope and you will not be able to use that unless the variable is declared as static


text:
Q: Problems building hadoop 3.0.0-SNAPSHOT on Windows 7 64 bits and Java 8 and Maven3.3.3 When I use Windows SDK 7.1 Command Prompt building apache/hadoop 3.0.0 with the command of mvn clean compile.But I have some problems when the process go to here.How can I fixed this problem ? Many many thanks to you.
[INFO] ------------------------------------------------------------------------
[INFO] Building Apache Hadoop Common 3.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Apache Hadoop Main ................................. SUCCESS [  0.504 s]
[INFO] Apache Hadoop Build Tools .......................... SUCCESS [  0.584 s]
[INFO] Apache Hadoop Project POM .......................... SUCCESS [  0.627 s]
[INFO] Apache Hadoop Annotations .......................... SUCCESS [  2.683 s]
[INFO] Apache Hadoop Project Dist POM ..................... SUCCESS [  0.112 s]
[INFO] Apache Hadoop Assemblies ........................... SUCCESS [  0.188 s]
[INFO] Apache Hadoop Maven Plugins ........................ SUCCESS [  1.092 s]
[INFO] Apache Hadoop MiniKDC .............................. SUCCESS [  1.873 s]
[INFO] Apache Hadoop Auth ................................. SUCCESS [  1.554 s]
[INFO] Apache Hadoop Auth Examples ........................ SUCCESS [  0.400 s]
[INFO] Apache Hadoop Common ............................... FAILURE [  0.021 s]
[INFO] Apache Hadoop NFS .................................. SKIPPED
[INFO] Apache Hadoop KMS .................................. SKIPPED
[INFO] Apache Hadoop Common Project ....................... SKIPPED

[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 12.969 s
[INFO] Finished at: 2015-07-14T10:50:53+08:00
[INFO] Final Memory: 56M/269M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to parse plugin descriptor for org.apache.hadoop:hadoop-maven-plu
gins:3.0.0-SNAPSHOT (C:\Users\mingleiz\mygit\hadoop\hadoop-maven-plugins\target\
classes): No plugin descriptor found at META-INF/maven/plugin.xml -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e swit
ch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please rea
d the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginDescript
orParsingException

A: I sovle this problem just now.Following is my solution:
1:set Platform=x64 (when building on a 64-bit system)
2:install VS 2010 professional and SP1 is must need.
OK,and here is the ending for my building.
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Apache Hadoop Main ................................. SUCCESS [  2.794 s]
[INFO] Apache Hadoop Build Tools .......................... SUCCESS [  1.582 s]
[INFO] Apache Hadoop Project POM .......................... SUCCESS [  1.160 s]
[INFO] Apache Hadoop Annotations .......................... SUCCESS [  2.250 s]
[INFO] Apache Hadoop Project Dist POM ..................... SUCCESS [  0.629 s]
[INFO] Apache Hadoop Assemblies ........................... SUCCESS [  0.349 s]
[INFO] Apache Hadoop Maven Plugins ........................ SUCCESS [  2.902 s]
[INFO] Apache Hadoop MiniKDC .............................. SUCCESS [  2.578 s]
[INFO] Apache Hadoop Auth ................................. SUCCESS [  5.007 s]
[INFO] Apache Hadoop Auth Examples ........................ SUCCESS [  2.580 s]
[INFO] Apache Hadoop Common ............................... SUCCESS [01:44 min]
[INFO] Apache Hadoop NFS .................................. SUCCESS [  3.074 s]
[INFO] Apache Hadoop KMS .................................. SUCCESS [ 22.619 s]
[INFO] Apache Hadoop Common Project ....................... SUCCESS [  0.071 s]
[INFO] Apache Hadoop HDFS Client .......................... SUCCESS [ 18.156 s]
[INFO] Apache Hadoop HDFS ................................. SUCCESS [01:50 min]
[INFO] Apache Hadoop HttpFS ............................... SUCCESS [01:09 min]
[INFO] Apache Hadoop HDFS BookKeeper Journal .............. SUCCESS [ 37.003 s]
[INFO] Apache Hadoop HDFS-NFS ............................. SUCCESS [  1.932 s]
[INFO] Apache Hadoop HDFS Project ......................... SUCCESS [  0.071 s]
[INFO] Apache Hadoop YARN ................................. SUCCESS [  0.076 s]
[INFO] Apache Hadoop YARN API ............................. SUCCESS [  9.896 s]
[INFO] Apache Hadoop YARN Common .......................... SUCCESS [01:24 min]
[INFO] Apache Hadoop YARN Server .......................... SUCCESS [  0.088 s]
[INFO] Apache Hadoop YARN Server Common ................... SUCCESS [  4.608 s]
[INFO] Apache Hadoop YARN NodeManager ..................... SUCCESS [  8.123 s]
[INFO] Apache Hadoop YARN Web Proxy ....................... SUCCESS [  1.975 s]
[INFO] Apache Hadoop YARN ApplicationHistoryService ....... SUCCESS [ 14.526 s]
[INFO] Apache Hadoop YARN ResourceManager ................. SUCCESS [ 15.525 s]
[INFO] Apache Hadoop YARN Server Tests .................... SUCCESS [  1.688 s]
[INFO] Apache Hadoop YARN Client .......................... SUCCESS [  3.273 s]
[INFO] Apache Hadoop YARN SharedCacheManager .............. SUCCESS [  1.601 s]
[INFO] Apache Hadoop YARN Applications .................... SUCCESS [  0.058 s]
[INFO] Apache Hadoop YARN DistributedShell ................ SUCCESS [  1.453 s]
[INFO] Apache Hadoop YARN Unmanaged Am Launcher ........... SUCCESS [  0.789 s]
[INFO] Apache Hadoop YARN Site ............................ SUCCESS [  0.074 s]
[INFO] Apache Hadoop YARN Registry ........................ SUCCESS [  2.915 s]
[INFO] Apache Hadoop YARN Project ......................... SUCCESS [  0.170 s]
[INFO] Apache Hadoop MapReduce Client ..................... SUCCESS [  0.117 s]
[INFO] Apache Hadoop MapReduce Core ....................... SUCCESS [ 11.576 s]
[INFO] Apache Hadoop MapReduce Common ..................... SUCCESS [  6.131 s]
[INFO] Apache Hadoop MapReduce Shuffle .................... SUCCESS [  1.574 s]
[INFO] Apache Hadoop MapReduce App ........................ SUCCESS [  8.106 s]
[INFO] Apache Hadoop MapReduce HistoryServer .............. SUCCESS [  3.868 s]
[INFO] Apache Hadoop MapReduce JobClient .................. SUCCESS [ 16.826 s]
[INFO] Apache Hadoop MapReduce HistoryServer Plugins ...... SUCCESS [  0.649 s]
[INFO] Apache Hadoop MapReduce NativeTask ................. SUCCESS [  2.308 s]
[INFO] Apache Hadoop MapReduce Examples ................... SUCCESS [  3.706 s]
[INFO] Apache Hadoop MapReduce ............................ SUCCESS [  0.145 s]
[INFO] Apache Hadoop MapReduce Streaming .................. SUCCESS [  7.313 s]
[INFO] Apache Hadoop Distributed Copy ..................... SUCCESS [ 30.467 s]
[INFO] Apache Hadoop Archives ............................. SUCCESS [  0.925 s]
[INFO] Apache Hadoop Rumen ................................ SUCCESS [  4.658 s]
[INFO] Apache Hadoop Gridmix .............................. SUCCESS [  3.211 s]
[INFO] Apache Hadoop Data Join ............................ SUCCESS [  1.279 s]
[INFO] Apache Hadoop Ant Tasks ............................ SUCCESS [  0.441 s]
[INFO] Apache Hadoop Extras ............................... SUCCESS [  1.121 s]
[INFO] Apache Hadoop Pipes ................................ SUCCESS [  0.063 s]
[INFO] Apache Hadoop OpenStack support .................... SUCCESS [  1.489 s]
[INFO] Apache Hadoop Amazon Web Services support .......... SUCCESS [ 41.175 s]
[INFO] Apache Hadoop Azure support ........................ SUCCESS [ 10.494 s]
[INFO] Apache Hadoop Client ............................... SUCCESS [  0.321 s]
[INFO] Apache Hadoop Mini-Cluster ......................... SUCCESS [  0.165 s]
[INFO] Apache Hadoop Scheduler Load Simulator ............. SUCCESS [  2.467 s]
[INFO] Apache Hadoop Tools Dist ........................... SUCCESS [  0.356 s]
[INFO] Apache Hadoop Tools ................................ SUCCESS [  0.051 s]
[INFO] Apache Hadoop Distribution ......................... SUCCESS [  0.109 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 11:47 min
[INFO] Finished at: 2015-07-14T18:09:24+08:00
[INFO] Final Memory: 227M/583M
[INFO] ------------------------------------------------------------------------


text:
Q: How to Scroll Down Youtube Channel on Chrome with Selenium in Python I am trying to scroll down a YouTube Channel's "Videos" tab so I can obtain the links to all the videos in that channel. I am using the Selenium module in Python 3, with Google Chrome as the browser. This is the method in my class that does this part (this is called right after I call self.driver.get(CHANNEL_URL))
def get_video_links(self):
    xpath = '/html/body/ytd-app/div/ytd-page-manager/ytd-browse/ytd-two-column-browse-results-renderer/div[1]/ytd-section-list-renderer/div[2]/ytd-item-section-renderer/div[3]/ytd-grid-renderer/div[1]/ytd-grid-video-renderer/div[1]/div[1]/div[1]/h3/a'
    elements = self.driver.find_elements_by_xpath(xpath)
    last_result = 0
    curr_result = len(elements)
    while curr_result != last_result:
        self.driver.find_element_by_tag_name('body').send_keys(Keys.END)
        self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(3)
        elements = self.driver.find_elements_by_xpath(xpath)
        last_result = curr_result
        curr_result = len(elements)
    video_links = [elem.get_attribute('href') for elem in elements]
    return video_links

This currently returns 60 urls, while doing no scrolling gets me 30 urls. The channel I'm scraping, however, has around 150 videos. I have succeeded with manual scrolling, so I know the element-finding part works. I have tried this and this but they only get me 30 urls and I don't see any scrolling happening on the browser.

A: You can use JavaScript to scroll down in selenium.
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    Taken from the selenium docs.
If you just want to download all the videos a channel has made, youtube-dl is the better job.
All you have to do is run youtube-dl from the console and add the Channel ID for the channel you want downloaded.
$ youtube-dl "[INSERT CHANNEL-ID]"

It also works on playlists and individual videos and even supports other sites.

A: This issue may be happening because after loading 60 videos, the page needs to load more videos and because of which not able to return you the full no. of videos of channel.
You can do one thing, after 60 videos which have loaded you may again search the videos link after that.

A: This doesn't work any longer as document.body.scrollHeight is 0 now. Should use document.getElementById('page-manager').scrollHeight instead.


text: Q: How to write to a descriptor in Ionic Ble I am using the ionic ble library to communicate with a bluetooth device. Currently I am not seeing any function to write to a descriptor. Is this possible with this library?


text:
Q: ARIA label for menu widget not read UA: Mozilla Firefox 28.0;
AT: JAWS 14.0.1534 and NVDA 2014.1;
OS: MS Windows 7 Professional SP1
Given the following simple ARIA-enhanced menu widget, why is the associated 'Where to go' label never read? It's been my understanding that labels associated with focusable elements should be announced when focus is received. Instead, only the menu item's text is read.

First page

Second page

Third page

Is it some kind of "optimization" as to prevent excessive information to be read to the user everytime the menu received focus? Like, the contents of the "menuitem" would be prioritized over the labelling of the containing menu widget. Of course, this is just a wild guess. Does anybody have more details that could help clarify the above situation?
A related question based on the same code sample: I've found out that doing away with the containing div (the one with the role="application" attribute) changes absolutely nothing regarding the behavior of the widget (there's Javascript code for controlling keyboard interaction and updating the UL's aria-activedescendant attribute). When do you actually need a container with role="application"?

A: Based on the example, it doesn't look like something that should be a menu.
The menu role is intended for application style menus which pop-up sub-menus. See this menubar example.
Upon tabbing to the menu, you then use arrow keys to navigate, not tab.
What you've got (so far at least) is simple navigation, and on a website the most appropriate mechanism is standard links.

First page

Second page

Third page

The aria-label may or may not be read out by a screenreader (in a brief test NVDA did not, VoiceOver did), if that is important hide an off-screen heading above the menu. However, that label is used if the user navigates by "landmark".
If you do go for a full menu, I'd try the accessible Adobe mega-menu.


text:
Q: Close a browser window of an ASP.NET and AJAX application What is the best way to close a browser window of an AJAX ASP.NET application after the server-side has been executed.
I found this solution, but it seems a little complex for what I want to accomplish.  Or is this the best way to accomplish my task.
UPDATE: I have to close the window after the button is pressed
UPDATE 1: I tried the solution from the other SO question, and it did not work for me.
<asp:Button ID="btnMyButton" runat="server" onClick="btnMyButton_Click" />

protected void btnMyButton_Click(object sender, EventArgs e)
{
}

I used the following code in my page, but the "The webpage you are viewing is trying to close the windows" module window pops up.
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
            ScriptManager.RegisterStartupScript(upApproveRequest, typeof(string), "closeWindow", "window.close();", true);

Any way to prevent this?

A: Actually you can do this by placing the following code in your button click event.
protected void btnMyButton_Click(object sender, ImageClickEventArgs e)
{
    // Update database
    bool success = Presenter.DoDatabaseStuff();

    if (success)
    {
        // Close window after success
        const string javaScript = "<script language=javascript>window.top.close();</script>";
        if (!ClientScript.IsStartupScriptRegistered("CloseMyWindow"))
        {
            ClientScript.RegisterStartupScript(GetType(),"CloseMyWindow", javaScript);
        }
    }
    else
    {
        // Display failure result
        result_msg_area.Visible = true;
        lblError.Text = "An error occurred!";
    }
}

A: No, there is no way to close a browser window without the user's consent. You can log them out of their application, but you can't forcibly close the browser window.

A: To avoid the script warning, you can use this:
window.open('', '_self', '');window.close();

So:
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
        ScriptManager.RegisterStartupScript(upApproveRequest, typeof(string), "closeWindow", "window.open('', '_self', '');window.close();", true);

A: That's pretty much it. You can just use ScriptManager.RegisterStartupScript(...)


text:
Q: Chrome appending -- to end of filename string fileName = "test.txt";
byte[] docBytes = getDocumentBytes();

return File(docBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);

This returns a file called "test.txt" on Firefox and Edge, however on Chrome it returns a file called "test.txt--".
Does anyone know why it behaves in this manner? Is there a way to fix this in the code?

A: Well this was hard to find out.
Chrome converts whitespace at the end of the filename into '-'.
 return File(docBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName.Trim());

The trim fixes this problem.


text:
Q: The derivative of a linear operator with respect to its argument How can one differentiate an expression involving a linear operator with respect to the argument. I never met something like this yet.
Assume $\mathcal{A}\colon \mathbb{R}^{n} \to \mathbb{R}^{p\times q}$ is a linear operator defined on $n$-dimensional real vectors. An example of this can be the Hankel operator. Given $g = [g1 \dots g5]^T$, The Hankel operator $\mathcal{H}$ takes $g$ as its argument and returns $\mathcal{H}(g)=\begin{bmatrix} g1 &g2&g3\\g2&g3&g4\\g3&g4&g5  \end{bmatrix}$. One might be interested in the operator $\mathcal{A}(g) = W_1\mathcal{H}(g)W_2$ for any constant matrices $W_1$ and $W_2$ with compatible dimensions.
How can we differentiate a scalar function of $g$ involving $\mathcal{A}$?
Here is an example: $\operatorname{trace}(\mathcal{A}(g)^T\mathcal{A}(g)) + q^Tg$.
If we want to minimize this functional by deciding the value of $g$, for a given linear operator $\mathcal{A}$ and a constant vector $q \in \mathbb{R}^n$, one would like to set the derivative to $0$.
I came across this in the literature:
Given a vector $a$ and constant matrices $Z$, $H$ and $X$, consider the scalar function $\frac{1}{2}(g-a)^T H (g-a) + \text{trace}(Z^T (\mathcal{A}(g)-X)) +\frac{\rho}{2}\|\mathcal{A}(g)-X\|_F^2$ as a function of $g$. The norm is the Frobenius norm. To minimize with respect to $g$ the author says that we should set the derivative with respect to $g$ to $0$ to get
$(H+\rho M)g^* = \mathcal{A}_{\text{adj}}(\rho X -Z) + Ha$
in which $M$ is a positive semidefinite matrix given by the solution of
$Mz = \mathcal{A}_{\text{adj}}(\mathcal{A}(z)) \;\;\forall z\in\mathbb{R}^n$
I do not know how to come about showing this. I don't see where the adjoint comes from.

A: Consider the matrix version of the problem where $g \in {\mathbb R}^{n\times m}$, and after finding a solution, the vector problem can be recovered by setting $m=1$.
Let $T \in {\mathbb R}^{p\times q\times n\times m}$, and define the following quantities
$$ \eqalign {
 A  &= T:g \cr
 b &= g-a \cr
 C &= A-X \cr
 S &= {\rm sym}(H) \equiv \frac {1}{2}(H+H') \cr
} $$
Now the function that you saw in the literature can be written as
$$ \eqalign {
 f &= {\frac {1}{2}}H:bb' + Z:C + {\frac {\rho}{2}}C:C \cr
} $$
The differential of the function is
$$ \eqalign {
 df &= H:{\rm sym}(db\,b') + Z:dC + \rho C:dC \cr
    &= {\rm sym}(H):db\,b' + (\rho C + Z):dC \cr
    &= Sb:db + (\rho C + Z):dA \cr
    &= S(g-a):dg + (\rho A -\rho X + Z):dA \cr
    &= S(g-a):dg + (\rho A -\rho X + Z):T:dg \cr
    &= (Sg-Sa + \rho A:T -\rho X:T + Z:T):dg \cr
} $$
So the derivative is
$$ \eqalign {
 \frac {\partial f}{\partial g} &= Sg - Sa + \rho A:T -\rho X:T + Z:T \cr
  &= Sg - Sa + \rho T':T:g -\rho X:T + Z:T \cr
} $$
Setting the derivative to zero yields
$$ \eqalign {
 Sg + \rho T':T:g &= Sa + (\rho X-Z):T \cr
} $$
Now is a good time to set $m=1$ so that $T$ becomes a third-order tensor and we need to solve this equation for the vector $g$
$$ \eqalign {
 (S + \rho T':T)g &= Sa + (\rho X-Z):T \cr
} $$
Letting $M=T':T$ and assuming $H$ is symmetric so that $S=H$, one obtains
$$ \eqalign {
 (H + \rho M)g &= T':(\rho X-Z) + Ha \cr
} $$
which is as close as I can get to the literature that you've cited.
NB:  The transpose operation for the third order tensor is such that
$Z:T = T':Z$ or in index notation $Z_{ij}T_{ijk} = {T'}_{kij}Z_{ij}$, which means ${T'}_{kij}=T_{ijk}$


text:
Q: FOSRestBundle json decode issue Using FOSRestbundle, trying to insert data into table using POST and content-type as application/json. My config.yml has the following
fos_rest:
  param_fetcher_listener: true
  body_listener: true
  format_listener:
    default_priorities: ['json', html, '*/*']
    prefer_extension: true
  view:
    view_response_listener: force
    failed_validation: HTTP_BAD_REQUEST
    default_engine: php
  formats:
    json: true

In controller added something like this
$request= $this->getRequest();
$form->bindRequest($request);
$em = $this->get('doctrine')->getEntityManager();
$em->persist($entity);
$em->flush();

But getting null values for all the DB fields.  Any idea?

A: FOSRestBundle's Body Listener already json decodes the request content and stores it in the Request parameter bag. You can access the json decoded array using
$request->request->all()
public function postFooAction(Request $request)
{
    if (!$request->getFormat($request->headers->get('Content-Type')) == 'json') {
        throw new BadRequestHttpException("Invalid Content-Type Headers");
    }
    $data = $request->request->all(); // FOSRestBundle's BodyListener sets the Request Parameter Bag to the json decoded data already

    return true;
}

A: Though it's Silex tailored, this should fix your problem:
use Symfony\Component\HttpFoundation\Request;

...

if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
    $data = json_decode($request->getContent(), true);
    $request->request->replace(is_array($data) ? $data : array());
}

A: Formtype getName method was returning formtype name,  changed that to table name. Its working now.  Thanks.


text:
Q: Is it possible to transfer data from Oracle to Teradata or vice-versa using JDBC? I am working on tool to transfer data from Oracle to Teradata and was thinking of using java-JDBC for that but when i looked over internet i could not find anything related to it but what i did find was that the data needs to be transformed before it can be moved to different RDBMS hence i just want to know if it is possible at all and if yes then some help would be appreciated.

A: Both, Oracle and Teradata databases, support JDBC.
So, if your question is if you can move data from one database to another developing your own tool, yes you can.
But, there are many third party tools that could be used to Extract Transform and Load (ETL) data from one JDBC compliant database to another.
You could start analysing the which data you have to move and making some tests using Oracle SQL Developer. It has support to connect to Teradata as well (not only Oracle). And even not being a "pure" ETL tool, I think it could be a good starting point:
http://www.oracle.com/technetwork/database/migration/jdbc-migration-1923524.html

A: It depends. The Teradata JDBC driver has support for the FastLoad API which affords you some bulk loading advantages over a straight row-by-row operation. It is not as effective as using Teradata's Parallel Transporter or FastLoad utility but it won't upset your DBA's nearly as much as doing singleton inserts for large data volumes. FastLoad will support loading an empty table.
As Peter mentioned, a proper ETL process may be more appropriate especially if the data volumes are significant or this is a repeatable process. Teradata's Parallel Transporter offers you a variety of load operators depending on the data volume and target you are loading in Teradata. (i.e. low volume vs high volume, empty vs populated target table, etc.)


text:
Q: Parallelize Functions in Numpy I have a function ComparePatchMany written in numpy, which does some basic matrix functions (dot product, diagonal, etc), and due to the size of matrices I'm using, is too slow. In order to achieve some speedup, I want to run calls to this function in parallel. Because of memory issues, I can't seem to call this on any more than 100 stacked matrices at a time. So simply running ComparePatchMany on a giant matrix is out (though it works in MatLab).
What I have right now is:
def comparePatchManyRunner(tex_flat,imMask_flat,s_tex,metrics,i):
    metrics[i] = ComparePatchMany.main(tex_flat[imMask_flat==1,:],np.reshape(s_tex[:,i],(-1,1)))

# N = 100
def main(TexLib,tex,OperationMask,N,gpu=0):

    if gpu:
        print 'ERROR: GPU Capability not set'
    else:
        tex_flat = np.array([tex.flatten('F')]).T

    CreateGrid = np.ones((TexLib.Gr.l_y.shape[1],TexLib.Gr.l_x.shape[1]))
    PatchMap = np.nan*CreateGrid
    MetricMap = np.nan*CreateGrid
    list_of_patches = np.argwhere(CreateGrid>0)

    for i in range(list_of_patches.shape[0]):
        y,x = list_of_patches[i]
        imMask = TexLib.obtainMask(y,x)
        Box = [TexLib.Gr.l_x[0,x],TexLib.Gr.l_x[-1,x],TexLib.Gr.l_y[0,y],TexLib.Gr.l_y[-1,y]]

        imMaskO = imMask
        imMask = imMask & OperationMask

        imMask_flat = np.dstack((imMask,imMask,imMask))

        if gpu:
            print 'ERROR! GPU Capability not yet implemented'
            # TODO
        else:
            imMask_flat = imMask_flat.flatten('F')

        if np.sum(imMask)<8:
            continue

        indd_s = np.random.randint(TexLib.NumTexs,size=(1,N*5))

        s_tex = TexLib.ImW[imMask_flat==1][:,np.squeeze(indd_s)]
        s_tex = s_tex.astype('float32')

        if gpu:
            print 'ERROR! GPU Capability not yet implemented'
            # TODO
        else:
            metrics = np.zeros((N*5,1))
            shared_arr = multiprocessing.Array('d',metrics)

            processes = [multiprocessing.Process(target=comparePatchManyRunner, args=(tex_flat,imMask_flat,s_tex,shared_arr,i)) for i in xrange(N*5)]
            for p in processes:
                p.start()
            for p in processes:
                p.join()
            metrics = shared_arr
            print metrics

I think this may be creating 500 processes, which could be an issue. One problem I keep running into with this and previous versions is IOError: [Errno 32] Broken pipe, which originates from p.start().
I'm working on Windows with Python 2.7, NumPy 1.8, and SciPy 0.13.2.
EDIT:
Comments suggested I use pools. So I'm trying this:
metrics = np.zeros((N*5,1))
shared_arr = multiprocessing.Array('d',metrics,lock=False)
po = multiprocessing.Pool(processes=2)
po.map_async(comparePatchManyRunner,((tex_flat,imMask_flat,s_tex,shared_arr,idex) for idex in xrange(N*5)))

But it doesn't seem to be writing anything to shared_arr, and I keep getting a PicklingError:
Exception in thread Thread-29:
Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
    self.run()
  File "C:\Python27\lib\threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "C:\Python27\lib\multiprocessing\pool.py", line 342, in _handle_tasks
    put(task)
PicklingError: Can't pickle <class 'multiprocessing.sharedctypes.c_double_Array_500'>: attribute lookup multiprocessing.sharedctypes.c_double_Array_500 failed


text:
Q: libev with two ev_timer 100%CPU utiluzed first,my english is very bad...
this is my code:
ev_timer_init(&m_netmsgpoptimer, netMsgTimer_cb, 10, 10.);
ev_timer_start(m_loop, &m_netmsgpoptimer);

m_mainlooptimer.data = (void*)this;
//
ev_timer_init(&m_mainlooptimer, mainloopTimer_cb, 20, 20.);
ev_timer_start(m_loop, &m_mainlooptimer);

ev_loop(m_loop, 0);

and this is perf said:
5504.368980 task-clock                #    0.999 CPUs utilized

the perf cpu-clock record like this:
+  30.08%  huhuGame  [kernel.kallsyms]  [k] mutex_lock                             ◆
+  29.40%  huhuGame  [kernel.kallsyms]  [k] memcpy                                 ▒
+   4.75%  huhuGame  [kernel.kallsyms]  [k] system_call_after_swapgs               ▒

if i changed my code line "ev_loop(m_loop, 0)" to this:
    timespec  _tstart, _tend;
while(!m_bExit)
{
    clock_gettime(CLOCK_REALTIME, &_tstart);
    ev_loop(m_loop, EVLOOP_ONESHOT);
    clock_gettime(CLOCK_REALTIME, &_tend);
    long long  t1, t2;
    t1 =   _tstart.tv_sec*10000+_tstart.tv_nsec/100000;
    t2 =  _tend.tv_sec*10000 + _tend.tv_nsec/100000;
    t1 =  (t2 - t1)*10;
    if(t1 < 100)
        usleep(100-t1);
}

cpu utiluze is low..
and why ev_loop(m_loop,0) with ev_time will cost 100% cpu performance?
any answer is helpful,thanks!


text:
Q: How can I make list-in-list sentence by sentence out of pandas dataframe? I currently 'pd.read_csv'-ed and got something like this:
  sent_id  word      pos_tag
0  1        Stack     noun
1  1        overflow  noun
2  1        is        verb
3  1        great     adjective
4  2        Luv       verb
5  2        you       pronoun
6  2        guys      noun
7  3        Thank     verb
8  3        you       pronoun

I want to return things like these:
[[Stack, overflow, is, great], [Luv, you, guys], [Thank, you], ...]
[[(Stack, noun), (overflow, noun), (is, verb), (great, adjective)], ...]

Please help me, thank you.


text:
Q: Add datetime difference to a duplicate selection The below sql gives me a list of CustomerID and FeeRuleID where there are duplicated records. The problem is, that I need to make sure the output of this is only "true" duplicates - those created within one second of each other.
How do I add the requirement in of Having count()>1 AND cfr.ModifiedOn difference <1 second?
select cfr.CustomerID, cfr.FeeRuleID
FROM CustomerFeeRule cfr
       inner join FeeRule fr on cfr.FeeRuleID = fr.FeeRuleID
       inner join FeeType ft on fr.FeeTypeID = ft.FeeTypeID
where GetDate() BETWEEN cfr.DateEffective and cfr.DateTerminated
group by cfr.CustomerID, cfr.FeeRuleID
having count(cfr.CustomerID)>1
Order by cfr.CustomerID, cfr.FeeRuleID

DateEffective is in the format date
ModifiedOn is in the format datetime


text:
Q: Is there a reason to use Scheme over JavaScript? As far as I know, JavaScript can be used to do everything that is possible in Scheme.
Every functional programming paradigm I've learnt in Scheme is doable in JavaScript.
I know that one may end up using JavaScript to write ungood code (ones with global variables, too many states and side effects) where as Scheme restricts one to write functional code.
But apart from that, is it really necessary to use Scheme anywhere over JavaScript?
For those of you who say JavaScript can be interpreted only on a browser kindly draw the same question to Python and Scheme.

A: Let me pose a similar question:
Is there a reason to use French over English? Anything that you can express in French you can express in English, so is it really necessary to use French over English? Kindly draw the same question to Russian, German, Spanish, or any other spoken language you choose.
No programming language is completely unique, anything you can do in one language can be done in a different language, some implementations might require a bit more creative thought but it can still be done.
Some reasons to use Scheme instead of JavaScript or Python:

*

*You appreciate the simplistic and minimalist structure of the
language

*Ease of implementation when compared to expressive power    (lambda
expressions)

*You are more familiar with Scheme

*The client has    existing code in Scheme

Specific implementations or algorithms might have a min/max calculation available to give exact benchmarks, but you would have to look at specific algorithms. In general there is no way to define one language as always better in all situations (or even 'never worse'), and trying to pigeon hole oneself into a single language is dangerous. In my opinion, open mindedness is one of the biggest strengths a programmer can have. Being able and willing to use different languages or techniques can be a powerful tool.
I personally suggest further reading by looking up Polyglot Programming. It isn't directly related to your question, but it is a mentality that speaks to the benefits of knowing and using a variety of languages.


text:
Q: Disable the line limit wrap when Code Format is selected Recently I set my line length limit to 100 or 120 and I also enabled an option that will wrap the code that exceeded those limits to the next line, whenever I clicked Code Format.
Now I want to disable that wrap and do it manually, but I don't know where that setting was.

A: In Android studio go to

Preferences > Editor > Code Style > Java > Wrapping and Braces > Keep
  when reformatting and uncheck the checkbox Line Breaks

A: Go to File->Settings->Editor->Code Style
There you'll find the two options "Right margin (columns)" and "Wrap when typing reaches right margin".


text:
Q: How to make a reminder window on mac I want to make an clock app on mac, when the time is pressing, I want to show a reminder windows on the screen, how can I do this? Thank you very much.

A: What about starting with a simple message box?
NSString *caption = @"Reminder";
NSString *text = @"Alarm!";
NSAlert* x = [[NSAlert alloc] init];
[x setInformativeText: text];
[x setMessageText: caption];
[x addButtonWithTitle: @"OK"];
[x runModal];
[x release];


text:
Q: Installing grunt - did it install or not? I tried installing grunt with npm install grunt but I'm not clear if grunt installed or not:
$ npm install grunt
npm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated minimatch@0.3.0: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
npm WARN template@0.0.1 No repository field.
npm WARN template@0.0.1 No license field.

e.g.
$ grunt
-bash: grunt: command not found

A: You installed it locally in the directory that you run the install command.
You'll have to install it globally with the -g flag.
In the grunt web they recomend to install grunt-cli.
npm install -g grunt-cli
Depending on how you installed node you may want to add sudo to that command:
sudo npm install -g grunt-cli

A: When you run npm install, the package is placed in the nearest node_modules directory, travelling up the directory tree.
So, ./node_modules is the first candidate, ../node_modules gets checked next, ../../node_modules next and so on, until one is found.
To run a program installed in the nearest local node_modules, you can use npm bin, which resolves to the appropriate path:
$(npm bin)/grunt

This is the same as running (assuming node_modules in current working directory):
./node_modules/.bin/grunt

If you want to install grunt system-wide, and run it without any of this ceremony, run npm install -g
npm install -g grunt-cli
grunt # run without prefix

Note, however, that this enforces a single version of grunt across all of your projects, since they all share the same instance.

A: You can use the following command to see if grunt is installed:
npm list grunt

If you are installing your packages globally using install -g, then modify the command to use the -g flag:
npm list -g grunt

To see all top-level installed packages, use:
npm list --depth=0

Note that you can also use the -g flag for the above command as well.
Hope this helps!


text:
Q: Why is `purrr::flatten` so slow? Trying to flatten a list of matrices into single data.frame in R.
purrr:flatten would be an obvious choice but it is really slow.
In this simple example below flatten is ca. 50 times slower on RStudio Server and 10 times slower on R terminal than the alternative using reduce(full_join)!
Why is that?
Is there a way around it?
library(dplyr)
library(purrr)
library(tibble)
start_time = Sys.time()
rerun(10, as_tibble(matrix(rnorm(36),nrow=6))) %>%
  flatten_dfc() # alternatively map_dfc(., bind_cols)
end_time = Sys.time()
end_time - start_time # 9.2 sec

start_time = Sys.time()
rerun(10, rowid_to_column(as_tibble(matrix(rnorm(36),nrow=6)))) %>%
  reduce(full_join, by="rowid", suffix = c(".1", ".2"))
end_time = Sys.time()
end_time - start_time # 0.2 sec


text:
Q: Returning fields and count in the same sql I have a specific query i can't figure out how to get done.
I need to return the values of my articles table named Articulos, and count how many times each article is used on every budget.
i have a detail table called pre_detalle which contains a field called idart, where the articulos.id are written in case of being included.
i need each counter to be returned as cont_num.
this is the query i tried to develop:
SELECT *, COUNT(articulos.id) as cont_num
FROM articulos
WHERE articulos.id IN(SELECT idart FROM pre_detalle)
GROUP BY articulos.id
ORDER BY cont_num

A: In most cases, you need to count a list of item that you display.
In most cases, you will use a pagination system to display your rows of data.
In most cases, if you try to do it with the same query, it will simply fail.
So, maybe you should get in mind to do it using one query to count the rows and another one to get the rows you want.
In most cases, this answer could help you (in a proper way).

A: this is what i needed to do, a couple hours later and after lots of tries i managed to get it working.
SELECT articulos., (SELECT COUNT() FROM pre_detalle WHERE pre_detalle.idart = articulos.id) AS cont_num FROM articulos


text:
Q: Evaluate a local variable inside a Julia macro I'm writing a Julia macro that takes an expression and serializes it, so that I can run it somewhere else. The macro therefore takes the expression and replaces all symbols with variables. The expression is then serialized and evaluated somewhere else.
My problem is related to evaluating variables that are not in the global scope. I.e. the following works fine, as a is defined in the global scope:
macro myprintf(ex)
    print(eval(ex))
end

# works
a = 2
@myprintf a

This throws an error as the macro doesn't see a, which is defined in the local scope of the loop (run in a new session):
macro myprintf(ex)
    print(eval(ex))
end

# UndefVarError: a not defined
for j=1:3
    a = 2
    @myprintf a
end

Is there any way I can access a inside the macro if it is defined in a local scope such as a loop? I'm aware that I'm not necessarily using macros as intended as I am calling eval on the expression inside the macro definition. The overall idea is that I want to serialize the expression that's passed to the macro and evaluate it somewhere else later (e.g. in a different Julia session).

A: eval only works in global scope.  But then I don't see how much use there is in replacing the variables by evaluated literals, resulting in an expression of literals.
Anyway, a different approach to the original problem could be mimick what R does: constructing thunks out of an expression plus its environment at the place where it was called.  To recreate that in Julia, you'd have to

*

*Figure out the free variables in the expression

*Create an environment data structure of their values

*Wrap the original expression in a closure such that it takes the local variables from the environment

*Put everything into a new object

Example:
for j=1:3
    a = 2
    @saveexpr a + 2
end

should expand to something like
for j=1:3
    a = 2
    SerializedExpr(
      (; a),
      function (env)
          let (a,) = env
              a + 2
          end
      end,
      :(a + 2))
end

If saving the closure is not feasible in your use case, I guess you have to either implement your own evaluator, or use something like JuliaInterpreter.jl.