text:
Q: C# Looping through a CSV file/API call I'm writing a console app that will look through three different folders (PathA, PathB, PathC) for csv files and email the customers inside. I need some help with the logic. For each email address in PathA, I want to call the api to send an email with TemplateA. For each email address in PathB, it needs TemplateB and so on. I'm not sure how I should be referencing each path and each template.
    static void RunTask(string[] args)
    {

       // List<DM.SendEmailRequest> response = GetEmailRequest();
        List<PathElement> paths = PathsConfig.GetCurrentPathConfiguration();
        foreach (PathElement folder in paths)//looks at every folder within main folder
        {
            foreach (string file in Directory.EnumerateFiles(folder.Path, "*.csv"))//looks at every file with the extension ".csv" in each folder
            {
                Debug.Write("\n" + file + "\n"); //writes out file names
                using (StreamReader sr = new StreamReader(file))
                {
                    String line;

                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] parts = line.Split(',');

                        string email = parts[1];
                        Debug.Write(email + "\n");//writes out email column
                        foreach (var customer in email)
                        {
                            if (PathA){ //how do I actually reference this path?
                                //call API and send TemplateA
                        }
                            else if (PathB)
                            {
                                //call API and send TemplateB
                            }
                            else
                            {
                                //call API and send TempateC
                            }
                    }

                    }
                }

            }
        }

    }

    private static List<DM.SendEmailRequest> GetEmailRequest()
    {
        using (var httpClient = GetHttpClient())
        {
            DM.SendEmailRequest request = new DM.SendEmailRequest();
            request.TemplateId = //A, B or C;
            request.RecipientAddress = //current recipient;

            var response = GetResponseString(httpClient, "SendEmail", new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"));

            return string.IsNullOrWhiteSpace(response) ? default(List<DM.SendEmailRequest>) : JsonConvert.DeserializeObject<List<DM.SendEmailRequest>>(response);
        }
    }

A: Here is everything i would put inside the Using {}
using (StreamReader sr = new StreamReader(file))
{
    String line;
    List<string> myEmailList = new List<string>();

    while ((line = sr.ReadLine()) != null)
    {
        string[] parts = line.Split(',');
        string email = parts[1];
        Debug.Write(email + "\n");//writes out email column
        myEmailList.Add(email);
    }
    foreach (var customer in myEmailList)
    {
        if (folder.path.Contains("first")){
             //Do stuff with "Customer"
             //call API and send TemplateA
        }
        else if(folder.path.Contains("second"))
        {
             //Do stuff with "Customer"
             //call API and send TemplateB
        }
        else
        {
             //Do stuff with "Customer"
             //call API and send TempateC
        }
    }
}

Alternativly,  you can do it like below
using (StreamReader sr = new StreamReader(file))
{
    String line;

    while ((line = sr.ReadLine()) != null)
    {
        string[] parts = line.Split(',');
        string email = parts[1];
        Debug.Write(email + "\n");//writes out email column
        if (folder.path.Contains("first")){
             //Do stuff with "email"
             //call API and send TemplateA
        }
        else if(folder.path.Contains("second"))
        {
             //Do stuff with "email"
             //call API and send TemplateB
        }
        else
        {
             //Do stuff with "email"
            //call API and send TempateC
        }
    }
}

Option 1 will read through the entire file,  collect ALL email addresses in all CSV's in that folder and build a list of them,  then iterate through that list sending emails after it's finished reading all the files (i would recommend this one,  as it would allow you to get the full list, check for duplicates (if needed) etc before you send all the emails)
Option 2 will send an email to the customer in the current line before it proceeds to the next line of the file.

A: It seems to me that you need to do something like this:
static void RunTask(string[] args)
{
    var templates = new Dictionary<string, string>()
    {
        { "C:\\test\\first", "A" },
        { "C:\\test\\second", "B" },
        { "C:\\test\\third", "C" },
    };

    List<PathElement> paths = PathsConfig.GetCurrentPathConfiguration();
    foreach (PathElement folder in paths)//looks at every folder within main folder
    {
        foreach (string file in Directory.EnumerateFiles(folder.Path, "*.csv"))//looks at every file with the extension ".csv" in each folder
        {
            Debug.Write("\n" + file + "\n"); //writes out file names
            using (StreamReader sr = new StreamReader(file))
            {
                String line;
                while ((line = sr.ReadLine()) != null)
                {
                    string[] parts = line.Split(',');
                    string email = parts[1];
                    Debug.Write(email + "\n");//writes out email column
                    GetEmailRequest(templates[folder.Path], email);
                }
            }

        }
    }
}

private static List<DM.SendEmailRequest> GetEmailRequest(string templateId, string recipientAddress)
{
    using (var httpClient = GetHttpClient())
    {
        DM.SendEmailRequest request = new DM.SendEmailRequest();
        request.TemplateId = templateId
        request.RecipientAddress = recipientAddress

        var response = GetResponseString(httpClient, "SendEmail", new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"));

        return string.IsNullOrWhiteSpace(response) ? default(List<DM.SendEmailRequest>) : JsonConvert.DeserializeObject<List<DM.SendEmailRequest>>(response);
    }
}

I also think you could get your RunTask method down to this:
static void RunTask(string[] args)
{
    var templates = new Dictionary<string, string>()
    {
        { "C:\\test\\first", "A" },
        { "C:\\test\\second", "B" },
        { "C:\\test\\third", "C" },
    };

    var responses =
    (
        from folder in PathsConfig.GetCurrentPathConfiguration()
        from file in Directory.EnumerateFiles(folder.Path, "*.csv")
        from line in File.ReadLines(file)
        let email = line.Split(',')[1]
        select GetEmailRequest(templates[folder.Path], email)
    ).ToArray();
}


text:
Q: Will a 2.5" SSD fit in my Toshiba Portege R830? I have a Toshiba Portege R830 - X3310.
Unfortunately my HDD gave up and I am thinking of switching to a SSD. Does any one have any idea if a Corsair Force GS will fit? The SSD is a 2.5" disk.
I tried searching but was not able to find any information on the dimensions of the HDD used in the laptop.
The Model No. for the Corsair SSD is CSSD-F240GBGS-BK.
The confusion is about some claims on a proprietary connector. I currently have a standard spinning 500GB HDD.

A: There's two standard sizes for 2.5 inch hard drives these days. Smaller/Thinner notebooks like ultrabooks systems use 7mm drives and the 'standard' for quite a while has been 9 inch. You should be able to fit a 7 mm drive in a 'larger' bay with no problem but not vice versa.
Looking up the drive model indicates that crucial's upgrade advisor suggests that the m4 works, and thats a 9.5mm drive and the drive on the Toshiba service video looks standard as well. The cosair force is also 9.5mm, so there should be no issues here

A: Any 2.5" ssd or hdd should work in your portege.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Matrix smoothly parametrized by t has eigenvalues (0, $\lambda$), eigenvector $v$. Is $\lambda v$ smooth? Let $C(t)$ be a symmetric, two-by-two real matrix whose entries are smooth functions of $t \in \mathbb{R}$. Suppose that $C(t)$ point-wise has eigenvalues $\lambda$ and $0$. Then $\lambda(t)$ is a smooth function too (since $\lambda(t)$ is the trace of $C(t)$). However, in general the unit-length eigenvector $v(t)$ corresponding to $\lambda(t)$ is not smooth. The problematic points are wherever $\lambda(t) = 0$ where $v(t)$ is not even well-defined even up to sign.
Is $\lambda(t) v(t)$ a smooth vector field?
Since $v(t)$ is only ever defined up to sign, I really mean to ask whether there is a smooth vector field of length $\left|\lambda(t)\right|$ that is point-wise an eigenvector of $C(t)$ of eigenvalue $\lambda(t)$.
Dieci and Eirola, 1999 Theorem 3.3 implies that if $\lambda(t)$ never goes to zero to infinite order, then $v(t)$ is in fact smooth. So we are interested in the case when $\lambda(t)$ goes to zero to infinite order and are hoping that $\lambda(t)$ then goes to zero fast enough to kill off any problems occurring in $v(t)$.

A: $\newcommand{\la}{\lambda}
\newcommand{\R}{\mathbb{R}}$Such a smooth field $(\la(t)v(t))$ does not exist in general.
Indeed, let
$$C=\begin{bmatrix}f&fg\\fg&fg^2\end{bmatrix},$$
where $f$ and $g$ are the (nonnegative) functions defined in this answer.
The eigenvalues of $C$ are $\la:=f+fg^2$ and $0$.
The eigenvectors of $C$ belonging to the eigenvalue $\la$ that are of length $|\la|[=\la]$ are of the form $w:=hf\sqrt{1+g^2}\,(1,-g)$ for some function $h\colon\R\to\{-1,1\}$. As detailed in the mentioned answer, the first coordinate $hf\sqrt{1+g^2}$ of this vector field $w$ cannot be smooth for any choice of a $\pm$-function $h$. Therefore, the vector field $w$ cannot be smooth for any choice of $h$.


text:
Q: Need to remove Minutes from Date $date = new DateTime("now", new DateTimeZone('Europe/Berlin') );
$dateUpdate = $date->format("d.m.Y H:i:s");

Hey, i need to subtract 4 Minutes from $dateUpdate.
How is this possible?
Thanks

A: You can do it this way :
$date = new DateTime("now", new DateTimeZone('Europe/Berlin'));
$interval = new DateInterval("PT4M");
$date->sub($interval);
echo $date->format('Y-m-d\TH:i:s.u');

DateTime Documentation
DateInterval Documentation


text:
Q: Help with the Integral of $x \arcsin x\,dx$ So I've started the integration using integration by parts, but I'm stuck on the second part of it.
$$ \int_0^\frac{1}{2} x \sin^{-1}x dx $$

*

*Step 1. Set up my variables
       $$ u = \arcsin x $$
       $$du = \frac{1}{\sqrt{1-x^{2}}} dx $$
       $$ dv = x dx $$
       $$ v = \frac{x^{2}}{2} $$

*Step 2. $uv - \int v\,du$
      $$ \frac{x^2}{2} \arcsin x   - \frac{1}{2} \int x^{2}\frac{1}{\sqrt{1-x^{2}}}$$

*Step 3. Now I need to integrate $ \frac{x^2}{\sqrt{1-x^2}} $
This is where I'm stuck. Do I do a trig sub? Let $x = \sin\theta$ which $1-\sin^2\theta$ would then equal $\sqrt{\cos^2\theta}$ turning the second part into $\int \sec \theta$?
Edit. Attempting to continue the problem with the suggestions provided.

*

*Step 3 (continued). $$ \frac{-1}{2} \int \frac{x^2}{\sqrt{1-x^2}}dx $$
$$ \text{Let }x = \sin \theta $$
$$ -\frac{1}{2} \int \frac{\sin^2\theta \cos\theta}{\sqrt{1-\sin^2\theta}} $$
$$ -\frac{1}{2} \int \frac{\sin^2\theta \cos\theta}{\sqrt{\cos^2\theta}} $$
$$ -\frac{1}{2} \int \frac{\sin^2\theta \cos\theta}{\cos\theta} $$
$$ -\frac{1}{2} \int \sin^2\theta  $$
$$ -\frac{1}{2} \int \frac{1 - \cos2\theta}{2} $$
$$ -\frac{1}{4} [\theta-\sin\theta \cos\theta] $$

*Step 4. Find what $\theta$ is equal to in terms of x.
Since we let $x = \sin\theta$, that would mean we have $$x^2 + b^2 = 1^2$$
So, does that mean I substitute $$ 1 - x$$ in for $\theta$?

A: If you want to continue with step (3), then you can use integration by parts again with $u=x$
$$ \int \frac{x^2}{\sqrt{1-x^2}} dx = -x\sqrt {-{x}^{2}+1}+\int \!\sqrt {1-{x}^{2}}{dx}.$$
For the last integral, you can use the trig. subs $x=\sin(\theta)$.


text:
Q: Get wrong URL ending I'd like to be able to track what my website visitors do wrong when they enter a faulty URL on my website. I'd like the end string to be uploaded into my database, for example:
Correct URL: https://www.example.com/example
Wrong URL entered: https://www.example.com/exmaple
I know how to get the URL ending from an existing part of the site and upload it to my database, but how do I get the erroneous URL ending (exmaple in this case) from a part of the site that doesn't exist in a usable format for the purpose (stored in a PHP variable for instance)?

A: All the information about what your clients have asked for is in the server access log.
For Debian/Ubuntu flavours of Linux these log files are in /var/log/apache2. The location may vary in other flavours of Linux, and Windows will differ too.
Here's a sample from Apache 2.4 for an absent file called fred. I've highlighted the 404 response code

192.168.237.28 - - [24/Jan/2021:09:57:56 +1300] "GET /fred HTTP/1.1" 404 497 "-"
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:85.0) Gecko/20100101 Firefox/85.0
"

Read the file, search for the statuses you want, add the data to a database, print a report, whatever.


text:
Q: C# Code Coverage not being imported into SonarQube 5.1.2 using MSBuild Runner 1 We've recently updated the C# plugin for SonarQube after which we had to use the MSBuild Runner v1. Since the update Code Coverage is no longer imported into sonrqube.
TFS2013 Build generates the codecoverage report which is picked up by the MSBuild runner and is converted (as seen below in the diagnostic view of the build).
"Run optional script after Test Runner"
11:09:43 AM Attempting to locate the CodeCoverage.exe tool...
11:09:43 AM Code coverage command line tool: C:\Program Files (x86)\Microsoft Visual Studio 12.0\Team Tools\Dynamic Code Coverage Tools\CodeCoverage.exe
11:09:43 AM Fetching code coverage report information from TFS...
11:09:43 AM Connecting to TFS...
11:09:43 AM Fetching build information...
11:09:43 AM Fetch code coverage report info...
11:09:43 AM Commencing retry-able operation. Max wait (milliseconds): 20000, pause between tries (milliseconds): 2000
11:09:43 AM Operation succeeded. Elapsed time (ms): 18
11:09:43 AM Coverage Id: 2623, Platform Any CPU, Flavor Any CPU
11:09:43 AM ...done.
11:09:43 AM The directory already exists: ***\.sonarqube\out
11:09:43 AM Connected to http://tfs***/tfs/***
11:09:43 AM Downloading coverage file from http://tfs***/tfs/**** ***\.sonarqube\out\VSCodeCoverageReport.coverage
11:09:50 AM Executing file C:\Program Files (x86)\Microsoft Visual Studio 12.0\Team Tools\Dynamic Code Coverage Tools\CodeCoverage.exe
Args: analyze /output:"***\.sonarqube\out\VSCodeCoverageReport.coveragexml" "***\.sonarqube\out\VSCodeCoverageReport.coverage"
Working directory: ***\.sonarqube\out
Timeout (ms):30000
Process id: 5420
11:09:50 AM Process returned exit code 0
11:09:50 AM Updating project info files with code coverage information...

We are using VS 2013, TFS 2013, Sonarqube 5.1.2, MSBuild runner 1
CodeCoverage was working before upgrading to C# plugin 4.1 and using the MSBuild Runner. Any help getting the code coverage to work would be great.

A: Apologies for not replying sooner, I think we aren't looking at the "sonarqube5.1" tag specifically, but at the "sonarqube" tag.
There are a few things we could check, so first:
You say you upgraded to MSBuild Runner v1.0. What did you upgrade from? Were you using MSBuild Runner v0.9 or the Visual Studio Bootstrapper? For the 0.9 -> 1.0 we have documented the upgrade process - did you follow these steps?

A: With msbuild sonarqube runner 1.0.1 I had trouble getting opencover reports imported where it used to work before. It turns out I had to make sure the sonar.cs.opencover.reportsPaths argument uses absolute paths to the reports, because the working directory is different from when I ran sonar-runner.bat directly before.


text:
Q: Guessing a non-recursive formula for a mathematical sequence I am stuck on a question, I'm not sure if I'm going about it correctly.
The question: Suppose $a_0, a_1, a_2, \ldots$ is a sequence such that $a_0 = a_1 = 1$ and, for $n \ge 2$, $a_{n+1} = n(a_n +  a_{n-1})$.
For the sequence I determined that:
$a_0 =  1, a_1 = 1, a_2 = 2, a_3 = 6, a_4 = 24$ and $a_5 = 120$.
I am trying to guess the non-recursive formula for this problem, but I am lost.
I know it should be easy, but is there a method or strategy that I should use to narrow down my formula or is it complete guesswork?

A: We will prove that $a_k=k!$ by induction.
$k=0$ and $k=1$ - the formula is true, you already checked it.
Assume $a_{n-1}=(n-1)!$ and $a_n=n!$.
Then
$$a_{n+1}=n(a_{n-1}+a_n)=n((n-1)!+n!)=n\cdot(n-1)!(1+n)=n!(n+1)=(n+1)!$$
so, by induction, $a_n=n!$ for all $n$.

A: Similar to larry01's answer, but I prove $$a_n=n\cdot a_{n-1}$$ by induction
For $n=1$ and $n=2$, the claim is true.
Suppose, the claim is true for $n$ and $n+1$
We have $$a_{n+2}=(n+1)(a_{n+1}+a_n)=(n+1)((n+1)a_n+a_n)=(n+2)(n+1)a_n=(n+2)a_{n+1}$$
Using the recurrence relation $a_1=1$ , $a_n=n\cdot a_{n-1}$ it is easy to guess that $a_n=n!$

A: Write the recurrence as $a_{n+1} - (n+1) \,a_n= -(a_n -  n\,a_{n-1})\,$. Applying repeatedly:
$$a_{n+1} - (n+1) a_n= -(a_n -  na_{n-1})=(-1)^2(a_{n-1} -  (n-1)a_{n-2})=\cdots =(-1)^n (a_1 - 1 \cdot a_0)$$
But the RHS is $0$ because $a_0=a_1=1\,$, therefore $a_{n+1}-(n+1)\,a_n=0\,$, so in the end $a_n=n!\,$.

[ EDIT ]   May be worth noting that the above $\,a_n=n  a_{n-1} + (-1)^{n-1} (a_1 - a_0)\,$ gives the general solution in terms of arbitrary $\,a_0,a_1\;$ as $\;a_n=n!\,\left(a_0 + (a_1-a_0)\,\sum_{k=1}^{n}\frac{(-1)^{k-1}}{k!}\right)\,$.


text:
Q: Git repos setup for multiple dependent projects I'm  looking for an advice how to manage source code between couple of projects where a subset of files (directory) should be shared between both.
Currently we have a single project A under one git repo. We are planing to port the app to anither runtime - project B. This would involve simply sharing www directory between both frameworks. So in abstract view the layout is as follows:
-----------             ------------
|    A    |             |    B     |
|---------|             |----------|
|   www   | <- shared-> |   www    |
-----------             ------------

Development primarily happens on A repo. We need ability to somehow to be able to merge any changes mage in www A to www B
It seems like we need 3 repos A, B and www where www would be nested within the other two. However I'm not sure whether nesting repositories is a best way to approach this. The other possibility there seems to exist is git submoduled but on the lack of personal experience I'm not sure if its a right solution for our setup.
Any ideas/suggestions are highly appreciated.

A: Yes, you can use Git Submodules to achieve this.
Setting up www as the submodule, located in a separate directory, then you can keep the subfolder www inside A and B is synced with the power of Git Submodules.


text:
Q: Which mathematical theory investigates distortions? For transformations like rotations, translations or boosts Lie theory is the appropriate theory. Which theory talks in similar, systematic terms about distortions
$$ M \vec{v} = m \vec{v} \quad \forall \ \vec{v} \quad ?$$
In Lie theory we can learn a lot about certain transformations/symmetries by looking at the corresponding Lie algebra and deriving representations of the transformations in question.
I'm searching for a similar treatment of distortions. Concretely this means looking at infinitesimal elements, deriving the corresponding algebra that encodes the information about the transformation and deriving systematically representations.
I wasn't able to find some "distortion group" and therefore I concluded there must be a good reason for this. Maybe we need here another framework. If it can be done using Lie theory, the correct name of the "distortion group" would help me immensely

A: You weren't able to find anything because "distortion" is not a term mathematicians use for scalar multiplication. (I object to the claim that scalar multiplication is a "distortion," anyway; compared to other things you could do to a vector space, scalar multiplication hardly distorts anything at all!)
If I understand your question correctly, you want to understand the structure, Lie algebra, and representation theory of the Lie group $\mathbb{R}^{\times}$ of invertible scalars. Another name for this Lie group is the general linear group $\text{GL}_1(\mathbb{R})$. This is a very easy Lie group to understand, since it's $1$-dimensional and therefore abelian. It has two connected components, the positive reals and the negative reals, and the positive reals are isomorphic to $\mathbb{R}$ (which is its Lie algebra) via the exponential map
$$\mathbb{R} \ni t \mapsto e^t \in \mathbb{R}^{\times}_{>0}.$$
Because this group is $1$-dimensional and abelian, its Lie algebra is also $1$-dimensional and abelian, and so there are no interesting Lie brackets.
A finite-dimensional complex representation of the Lie algebra $\mathbb{R}$ is given by a choice of square complex matrix. The classification of representations is the classification of complex matrices up to conjugation, which is described by Jordan normal form. The classification of real representations is a bit more complicated but can be deduced from the structure theorem for finitely generated modules over a PID applied to $\mathbb{R}[x]$ (which should be interpreted in this context as the universal enveloping algebra of the Lie algebra $\mathbb{R}$).
There is absolutely no need to go beyond standard linear algebra and Lie theory here. Replacing $\mathbb{R}$ with $\mathbb{C}$ is also not an issue.


text:
Q: Prevent access to extension-less files from .htaccess? I want PHP to generate log files which is usually an "error_log" file, without an extension. So how do you block access to such files in .htaccess?

A: The following will deny all files. Then allow files containing ".".
deny from all
<Files ~ "\.">
   order allow,deny
   allow from all
</Files>


text:
Q: Question about composite primary keys Example table:
Ticket
    - id
    - tenant_id
    - foo
TicketItem
    - id
    - tenant_id
    - ticket_id
    - bar

Assuming that id and tenant_id on each table make up composite primary keys, and that ticket_id is a foreign key to Ticket will this setup protect me from a circumstance where a TicketItem has tenant_id=1 and ticket_id=5  where the Ticket with id=5 has tenant_id=2? In simpler words, would the database allow me to link rows from 2 tables - each with different tenant_id - together, ruining my data, or does it protect me from this?
Also, does the above example seem like a "good" use of a composite primary key?

A: IF your Ticket table has a primary key on (TicketID, TenantID), then any table referencing the Ticket table would also have to reference both columns, e.g.
TicketItem(TicketID,TenantID) ==> Ticket(TicketID,TenantID)

You cannot have a reference to just parts of a (compound) primary key, e.g. you cannot have TicketID in TicketItem reference the Ticket table - you need both parts of a compound primary key in every single foreign key referencing it (one of the major drawbacks of compound indices, in my opinion - it makes joins cumbersome)

A: If I understand you correctly - the foreign key in TicketItem should reference both the id and tenant_id fields in the Ticket table. A foreign key should reference a primary key - if you were to only reference the id, you would not be referencing the primary key of the ticket table, as the Ticket table contains a composite key that includes both the id and the tenant_id fields.
If you have a foreign key in TicketItem that references the Ticket table's primary key (both id and tenant_id), then you will not be able to insert/update a record in the TicketItem table that does not have a corresponding id + tenant_id record in the Ticket table (this is what you desire).
TicketItem:
Foreign Key should reference ticket_id -> Ticket.id AND tenant_id -> Ticket.tenant_id
As far as a "good" use of the composite key - it depends on your design/requirements, but there is not anything "bad" about it.

A: "where the Ticket with id=5 has tenant_id=2"
Based on that wording ("the ticket"), is there only ever one ticket with id = 5? If so, that's your primary key and using the tenant_id to make a composite key is just making things more cumbersome.
If you can have multiple id = 5 then you can use the composite key, and yes it'll need to match both correctly in order for the reference to work.


text:
Q: How do I utilize move semantics when returning a member variable? I'm implementing a factory class which builds a vector of uint8_t. I want to be able to utilize move semantics when returning the resulting vector. This seems to work but I'm not confident this is the correct way of accomplishing what I want.
I have seen quite a few examples of how a returned automatic variable will be regarded as an rvalue and use the move constructor of the calling code, but in my example, the returned object is a member. I know the member will loose its contents if the caller puts the return value into a move constructor - and this is just what I want.
I have written it something like this:
#include <cstdint>
#include <iostream>
#include <vector>

class Factory
{
public:
    std::vector<uint8_t> _data;

    Factory(std::size_t size) :
        _data(size, 0)
    {
    }

    void buildContent(int param)
    {
        // perform operations on the contents of _data
    }

    std::vector<uint8_t> && data()
    {
        return std::move(_data);
    }
};

int main()
{
    Factory factory(42);
    factory.buildContent(1);
    std::vector<uint8_t> temp(factory.data());
    std::cout << "temp has " << temp.size() << " elements" << std::endl;
    std::cout << "factory._data has " << factory._data.size() << " elements" << std::endl;

    return 0;
}

Edit:
Oh, and the example code outputs the following:
temp has 42 elements
factory._data has 0 elements

A: First of all, you have to decide what you want. Do you really want to suck data out of your instance? If so, what you have achieves that fine. On the other hand, it looks quite unsafe. What you could do is use reference qualifiers to enforce that you only return an rvalue reference when the instance itself is an rvalue reference:
std::vector<uint8_t> && data() && // called on rvalue
{
    return std::move(_data);
}

// return lvalue ref or value
std::vector<uint8_t>& data() & // called on lvalue
{
    return _data;
}

In the end, it all depends on which problem you are trying to solve, which is not apparent from your question.

A: If your compiler has rvalue references to this (&& after methods), you might want to use that.  See @juanchopanza's answer.
If you don't, you first want to make sure that data() makes it clear that you are moving.  There are a few ways to do this.
First, non-member methods (friends) can override on &&.  So you can get this syntax:
std::vector<uint8_t> temp(get_data( std::move(factory) );

where get_data has && and & overloads on your factory type, and either moves or not based off it.
Next, you want to return a std::vector<uint8_t> instead of a `std::vector<uint8_t>&& for lifetime extension issues.  The runtime cost is somewhere between zero and small, but the bugs eliminated are worthwhile.
If create_factory returns a Factory object, then if we do this:
for( uint8_t x : get_data( create_factory() ) )

the get_data that returns a && doesn't work, while the one that returns a temporary works flawlessly.
What is going on?  Well, ranged-based for loops are defined as binding the thing you are iterating over to a reference.  A temporary bound to a reference has its lifetime extended: a reference bound to a reference has no lifetime extension.  The create_factory function's return value's lifetime is not extended in either case.
With the && case, the reference to vector is left dangling.  With the return-temporary case, the factory's vector is moved into the temporary, then that temporaries lifetime is extended.
In short, returning && references is very rarely a good idea.

A: How about hiding the assignment operator in your vector and only implementing move assignment operator (essentially disallowing copying - if that's what you want).
So that this:
std::vector<uint8_t> temp(factory.data());

will not compile unless you change it to this :
std::vector<uint8_t> temp(std::move(factory));


text: Q: windows 7 truecrypt boot loader my entire disk was encrypted with truecrypt. When i was working on, the pc shutdown immediately. I try to turn it on. Truecrypt boot loader password is asked. I enter the pwd correctly but i can only see windows repair screen. And the partitions are seemed as null. i can only see x: partition that is about boot loader as i guess. can you help me how i can get my operating system back? Thank you.


text:
Q: Return Entire Row from Index Match Function Excel In Table 1:

*

*I have Product Segments 1-6 for Companies

*1-8. Each have different products that they list, not necessarily in the same order.
1-8. Each have different products that they list, not necessarily in the same order.

In Table 2:

*

*I would like to return a "True" or "False" if the company lists Product Segments A-F as one of their products. For example, in Table 2 for Product Segment A, company 1 would return "True" and company 4 would return "False"

I feel like an =MATCH(J$2,INDEX($B$3:$G$10,MATCH($I3,$A$3:$A$10,0)),0) function is exactly what I'm looking for, but unfortunately I cannot return an array with excel's INDEX function.
Any suggestions would be highly appreciated.
Please refer to the image below:
http://i.stack.imgur.com/491Wk.jpg

A: I would use SUMPRODUCT:
=SUMPRODUCT(($A$3:$A$10=$I3)*($B$3:$G$10=J$2))>0


text:
Q: JxBrowser escape key not dispatched When I dispatch an escape key from Java to JxBrowser, it is not received.  But I can successfully send numeric keys, the enter key, alpha keys, etc.  The two simple test cases below show my problem (read misunderstanding).
    KeyTyped keyTyped = KeyTyped.newBuilder().setKeyCodeValue(13).build();
    browser.dispatch(keyTyped);   // JavaScript handler receives enter keystroke

    KeyTyped keyTyped = KeyTyped.newBuilder().setKeyCodeValue(27).build();
    browser.dispatch(keyTyped);   // JavaScript handler DOES NOT receive escape keystroke

// JS handler
$(document).on('keypress.lineItemSelected', this.handleKeyboardPress.bind(this));

A: ESC is not a text symbol. Sending only KeyTypes is not correct way of simulating keyboard input. Please try dispatching KeyPressed, KeyTyped, and then KeyReleased as shown in the example at https://jxbrowser-support.teamdev.com/docs/guides/browser.html#dispatch-keyboard-events
private static void dispatchKeyEvent(Browser browser, char character, KeyCode keyCode) {
    KeyPressed keyPressed = KeyPressed.newBuilder(keyCode)
            .keyChar(character)
            .build();
    KeyTyped keyTyped = KeyTyped.newBuilder(keyCode)
            .keyChar(character)
            .build();
    KeyReleased keyReleased = KeyReleased.newBuilder(keyCode)
            .build();

    browser.dispatch(keyPressed);
    browser.dispatch(keyTyped);
    browser.dispatch(keyReleased);
}


text:
Q: Taking an infinite number of square-roots. CORRECTION: Thank you to those who pointed out the mix-up, I meant to write the limit as $i$ approaches infinity.
I came across an interesting application of geometric series. Considering $...\sqrt(\sqrt(\sqrt(\sqrt(\sqrt(...(\sqrt(2)))))) = 2^{\lim_{i \rightarrow \infty}\frac{1}{2^i}} = 2^1 = 2$, it appears to follow that for any arbitrary non-zero, positive, real-number $a$, $a^{\lim_{i \rightarrow \infty}\frac{1}{2^i}} = a$. While I haven't taken complex analysis, is this also true for any complex number? As in, is it true that for non-zero, $a,b \in \mathbb{R}$ that $(a + bi)^{\lim_{i \rightarrow \infty}\frac{1}{2^i}} = a + bi$?
As an aside, I find the result: $2^{\lim_{i \rightarrow \infty}\frac{1}{2^i}} = 2$ very counter-intuitive. Using a calculator, the more and more square-roots I take of $2$, it appears to get further and further away from 2 $-$ not closer, as I would expect given the result. Any explanation would be appreciated.

A: You're wrong! Taking "an infinite" number of square roots leads to $$...\sqrt(\sqrt(\sqrt(\sqrt(\sqrt(...(\sqrt(2))))))={\left({\left(2^{\frac{1}{2}}\right)}^{\frac{1}{2}}\right)}^{\frac{1}{2}...}=2^{\frac{1}{2}\frac{1}{2}\frac{1}{2}...}$$
The application would be multiplying an infinite number of square roots of other square roots, i.e.
$$\left(\sqrt{2}\right)\left(\sqrt{\sqrt{2}}\right)\left(\sqrt{\sqrt{\sqrt{2}}}\right)...=2^{\frac{1}{2}}2^{\frac{1}{2^2}}2^{\frac{1}{2^3}}...=2^{\sum \frac{1}{2^i}}=2^1=2$$
And this is true since the function $2^x$ is continuous (so if $a_n$ converges to $a$, $2^{a_n}$ converges to $2^a$). Note this is valid if I change 2 by any complex number.

A: The result you're looking for is this:
$$
\sqrt{a}\cdot\sqrt{\sqrt{a}}\cdot\sqrt{\sqrt{\sqrt{a}}}\cdots = a^{1/2}a^{1/4}a^{1/8}\cdots=a^{1/2+1/4+1/8+\ldots}=a.
$$
When you multiply the different levels of nested square roots together, you get a geometric series summing to $1$ in the exponent.  This will work for complex $a$ as well, as long as you choose a consistent branch for the square roots; for instance, you can lay the branch cut along the negative real axis.

A: Taking an infinite number of square roots like that will not sum any exponents, it will multiply them. You will end up with simply the limit as $n$ approaches infinity of $2^{\frac{1}{2^{n}}}$.
This is $1$, and it is $1$ regardless of whether we have $2^{\frac{1}{2^{n}}}$, $42^{\frac{1}{2^{n}}}$, $i^{\frac{1}{2^{n}}}$, etc.

A: Anyway indeed your question is wrong but $(a+ib)^{1/2^n}\to 1$ as $n \to \infty$


text:
Q: Excel split cell I'm trying to split the below data in EXCEL but unable to get the required result.

A
B
C

ABC Abc
ABC
Abc

BCD Bcd Cde
BCD
Bcd Cde

CDE EFG Cde
CDE EFG
Cde

Colum A to be splitted as mentioned in B and C column

B Column will have data of all capital words before space of capitlize word

C column will have Cap words

A: The array formula in B1 below

is
=LEFT(A1,AGGREGATE(15,6,FIND(CHAR(96+COLUMN(A1:Z1)),A1),1)-3)

and the array formula in C1 is
=MID(A1,AGGREGATE(15,6,FIND(CHAR(96+COLUMN(A1:Z1)),A1),1)-1,LEN(A1)-LEN(B1))


text:
Q: Enum Values to Array i want to get only the values of an enum as an array. So if you have:
    enum A {
        dog = 1,
        cat = 2,
        ant = 3
    }

What i want: ["dog", "cat", "ant"] by:
    Object.values(A)

but it gets you: ["dog", "cat", "ant", 0, 1, 2]
Also the values returned (0, 1, 2) would not match the given ones (1, 2, 3) anyway.
How can i accomplish that?

A: The short answer you can't since typescript would compile your enum into the following
var A;
(function (A) {
    A[A["dog"] = 1] = "dog";
    A[A["cat"] = 2] = "cat";
    A[A["ant"] = 3] = "ant";
})(A || (A = {}));

link to typescript playground
however, since enums can't have numeric keys you can do the following to get the keys
Object.keys(A).filter(isNaN)

this works because an Enum can't contain a numeric value as an entry


text:
Q: Bonescript Unable to find devicetree fragment I'm working with a BeagleBone Black and trying to get bonescript running. I'm running Debian Wheezy with the latest updates and the latest versions of node v0.10.21 and bonescript 0.2.4. I'm able to blink the internal LED, so I'm fairly certain my installation is working fine. My problem is that I'm unable to control any of the P8 or P9 gpios. Using the examples on the bonescript website I'm running the following script. I'm not sure exactly what this error means so even if someone can point me into the right direction I would appreciate it.
Thank you
Scottt
=============================================
var b = require('bonescript');
var led = "P8_3";
var state = 0;

b.pinMode(led, b.output);
toggleLED = function() {
    state = state ? 0 : 1;
    b.digitalWrite(led, state);
};

timer = setInterval(toggleLED, 100);

stopTimer = function() {
    clearInterval(timer);
};

setTimeout(stopTimer, 30000);

=====================================================
I turned on bonescript debugging and get the following output regarding being unable to find the devicetree fragment.
root@debian-armhf:/usr/lib/node_modules/bonescript# nodejs blinkext.js
debug: cpuinfo = processor      : 0
model name      : ARMv7 Processor rev 2 (v7l)
BogoMIPS        : 660.76
Features        : swp half thumb fastmult vfp edsp thumbee neon vfpv3 tls
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x3
CPU part        : 0xc08
CPU revision    : 2

Hardware        : Generic AM33XX (Flattened Device Tree)
Revision        : 0000
Serial          : 0000000000000000

debug: index.js loaded
debug: pinMode(P8_3,,,,);
debug: templateFilename = /usr/lib/node_modules/bonescript/bspm_template.dts
debug: fragment = bspm_P8_3_2f
debug: command = dtc -O dtb -o /lib/firmware/bspm_P8_3_2f-00A0.dtbo -b 0 -@ /lib/firmware/bspm_P8_3_2f-00A0.dts
error: Failed to find devicetree fragment: bspm_P8_3_2f
info:  0: 54:PF---
 1: 55:PF---
 2: 56:PF---
 3: 57:PF---
 4: ff:P-O-L Bone-LT-eMMC-2G,00A0,Texas Instrument,BB-BONE-EMMC-2G
 5: ff:P-O-L Bone-Black-HDMI,00A0,Texas Instrument,BB-BONELT-HDMI

debug: Unable to configure mux for pin [object Object]: Error loading devicetree overlay for P8_3 using template bspm
debug: getPinMode(P8_3);
debug: getPinMode(P8_3): Error: ENOENT, no such file or directory '/sys/kernel/debug/pinctrl/44e10800.pinmux/pins'
debug: pinMode: mode = {"pin":"P8_3","name":"GPIO1_6","options":["gpmc_ad6","mmc1_dat6","NA","NA","NA","NA","NA","gpio1_6"],"gpio":{"allocated":false}}
debug: getPinMode(P8_3);
debug: getPinMode(P8_3): Error: ENOENT, no such file or directory '/sys/kernel/debug/pinctrl/44e10800.pinmux/pins'
info: Error loading devicetree overlay for P8_3 using template bspm

=======================================================
Here is what I believe is the overlay template bonescript creates.
/*
 * This is a template-generated file from BoneScript
 */

/dts-v1/;
/plugin/;

/{
    compatible = "ti,beaglebone", "ti,beaglebone-black";
    part_number = "BS_PINMODE_P8_3_0x2f";
    version = "00A0";

    exclusive-use =
        "P8.3",
        "gpio1_6";

    fragment@0 {
        target = <&am33xx_pinmux>;
        __overlay__ {
            bs_pinmode_P8_3_0x2f: pinmux_bs_pinmode_P8_3_0x2f {
                pinctrl-single,pins = <0x018 0x2f>;
            };
        };
    };
    fragment@1 {
        target = <&ocp>;
        __overlay__ {
            bs_pinmode_P8_3_0x2f_pinmux {
                compatible = "bone-pinmux-helper";
                status = "okay";
                pinctrl-names = "default";
                pinctrl-0 = <&bs_pinmode_P8_3_0x2f>;
        target = <&am33xx_pinmux>;
        __overlay__ {
            bs_pinmode_P8_3_0x2f: pinmux_bs_pinmode_P8_3_0x2f {
                pinctrl-single,pins = <0x018 0x2f>;
            };
        };
    };

    fragment@1 {
        target = <&ocp>;
        __overlay__ {
            bs_pinmode_P8_3_0x2f_pinmux {
                compatible = "bone-pinmux-helper";
                status = "okay";
                pinctrl-names = "default";
                pinctrl-0 = <&bs_pinmode_P8_3_0x2f>;
            };
        };
    };
};

A: We have forked bonescript and released new package. We faced same error and now solved everything by re-writing lot of code in original bonescript. You can install and use in your projects. https://www.npmjs.org/package/octalbonescript


text:
Q: Exposition about Ergodic Entropy does anybody could suggest me any book or paper about Entropy in Ergodic Theory?
I'm trying to prepare an exposition but I've just 30/40 minutes more or less so I'd like to choose a theme, or some theme interesting about it without loosing anything important.
Since I'm not that skilled about it I hope that somebody could help suggesting me a scheme or a possible list of main topic I can choose between.
Also paper about it or book will be helpful.
Thank you

A: Michael Brin and Garret Stuck pdf book http://inis.jinr.ru/sl/vol2/Mathematics/Diff.Equations/Brin%20M.,%20Stuck%20G.,%20Introduction%20to%20Dynamical%20Systems,%202003.pdf (metric entropy chapter 9)
survey by Lai Sang Young  http://cims.nyu.edu/~lsy/papers/entropy.pdf

A: There is a several papers and books about this matter.

*

*The Brin Stuck Book, the last chapther is about metric entropy. (I think it's the best introduction that I know)

*The Katok-Hasselblatt  book, A Modern Introduction  to Dynamical Systems(It has an approach similar to the previous reference but with more detailed calculations)

*The Lai Sang Young Survey, Entropy in Dynamical Systems ( Gives an overview of the theory, but without calculations.)

*The  Bowens Book ,Equilibrium States and the Ergodic Theory of Anosov Diffeomorphisms, (Besides being very introductory has many references at the end of each chapter.)

*Entropy in Dynamical Systems - Tomasz Downarowicz -( this book is very detailed. deals with the subject in a profound way)


text:
Q: Get difference of digit count between 2 numbers For a simple command line tool I want to draw a simple graph showing some points and their y-axis value. For the y-axis labeling I want to print the level of the current "row" like:
55,09|  |
54,90|  ||
54,70|  ||
54,51|  ||
54,32|  ||
54,13|  ||
53,94|  ||
53,75|  ||
53,56|  ||
53,37|  |||
53,18|  |||                   |    |
52,99|  |||            |     ||    |
52,80|  |||         |  |     ||    |
52,61|  |||         || |     |||   |
52,42| ||||||       || |  |  ||||  ||
52,23| ||||||       ||||  |  ||||  ||
52,04| ||||||       ||||  |  |||| |||
51,85| ||||||       ||||  |  |||| |||
51,66| ||||||       |||| ||| |||| |||
51,47| ||||||      ||||||||| ||||||||
51,28| ||||||      ||||||||||||||||||
51,09| ||||||      ||||||||||||||||||
50,90| ||||||     |||||||||||||||||||
50,71| ||||||     |||||||||||||||||||
50,52| |||||||    |||||||||||||||||||
50,33| |||||||    |||||||||||||||||||
50,14| |||||||  |||||||||||||||||||||
49,95| |||||||  |||||||||||||||||||||
49,76| |||||||| |||||||||||||||||||||
49,28| ||||||||||||||||||||||||||||||

but it can happen that the max value has more digits than the min value:
1000,00| |
666,67| | |
333,33| |||
0,01|||||

so how can I get the difference of the digits between the max and min value so I can add leading spaces?
1000,00| |
 666,67| | |
 333,33| |||
   0,01|||||

A: Quick'n'dirty:
double max = getMaximum(); // Get your maximum Y value
int smax = String.format("%.2f", max).length(); // Print as a string and get number of characters

In your loop:
System.out.format("%"+smax+".2f", value);

Edit, from @EJP's comment
It is indeed both cleaner and more efficient to use log10 on the max. It will give you the power of 10, hence the number of digit (minus one) that will be used. While the first solution is straightforward (counting characters, which is straightly what we want), that solution is better in every other aspect:
double max = getMaximum();
int ndigits = (int)Math.floor(Math.log10(max)) + 1;
int precision = 2; // Number of digits after decimal point
String fmt = "%"+(ndigits+1+precision)+"."+precision+"f"; // "%x.pf", x is the TOTAL length, including the point and precision digits

In your loop:
System.out.format(fmt, value);


text:
Q: What's the DMA direction for memory-to-memory transfer? It seems that the dma_data_direction enum is defined for transfer between device and memory:
enum dma_data_direction {
    DMA_BIDIRECTIONAL = 0,
    DMA_TO_DEVICE = 1,
    DMA_FROM_DEVICE = 2,
    DMA_NONE = 3,
};

Why there is not a direction definition for memory-to-memory (or device-to-device) DMA transfer?

A: Memory-to-memory DMA transfer mean you "READ" from memory and "WRITE" to memory. In this case the dma_data_direction is DMA_BIDIRECTIONAL.
For other value:

*

*DMA_TO_DEVICE : mean from memory to device

*DMA_FROM_DEVICE : mean from device to memory


text:
Q: What does "hump" mean in this context? The context is from the movie "Fear And Loathing In Las Vegas"
The following text is the main character's narration of things and people he sees while walking around a casino in Las Vegas.
        DUKE:
        Who are these people?  These faces!
        Where do they come from?  They look
        like caricatures of used car
        dealers from Dallas.
        And, sweet Jesus, there are a hell
        of a lot of them at four-thirty on
        a Monday morning.  Still **humping**
        the American dream, that vision of
        the big winner somehow emerging
        from the last minute predawn chaos
        of a stale Vegas casino.

The only definition I found that might have something to do with this context is this one
6. Slang. to exert (oneself) in a great effort.
(It's from thefreedictionary.com)

A: It's just a vaguely obscene metaphor.  "Have sex with the American Dream".
Humping is not like "making love".  It's boring, routine sex, done without much emotion or connection.
The American dream is that "You can achieve anything! (if you work for it)"  These guys are dreaming of getting rich, but they aren't emotionally connected to that dream, and not to the bit about "working for it".  It is boring and routine.
But by using vulgar language, Duke gets to insult these people.


text:
Q: Should static_cast(Base pointer) give compile time error? Should static_cast(Base pointer) give compile time error?
class A
{
public:
    A()
    {

    }
};

class B : public  A
{
 public:
     B()
     {
     }
};

int main()
{
    A *a=new A();
    B * b=static_cast<B*>(a);   // Compile Error?
}

A: It cannot give compile time error because a Base-Derived relationship can exist at runtime depending on the address of the pointers being casted.
static_cast always succeeds, but will raise undefined-behavior if you don't cast to the right type. dynamic_cast may fail or not, actually telling you whether you tried to cast to the right type or not.
So in my opinion, static_cast should be used to downcast only if the design can establish that such a possibility exists. One good example of this is CRTP. So it is logical in some situations but try to avoid it as it is undefined-behavior.
RTTI is not needed for static_cast which might make it theoretically faster, but I will anytime trade-in a dynamic_cast against the undefined behavior that static_cast may cause!

A: It doesn't give a compile time error because the cast could very-well be valid, and you would often do it in practice, e.g.:
A* a = new B;
B* b = static_cast<B*>(a); // OK

In your code, as far as the compiler is concerned, you are doing the same thing. It cannot know that the cast would be invalid, so it allows it at compile time. At run time however, you're going to get some nasty errors as soon as you try to use a feature of B on an instance of A.


text:
Q: Hosting Emberjs Application on Koajs with koa-static I'm hosting an emberjs application on koajs with koa-static.
according to below code :
var app = koa();
var App1 = koa();
App1.use(stati(__dirname + "/App1"));
app.use(mount('/AppViewer',App1));
app.listen(3000);

When  calling localhost:3000/AppViewer i can't see my page and gets error says can't find .js and .css files, but when calling localhost:3000/AppViewer/index.html all things works correctly. so my question is how to see my page when calling localhost:3000/AppViewer.

A: This was sufficient for me using ember-cli and deploying to heroku:
var common = require('koa-common'),
    koa = require('koa'),
    app = koa();

var env = process.env.NODE_ENV || 'development',
    port = process.env.PORT || '3800';

app.use(common.logger());
app.use(common.responseTime());
app.use(common.static(__dirname + "/dist"));

app.listen(port);

console.log('listening on port ' + port);

where /dist is the build output for ember build (equivalent of grunt dist w/ EAK)

A: First, it seems strange, because koa-static is supposed to default to serving index.html on root. Make sure App1 is not routing the / to somewhere else.
Then, you can still get rid of index.html in URL by using koa-rewrite. Something like:
var rewrite = require('koa-rewrite');
App1.use(rewrite('/*', '/index.html'));

UPDATE
Tested with the following code:
var koa = require('koa');
var app = koa();
var app1 = koa();
var mount = require('koa-mount');
var serve = require('koa-static');
var rewrite = require('koa-rewrite');
var route = require('koa-route');

app1.use(serve(__dirname + "/app1"));
app1.use(rewrite('/*', '/index.html'));
app.use(mount('/av', app1));

app.use(route.get('/', function *(next) {
  this.body = 'I\'m the main app!';
}));

app.listen(3000);

A: koa-static didn't work for me. I instead tried koa-static-server and yay!
My middleware:
var Proxy = require("koa-proxy");
// const Rewrite = require("koa-rewrite");
const StaticServer = require("koa-static-server");

export const InstallWebApp = (app) => {
  if (process.env.NODE_ENV === "production") {
    // Install static web app
    // app.use(Rewrite('/*', '/'));
    app.use(StaticServer({rootDir: `${__dirname}/../../../../client-web/build`, notFoundFile: "index.html"}));
  } else {
    // Install dev server
    app.use(
      Proxy({
        host: `http://localhost:${process.env.WEB_DEV_PORT}`,
      })
    );
  }
};


text:
Q: Calculating type of polymorphism haskell I need to calculate types of following expressions:

*

*curry fst

*foldr const

*(foldr const) . (curry fst)

First I have:
curry :: ((a, b) -> c) -> a -> b -> c
fst :: (d, e) -> d

{}                      |   (a,b)-> c = (d,e) -> d
{}                      |   (a,b) = (d,e) , c = d
c -> d                  |   (a,b) = (d,e)
c -> d , a ->d          |   b = e
c -> d , a ->d, b -> e  |   {}

then replace the result in a -> b -> c and you get d -> e -> d
Now similar to this I do:
foldr :: (f -> g -> g) -> g -> [f] -> g
const :: h -> i -> h

{}                      |    (f -> g -> g) =  h -> i -> h
{}                      |    f = h , g = i, g = h
f -> h                  |    g = i, g = h
f -> h, g -> i          |    i = h
f -> h, g -> i  i->h    |    {}

then replace the result in g -> [f] -> g and you get i -> [h] -> i
Next, i  have to do
(foldr const) . (curry fst) but i am not sure if these results are correct. I tried anyway but got stuck. So:
(foldr const) :: i -> [h] -> i and (curry fst) :: d -> e -> d
(.) :: (j -> k) -> (l -> j) -> l -> k

then i start with:
d = (j -> k) -> (l -> j) -> l -> k, e =  d -> e -> d
e = (j -> k) -> (l -> j) -> l -> k -> e -> (j -> k) -> (l -> j) -> l -> k

but it feels wrong and i cannot continue...
Are my first two results correct?
If they are, how should i solve the last one?

A: The first result is correct.
The calculation for the second result is correct until you make the substitution in the last step. Easily missed. You had (using =, rather than ->, as the latter constructs function types and thus might cause confusion)
f = h, g = i, i = h

so substituting in g -> [f] -> g gives
h -> [h] -> h

not i -> [h] -> i, because although g = i, it's also the case that i = h, so together, g = h. That is, you need either to normalise your substitution (applying each new solution to instantiate the old substitution as well as extend it, giving f = h, g = h, i = h), or to apply your substitution carefully one step at a time:
g -> [f] -> g
  -- f = h
g -> [h] -> g
  -- g = i
i -> [h] -> i
  -- i = h
h -> [h] -> h

Now, for the final step of the calculation, you have all the pieces, but you have missed the way . is an infix operator. Its first argument is foldr const which must have type j -> k. Its second argument is curry fst which must have type l -> j. The whole thing has type l -> k. So, the equations you must solve are
j -> k  =  h -> [h] -> h   -- from the first argument
l -> j  =  d -> e -> d     -- from the second argument

Now, -> associates to the right, so the first gives
j = h
k = [h] -> h

and the second gives
l = d
j = e -> d

Combining the two gives
h = e -> d

so we end up with (normalised)
h = e -> d
j = e -> d
k = [e -> d] -> e -> d
l = d

and instantiating l -> k gives the type
d -> [e -> d] -> e -> d

The function takes a default d, then a list of functions, then an input e: if the list of functions is empty, you get the default as the result; if the list is nonempty, you get the result of applying the first function to the input.


text:
Q: How to sum JSON objects data in Rails using after_save? I'm storing daily orders inside daily_orders table. Inside that table, I've total column and special_kitchen_orders column (type: JSON).
Right now, when I run this into my console:
ap DailyOrder.first.special_kitchen_orders

I get this back:
[
    [0] {
         "name" => "pizza",
          "qty" => 1,
        "price" => 10
    },
    [1] {
         "name" => "burger",
          "qty" => 1,
        "price" => 20
    },
    [2] {
         "name" => "cake",
          "qty" => 1,
        "price" => 30
    }
]

I was thinking to use after_save to calculate sum of all objects price but I've no idea how to make it.
In this example, the total should be 60 (10 + 20 + 30).
How to sum all objects price after saving the record and put it inside the total column using after_save?
Note: ap is from awesome_print gem.
SOLVED
I just found the idea after reading this article. Thanks Sergio Tulentsev for pointing this reduce thing to me. It's totally new thing for me.
def total(array)
  array.reduce(0) do |sum, num|
    sum += num
  end
end

total([1,2,3])
# => 6

A: It's as simple as this
special_kitchen_orders.reduce(0) do |memo, order|
  memo + order['qty'] * order['price']
end

Also you might want to do this in a before_save, not after_save.


text:
Q: How to make a listview entry blink after scrolling to it? I have a listview in my app and I want to be able to scroll to a position in the listview and then perform a blink animation at that entry to highlight it to the user.
The issue I'm having it that the blinking animation doesn't happen if the entry that's scroll to is outside of the listview's view. I understand that the listview is efficient because it doesn't load all the entries at once, so this is likely the reason the animation doesn't occur. How can I get around this issue?
Scroll to code:
    //Changes to tab with listview
    tabLayout.getTabAt(1).select();
    //Get index to scroll to
    int selectIndex = whitelistFragment.getWhitelistTableHelper().getListViewEntryIndex(entryString);
    //If the entry exists
    if(selectIndex != -1) {
        //Scroll to index
        whitelistFragment.getWhitelistTableHelper().getListView().setSelection(selectIndex);

        //Make entry blink several times
        View entryView = helperFunctions.getViewByPosition(selectIndex, whitelistFragment.getWhitelistTableHelper().getListView());
        Animation blinkAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink);
        entryView.startAnimation(blinkAnimation);
    }

Blink.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <alpha android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="600"
        android:repeatMode="reverse"
        android:repeatCount="5"/>
</set>

A: ListView is not efficient, you should use RecyclerView. It have method scrollToPosition(). Later in onBindViewHolder check if position == blink postion and run animation on itemView. You could use startDelay for better look.


text:
Q: help with sample size calculation hi im conducting a study on a certain ratio in a blood exam (lets call it X) .
I aim to say that there is a certain sensitivity (let say>80%) for people to be sick if X>10. (my actual intent is to check the sensitivity for different values of X)
its a retrospective cohort and the estimated incidence of sick people in the whole group is 3.5%
how or which tool should i use to calculate the sample size? i have tried to find an answer online (including this good chinese site: http://www.statstodo.com/StatsToDoIndex.php#Sample Size) but so far no success
(type 1 error 0.05 power 0.8)


text:
Q: Android / Java find the correct library for a particular class How can I figure out which class needs to import which library?
For example, I see a sample code like below:
RequestQueue queue = Volley.newRequestQueue(this);

When I try this code Android Studio throws that RequestQueue and Volley cannot resolve.
Is there any documentation, wiki, a website for finding out the correct import library for these classes?

A: Just do a search for the class on google. So in this case, search for the class 'RequestQueue' on google and the second result itself gives you the package. Here, it is com.android.volley package.
http://afzaln.com/volley/com/android/volley/RequestQueue.html

A: There is a library that you can use for parsing and this code is related to Volley library to remove that error you must check that library is in your project or not.
Check your build.gradlefile(App)
dependencies {
    ...
    compile 'com.android.volley:volley:1.0.0'
}

If above line is there then you can use that library


text:
Q: Laravel 5.8 403 This action is unauthorized I have update method like this
  public function update(Contact  $contact)
{

    $this->authorize('ownItems', $contact);
    ......
}

and ContactPolicy :
public function ownItem(User $user,Contact $contact)
{
  return true;
}

It work correctly but when I replace Contcact to ContactRequest  in my update method
show me this :

403 This action is unauthorized.

update method :
public function update(ContactRequest  $contact)
{
    $this->authorize('ownItems', $contact);
    .......
}

authorize method in ContactRequest:
public function authorize()
{
    return true;
}

A: ContactRequest is a laravel Request class instance

public function update(ContactRequest $request,Contact  $contact)
{
    $this->authorize('ownItems', $contact);
    .......
}

A: You misspelled method name in $this->authorize('ownItems', $contact);, it should be "ownItem"
UPD
ContactRequest is probably instance of Illuminate\Http\Request but authorize method waiting for Model instance, if you do not have model identifier in yout request. first you should to find model: $model = Contact::find($contact->input('id')) and than check your policy with $this->authorize('ownItems', $model)


text:
Q: bootstrap 3.0 grid with less than 12 columns I am trying to create a calendar using the grid with only 7 columns. I would like to have these 7 columns evenly spaced and fit the entire row. Currently, the 7 columns does not add up to 12 and I get 12 columns with 5 empty. Is there a way in Bootstrap 3 to get all 7 spread across the row?

A: Your best bet is probably to create your own custom column class. Since you want a colum that spans 1/7th the width of it's parent, use width:14.285%; (100 divided by 7 = 14.285...).
DEMO: http://www.bootply.com/uakh14tkuX
CSS
.col-day{
    width:14.285%;
    border:1px solid grey;
    float:left;
    position: relative;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
  }

HTML

Sun

Mon

Tue

Wed

Th

Fr

Sat

Sun

Mon

Tue

Wed

Th

Fr

Sat

In the CSS section, float, position, min-height and the paddings are the same as any other bootstrap col-class. Width and border are the only truly custom aspects. But you'll also want to consider what happens on different sized devices - this solution is NOT responsive the way combined col-classes are...

A: Short answer: not really maybe?
From Grid description:
Remember, grid columns should add up to twelve for a single horizontal block. More than that, and columns start stacking no matter the viewport.

The number 12 was chosen due to high versatility (you can have: 1,2,3,4,6 or 12 columns), but there is always some caveat to such solutions: they require some conformity to its standards.
Now, what happens when you create 7 divs like this:
? I've done a quick test and well, I've got 7 columns. Of course they take only 7/12 of my container width - so if that's acceptable, then you can roll with it.
If not, you'll either have to use your own solution (either leveraging existing bootstrap classes or start from blank), modify bootstrap (possible, but I'd advice against, because it creates problems for future maintenability), or change your design. Or maybe just use some other component/template?

A: Why not double 7 to 14?  It's much simpler to keep it an even number. That way you can create a layout that appears to add up to 7 columns. So for instance if you wanted a col-3 and col-4 layout, you would simply do col-6 and col-8. For a calendar, that would mean each day would get a  col-2 class.
Also check out https://github.com/zirafa/bootstrap-grid-only which might be easier to understand than Bootstrap's mixins, though you can always just go to the Bootstrap customize page and enter in the number of columns you want: http://getbootstrap.com/customize/


text:
Q: Create a Thread in UEFI Is there a way to have a threaded application running on UEFI? I've only found a few mentions of threading in the UEFI specifications, but they didn't really answer my question.

A: There is no threads in UEFI right now, but there is a MpService protocol, that can be used for performing tasks on CPU cores other then BSP (BootStrap Processor, the core that runs UEFI itself).
You can read more about the same question here, nearly nothing is changed from that time. This presentation can also be useful, but not all functions mentioned there (sync primitives library, for example) are implemented in any given UEFI firmware.


text:
Q: MissingPropertyException: No such property: Error in Groovy script I execute the following Groovy script in my SoapUI
import com.*
import javax.xml.XMLConstants
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.SchemaFactory

def xsd = '''
<xs:schema targetNamespace="http://maps.googleapis.com" elementFormDefault="qualified" xmlns="http://maps.googleapis.com" xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <xs:element name="GeocodeResponse" type="_GeocodeResponse"/>
   <xs:complexType name="result_geometry">
      <xs:sequence>
         <xs:element name="location" type="geometry_location"/>
         <xs:element name="location_type" type="xs:string"/>
         <xs:element name="viewport" type="geometry_viewport"/>
         <xs:element name="bounds" type="geometry_bounds"/>
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="viewport_southwest">
      <xs:sequence>
         <xs:element name="lat" type="xs:decimal"/>
         <xs:element name="lng" type="xs:decimal"/>
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="bounds_northeast">
      <xs:sequence>
         <xs:element name="lat" type="xs:decimal"/>
         <xs:element name="lng" type="xs:decimal"/>
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="geometry_viewport">
      <xs:sequence>
         <xs:element name="southwest" type="viewport_southwest"/>
         <xs:element name="northeast" type="viewport_northeast"/>
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="geometry_bounds">
      <xs:sequence>
         <xs:element name="southwest" type="bounds_southwest"/>
         <xs:element name="northeast" type="bounds_northeast"/>
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="bounds_southwest">
      <xs:sequence>
         <xs:element name="lat" type="xs:decimal"/>
         <xs:element name="lng" type="xs:decimal"/>
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="viewport_northeast">
      <xs:sequence>
         <xs:element name="lat" type="xs:decimal"/>
         <xs:element name="lng" type="xs:decimal"/>
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="_GeocodeResponse">
      <xs:sequence>
         <xs:element name="status" type="xs:string"/>
         <xs:element name="result" type="GeocodeResponse_result"/>
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="address_component">
      <xs:sequence>
         <xs:element name="long_name" type="xs:string"/>
         <xs:element name="short_name" type="xs:string"/>
         <xs:element name="type" type="xs:string" maxOccurs="2"/>
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="GeocodeResponse_result">
      <xs:sequence>
         <xs:element name="type" type="xs:string" maxOccurs="2"/>
         <xs:element name="formatted_address" type="xs:string"/>
         <xs:element name="address_component" type="address_component" maxOccurs="3"/>
         <xs:element name="geometry" type="result_geometry"/>
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="geometry_location">
      <xs:sequence>
         <xs:element name="lat" type="xs:decimal"/>
         <xs:element name="lng" type="xs:decimal"/>
      </xs:sequence>
   </xs:complexType>
</xs:schema>
'''.trim()

def factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
def schema = factory.newSchema(new StreamSource(new StringReader(xsd)))
def validator = schema.newValidator()
validator.validate(new StreamSource(new StringReader(XmlExamples.G_RECORDS)))

XmlExamples.groovy is located in C:\Program Files\SmartBear\SoapUI-4.6.1\bin\ext\com
i.e.
class XmlExamples {
  static def G_RECORDS = '''
   <GeocodeResponse>
   <status>OK</status>
   .....

         </bounds>
      </geometry>
   </result>
</GeocodeResponse>
  '''
}

But problem is I am getting following error in SoapUI
:ERROR:groovy.lang.MissingPropertyException: No such property: XmlExamples for class: Script1
   groovy.lang.MissingPropertyException: No such property: XmlExamples for class: Script1
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
    at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:49)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:231)
    at Script1.run(Script1.groovy:86)
    at com.eviware.soapui.support.scripting.groovy.SoapUIGroovyScriptEngine.run(SoapUIGroovyScriptEngine.java:96)
    at com.eviware.soapui.impl.wsdl.teststeps.WsdlGroovyScriptTestStep.run(WsdlGroovyScriptTestStep.java:149)
    at com.eviware.soapui.impl.wsdl.support.AbstractTestCaseRunner.runTestStep(AbstractTestCaseRunner.java:239)
    at com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner.runCurrentTestStep(WsdlTestCaseRunner.java:48)
    at com.eviware.soapui.impl.wsdl.support.AbstractTestCaseRunner.internalRun(AbstractTestCaseRunner.java:148)
    at com.eviware.soapui.impl.wsdl.support.AbstractTestCaseRunner.internalRun(AbstractTestCaseRunner.java:43)
    at com.eviware.soapui.impl.wsdl.support.AbstractTestRunner.run(AbstractTestRunner.java:135)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

What could be the possible root causes. Is there anything to do with CLASSPATH? I believe the default location would be .......bin/ext
Cheers

A: The class XmlExamples seems to be missing the correct package declaration. Since it resides in a package called com you should have the following class:
package com

class XmlExamples {
  static def G_RECORDS = '''
    <GeocodeResponse>
      <status>OK</status>
        .....
          </bounds>
        </geometry>
      </result>
    </GeocodeResponse>
  '''
}

A: It appears that you are trying to validate an xml with the xsd using the example and the same sample code is successfully got executed in SoapUI tool when I tried both code snippets copied in same groovy script. May be you would want to try like that to isolate the problem.


text:
Q: How to rearrange the items in a map based on another map keys Hi I had a requirement where objects of a map are to arranged
in order of keys of another map.
here is the map
Map ObjectMap = new HashMap()
ObjectMap .put(id1,Obj1);
ObjectMap .put(id2,Obj2);
ObjectMap .put(id3,Obj3);
ObjectMap .put(id4,Obj4);

Now a rank map decides the order of ids in ObjectMap
Map rankedMap = new HashMap()

rankedMap .put(rank1,id3);
rankedMap .put(rank2,id4);
rankedMap .put(rank3,id1);
rankedMap .put(rank4,id2);

Now I have to arrange the ObjectMap objects accoding to the rank of each ids like
ObjectMap .put(id3,Obj1);
ObjectMap .put(id4,Obj2);
ObjectMap .put(id1,Obj3);
ObjectMap .put(id2,Obj4);

ids are Long objects
ranks are int objects
Please help Thanks in advance

A: The 'rankedMap' should be a linked map, as said above:
Map rankedMap = new LinkedHashMap()

rankedMap .put(rank1,id3);
rankedMap .put(rank2,id4);
rankedMap .put(rank3,id1);
rankedMap .put(rank4,id2);

next, you can iterate over the ids in the rankedMap to fill the rankedObjectMap, which is also a linkedHashMap: (code not tested)
Map rankedObjectMap = new LinkedHashMap();
for(Object id : rankedMap.values()){
  rankedObjectMap.put(id, objectMap.get(id));
}

A: HashMap has no defined ordering. If you want ordering, and still benefit the O(1) seek time the HashMap offers, you might want to use LinkedHashMap, but note that ordering in this map is defined by order of insertions. You will have to take care of it by inserting your elements in order.

A: You can try with TreeMaps and custom Comparators.


text:
Q: Limit of number of nodes in Hyperledger In Hyperledger-fabric blockchain, is there a limit to the number of nodes participating in a network? If yes, how many nodes can be in a network?

A: To get the complete functionality of blockchain(consensus mechanism, hyperledger fabric uses PBFT consensus which means it will accept any transaction to be valid if more than 66% of the nodes are up and running.
In short more than 66% of nodes must be up and must validate the order to requests in Hyperledger farbic.
Both the Starter Developer plan and the High Security Business Network plan enable you to test the Practical Byzantine Fault Tolerance (PBFT) consensus protocol on a four-node blockchain network
Consensus is a method for validating the order of requests, or transactions (deploy and invoke), on a blockchain network. The correct ordering of transactions is critical, because many transactions have a dependency on one or more prior transactions (account debits often have a dependency on prior credits, for example).
The network can tolerate no more than one Byzantine node. Each network contains N=4 nodes, so applying the formula for the maximum number of tolerated Byzantine nodes results in: f=(4-1)/3=1. If two or more Byzantine nodes (f>1) exist, a the 4-node PBFT network cannot guarantee consistency or integrity of the ledger across all nodes. (For comparison, tolerating two Byzantine nodes would require f=(7-1)/3=2, or a minimum 7-node PBFT blockchain network.)

A: In Hyperledger Fabric, nodes can be of type orderers, endrosing peers or clients. Are you asking about a number of Byzantine nodes, or the number of nodes in general?

*

*If you are asking about how many Byzantine nodes, then the precise answer is as follows: a) There is no limit on Byzantine peers and clients. If there are too many of them, a client just won't be able to get his transaction endorsed. However the integrity of the system is not endangered. b) Since the consensus algorithm is run between the orderers, then the limit depends on that specific algorithm used. Remember Hyperledger Fabric supports pluggable consensus, meaning that the consensus algorithm is not necessarily hardcoded. In its current implementation, Hypeledger Fabric runs "Kafka" which is NOT Byzantine-Fault tolerant. This means that even one Byzantine orderer can compromise the whole system! However, there are plans for BFT-Smart which is Byzantine-Fault tolerant and supports up to 33% faulty nodes, as the above answer says.

*If you are asking about the total number of nodes, then the precise answer is as follows: a) There is (theoretically) no limit on the number of clients-peers. b) The practical limit of orderers again depends on the consensus. For BFT, this translates up to practically 10 (maybe 20) orderers. c) The practical limit of peers depends on the network latency. The Hyperledger paper by Androulaki et al. has an evaluation up to 100 peers showing its performance in a WAN and a LAN environment.


text:
Q: WildFly vs. Payara JSON response - what is standard behavior? In a small demo JAX-RS application, I had the following POJO:
public class Book {
    private String title;
    private String author;
    private int year;

    // only this constructor, no default
    public Book(String title, String author, int year) {
        this.title = title;
        this.author = author;
        this.year = year;
    }

    // getters for members, no setters
    ...
}

I used this as a response within a REST operation:
@GET
@Path("books")
@Produces(MediaType.APPLICATION_JSON)
public List<Book> getBooks() {
    List<Book> books = new ArrayList<>();
    // add some books via Book constructor
    ...
    return books;
}

The application ran perfectly on WildFly 10, producing a JSON output of the book objects.
The very same war deployed on a recent Payara, got me an exception in server log:
MessageBodyWriter not found for media type=application/json

After adding a default constructor and @XmlAccessorType(XmlAccessType.FIELD) (or setters, which I ommited for fuctional design reasons), it worked.
All this lead me to 2 questions:

*

*Why is the behavior different and which container does something non-standard or additionally?

*Is there a recommended way for either using data objects such as my Book class as responses and let it convert to JSON automatically (with of course an additionally http response code) or like shown in many examples instead building the JSON response object manually?

A: Unfortunately, the mapping of Java objects to/from JSON is not defined yet in Java EE, therefore both WildFly and Payara Server behavior is by definition not standard. It is planned to be defined by the JSON-Binding JSR, which will be included in Java EE 8. Most of the implementations right now use JAX-B for mapping, but that was designed for mapping between Java and XML and doesn't work without issues for JSON.
By default, Payara Server uses Moxy to map to/from JSON. You can force using Jackson for example, if you add Jackson to your app and add JacksonFeature into JAX-RS classes: Force Glassfish4 to use Jackson instead of Moxy
If you want your application behave in standard way all the time, you would need to configure JAX-RS to use your own MessageBodyWriter/Reader.


text:
Q: How can I change the resolution of the GRUB menu? I'd like to change my GRUB's resolution since it seems as if it doesn't use my screen's whole 1920x1080. I tried to get the supported resolutions using videoinfo, but it literally shows nothing. I tried vbeinfo as well, but that didn't work either.
Looking forward to a solution for this or at least a way to tell which resolution GRUB is actually using at the moment.
This is how my GRUB config file looks:
GRUB_TIMEOUT=8
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX="nouveau.modeset=0"
GRUB_GFXMODE=1920x1080

A: the default look of my grub menu when the some of the content in /etc/default/grub file is
GRUB_DEFAULT=0
GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""
#GRUB_GFXMODE=640X480

When i edited the file and changed some of the content in /etc/default/grub like below
GRUB_DEFAULT=0
GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""
GRUB_GFXMODE=640X480

and run sudo update-grub it looks like this

when content is like this
GRUB_DEFAULT=0
GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT=10
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""
GRUB_GFXMODE=960X600

It looks like this after running sudo update-grub

The value 960x600 i choose from below
pratap@i7-6550U:~$ xrandr
Screen 0: minimum 320 x 200, current 1366 x 768, maximum 8192 x 8192
eDP-1 connected primary 1366x768+0+0 (normal left inverted right x axis y axis) 344mm x 194mm
   1366x768      60.00*+
   1360x768      59.80    59.96
   1280x720      60.00    59.99    59.86    59.74
   1024x768      60.04    60.00
   960x720       60.00
   928x696       60.05
   896x672       60.01
   1024x576      59.95    59.96    59.90    59.82
   960x600       59.93    60.00
   960x540       59.96    59.99    59.63    59.82
   800x600       60.00    60.32    56.25
   840x525       60.01    59.88
   864x486       59.92    59.57
   800x512       60.17
   700x525       59.98
   800x450       59.95    59.82
   640x512       60.02
   720x450       59.89
   700x450       59.96    59.88
   640x480       60.00    59.94
   720x405       59.51    58.99
   684x384       59.88    59.85
   680x384       59.80    59.96
   640x400       59.88    59.98
   576x432       60.06
   640x360       59.86    59.83    59.84    59.32
   512x384       60.00
   512x288       60.00    59.92
   480x270       59.63    59.82
   400x300       60.32    56.34
   432x243       59.92    59.57
   320x240       60.05
   360x202       59.51    59.13
   320x180       59.84    59.32
HDMI-1 disconnected (normal left inverted right x axis y axis)
pratap@i7-6550U:~$

A: You can use 1920x1080 screen size but you will want to generate a larger font. Although the following GIF uses grub themes for additional graphics, generating larger 24 or 36 point fonts is the same for regular grub.

Make Grub fonts
Even if you are just using regular grub, if you want a different font you must use grub-mkfont program first. The same holds true for Grub Customizer used by OP and Grub Themes used in first section of this answer.
Here are the fonts I have made for grub to use:
$ ll /usr/share/grub/themes/Tuxkiller2/*.pf2
-rwxrwx--- 1 root root 176923 Jun  9 16:41 /usr/share/grub/themes/Tuxkiller2/dejavu_14.pf2*
-rwxrwx--- 1 root root  20041 Jun  9 16:41 /usr/share/grub/themes/Tuxkiller2/droidlogo_bold_17.pf2*
-rwxrwx--- 1 root root  23339 Jun  9 16:41 /usr/share/grub/themes/Tuxkiller2/droidlogo_bold_20.pf2*
-rwxrwx--- 1 root root  31498 Jun  9 16:41 /usr/share/grub/themes/Tuxkiller2/droidlogo_bold_26.pf2*
-rwxrwx--- 1 root root  15244 Jun  9 16:41 /usr/share/grub/themes/Tuxkiller2/droidlogo_regular_12.pf2*
-rwxrwx--- 1 root root  19148 Jun  9 16:41 /usr/share/grub/themes/Tuxkiller2/droidlogo_regular_17.pf2*
-rwxrwx--- 1 root root 113623 Jul 11 17:05 /usr/share/grub/themes/Tuxkiller2/ubuntu_bold_italic_36.pf2*
-rwxrwx--- 1 root root  45391 Jul 11 17:08 /usr/share/grub/themes/Tuxkiller2/ubuntu_light_20.pf2*
-rwxrwx--- 1 root root  41020 Jul 11 17:16 /usr/share/grub/themes/Tuxkiller2/ubuntu_regular_18.pf2*
-rwxrwx--- 1 root root  46423 Jul 11 17:16 /usr/share/grub/themes/Tuxkiller2/ubuntu_regular_20.pf2*
-rwxrwx--- 1 root root  68602 Jul 11 16:59 /usr/share/grub/themes/Tuxkiller2/ubuntu_regular_28.pf2*

To create a font use the grub-mkfont program like this guide outlines: Increase Font in GRUB for High DPI Screens:
sudo grub-mkfont --output=/boot/grub/fonts/DejaVuSansMono24.pf2 \
  --size=24 /usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf

Then in your /etc/default/grub configuration file tell it to use the new .pf2 font file:
# More readable font on high dpi screen, generated with
# sudo grub-mkfont --output=/boot/grub/fonts/DejaVuSansMono24.pf2 \
#    --size=24 /usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf
GRUB_FONT=/boot/grub/fonts/DejaVuSansMono24.pf2

Finally run:
sudo update-grub


text:
Q: field not appearing in lightning-datatable from query in controller I am working on a datatable to create a user view and bring in permissionSetAssignments related to the user record page for each user by AssigneeId
I am able to get the table to populate as if there was data there with the correct assignments but the PermissionSet.Name field is appearing blank as if the data is there, but invisible from the query.
Controller, method in question: getPermissionSets
public class UserDataTableController {

    @AuraEnabled(cacheable=true)

    public static List<User> getUsers(string str){

        String name ='%'+str+'%';

        return [SELECT Id, Name, Email, Username, ATTUID__c, FederationIdentifier FROM User

        WHERE Name like :name LIMIT 20];

    }

    @AuraEnabled(cacheable=true)

    public static List<PermissionSetAssignment> getPermissionSets(String recordId){

        return [SELECT Id, PermissionSetId, PermissionSet.Name, PermissionSet.ProfileId, PermissionSet.Profile.Name, AssigneeId, Assignee.Name

        FROM PermissionSetAssignment WHERE AssigneeId = :recordId];

    }

}

.js
import {LightningElement, wire, track, api} from 'lwc';

// importing apex class methods

import getPermissionSets from '@salesforce/apex/UserDataTableController.getPermissionSets';

// datatable columns with row actions

const columns = [

    {
        label: 'Permission Set Name',
        fieldName: 'PermissionSet.Name'
    }

];

export default class GetPermSetDisplay extends LightningElement {

    @track data;
    @track columns = columns;
    @api recordId;

    // retrieving the data using wire service

    @wire(getPermissionSets, {recordId: '$recordId'})
    permissions(result) {
        if (result.data) {
            this.data = result.data;
            this.error = undefined;

        } else if (result.error) {
            this.error = result.error;
            this.data = undefined;
        }
    }
}

HTML:
<template>

    <lightning-card title="Permission Set Assignments">

        <lightning-datatable data={data} columns={columns} key-field="Id">

        </lightning-datatable>

    </lightning-card>

</template>

Output:

A: Datatable displays simple fields directly accessible in the row of data you're passing it. It doesn't understand dots to go "up". You'll need to simplify, flatten the data

*

*you could create helper wrapper class in apex, populate bunch of string etc. fields in that and return that

*or do similar flattening in js as you process the wire's results

*or consider rewriting the query. Maybe something like
select name
from permissionset
where id in (select permissionsetid
   from PermissionSetAssignment
   where assigneeid =...)


text:
Q: copy and pasting to the next empty row I have this following code which copies BX2 to BX400 from "copySheet" and pastes it to first empty row in Column A of "pasteSheet".
 copySheet.Range("BX2:BX400").Copy
 pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial  xlPasteValues

Which code pastes it to first empty row in Column B then ?

A: If you are only concerned with pasting the values then direct value transfer is preferred as it does not involve the clipboard.
with copySheet.Range("BX2:BX400")
    pasteSheet.Cells(Rows.Count, "B").End(xlUp).Offset(1, 0).resize(.rows.count, .columns.count) = .value
end with


text:
Q: How to execute BaseClass method before it gets overridden by DerivedClass method in Python I am almost sure that there is a proper term for what I want to do but since I'm not familiar with it, I will try to describe the whole idea explicitly. So what I have is a collection of classes that all inherit from one base class. All the classes consist almost entirely of different methods that are relevant within each class only. However, there are several methods that share similar name, general functionality and also some logic but their implementation is still mostly different. So what I want to know is whether it's possible to create a method in a base class that will execute some logic that is similar to all the methods but still continue the execution in the class specific method. Hopefully that makes sense but I will try to give a basic example of what I want.
So consider a base class that looks something like that:
class App(object):

    def __init__(self, testName):
        self.localLog = logging.getLogger(testName)

    def access(self):
        LOGIC_SHARED

And an example of a derived class:
class App1(App):

    def __init__(self, testName):
        . . .
        super(App1, self).__init__(testName)

    def access(self):
        LOGIC_SPECIFIC

So what I'd like to achieve is that the LOGIC_SHARED part in base class access method to be executed when calling the access method of any App class before executing the LOGIC_SPECIFIC part which is(as it says) specific for each access method of all derived classes.
If that makes any difference, the LOGIC_SHARED mostly consists of logging and maintenance tasks.
Hope that is clear enough and the idea makes sense.
NOTE 1:
There are class specific parameters which are being used in the LOGIC_SHARED section.
NOTE 2:
It is important to implement that behavior using only Python built-in functions and modules.
NOTE 3:
The LOGIC_SHARED part looks something like that:
try:
    self.localLog.info("Checking the actual link for %s", self.application)
    self.link = self.checkLink(self.application)
    self.localLog.info("Actual link found!: %s", self.link)
except:
    self.localLog.info("No links found. Going to use the default link: %s", self.link)

So, there are plenty of specific class instance attributes that I use and I'm not sure how to use these attributes from the base class.

A: The easiest method to do what you want is to simply call the parent's class access method inside the child's access method.
class App(object):
    def __init__(self, testName):
        self.localLog = logging.getLogger(testName)

    def access(self):
        LOGIC_SHARED

class App1(App):
    def __init__(self, testName):
        super(App1, self).__init__(testName)

    def access(self):
        App.access(self)
        # or use super
        super(App1, self).access()

However, your shared functionality is mostly logging and maintenance. Unless there is a pressing reason to put this inside the parent class, you may want to consider is to refactor the shared functionality into a decorator function. This is particularly useful if you want to reuse similar logging and maintenance functionality for a range of methods inside your class.
You can read more about function decorators here: http://www.artima.com/weblogs/viewpost.jsp?thread=240808, or here on Stack Overflow: How to make a chain of function decorators?.
def decorated(method):
    def decorated_method(self, *args, **kwargs):
        LOGIC_SHARED
        method(self, *args, **kwargs)
    return decorated_method

Remember than in python, functions are first class objects. That means that you can take a function and pass it as a parameter to another function. A decorator function make use of this. The decorator function takes another function as a parameter (here called method) and then creates a new function (here called decorated_method) that takes the place of the original function.
Your App1 class then would look like this:
class App1(App):
    @logged
    def access(self):
        LOGIC_SPECIFIC

This really is shorthand for this:
class App1(App):
    def access(self):
        LOGIC_SPECIFIC

decorated_access = logged(App.access)
App.access = decorated_access

I would find this more elegant than adding methods to the superclass to capture shared functionality.

A: Sure, just put the specific logic in its own "private" function, which can overridden by the derived classes, and leave access in the Base.
class Base(object):
    def access(self):
        # Shared logic 1
        self._specific_logic()
        # Shared logic 2

    def _specific_logic(self):
        # Nothing special to do in the base class
        pass

        # Or you could even raise an exception
        raise Exception('Called access on Base class instance')

class DerivedA(Base):
    # overrides Base implementation
    def _specific_logic(self):
        # DerivedA specific logic

class DerivedB(Base):
    # overrides Base implementation
    def _specific_logic(self):
        # DerivedB specific logic

def test():
    x = Base()
    x.access()           # Shared logic 1
                         # Shared logic 2

    a = DerivedA()
    a.access()           # Shared logic 1
                         # Derived A specific logic
                         # Shared logic 2

    b = DerivedB()
    b.access()           # Shared logic 1
                         # Derived B specific logic
                         # Shared logic 2

A: If I understand well this commment (How to execute BaseClass method before it gets overridden by DerivedClass method in Python) you want that additional arguments passed to the parent class used in derived class
based on Jonathon Reinhart's answer
it's how you could do
class Base(object):
    def access(self,
                    param1 ,param2, #first common parameters
                    *args,          #second positional parameters
                    **kwargs        #third keyword arguments
               ):
        # Shared logic 1
        self._specific_logic(param1, param2, *args, **kwargs)
        # Shared logic 2

    def _specific_logic(self, param1, param2, *args, **kwargs):
        # Nothing special to do in the base class
        pass

        # Or you could even raise an exception
        raise Exception('Called access on Base class instance')

class DerivedA(Base):
    # overrides Base implementation
    def _specific_logic(self, param1, param2, param3):
        # DerivedA specific logic

class DerivedB(Base):
    # overrides Base implementation
    def _specific_logic(self, param1, param2, param4):
        # DerivedB specific logic

def test():
    x = Base()

    a = DerivedA()
    a.access("param1", "param2", "param3")           # Shared logic 1
                                                     # Derived A specific logic
                                                     # Shared logic 2

    b = DerivedB()
    b.access("param1", "param2", param4="param4")   # Shared logic 1
                                                    # Derived B specific logic
                                                    # Shared logic 2

A: I personally prefer Jonathon Reinhart's answer, but seeing as you seem to want more options, here's two more. I would probably never use the metaclass one, as cool as it is, but I might consider the second one with decorators.
With Metaclasses
This method uses a metaclass for the base class that will force the base class's access method to be called first, without having a separate private function, and without having to explicitly call super or anything like that. End result: no extra work/code goes into inheriting classes.
Plus, it works like maaaagiiiiic </spongebob>
Below is the code that will do this. Here http://dbgr.cc/W you can step through the code live and see how it works :
#!/usr/bin/env python

class ForceBaseClassFirst(type):
    def __new__(cls, name, bases, attrs):
        """
        """
        print("Creating class '%s'" % name)

        def wrap_function(fn_name, base_fn, other_fn):
            def new_fn(*args, **kwargs):
                print("calling base '%s' function" % fn_name)
                base_fn(*args, **kwargs)
                print("calling other '%s' function" % fn_name)
                other_fn(*args, **kwargs)

            new_fn.__name__ = "wrapped_%s" % fn_name
            return new_fn

        if name != "BaseClass":
            print("setting attrs['access'] to wrapped function")
            attrs["access"] = wrap_function(
                "access",
                getattr(bases[0], "access", lambda: None),
                attrs.setdefault("access", lambda: None)
            )

        return type.__new__(cls, name, bases, attrs)

class BaseClass(object):
    __metaclass__ = ForceBaseClassFirst

    def access(self):
        print("in BaseClass access function")

class OtherClass(BaseClass):
    def access(self):
        print("in OtherClass access function")

print("OtherClass attributes:")
for k,v in OtherClass.__dict__.iteritems():
    print("%15s: %r" % (k, v))

o = OtherClass()

print("Calling access on OtherClass instance")
print("-------------------------------------")
o.access()

This uses a metaclass to replace OtherClass's access function with a function that wraps a call to BaseClass's access function and a call to OtherClass's access function. See the best explanation of metaclasses here https://stackoverflow.com/a/6581949.
Stepping through the code should really help you understand the order of things.
With Decorators
This functionality could also easily be put into a decorator, as shown below. Again, a steppable/debuggable/runnable version of the code below can be found here http://dbgr.cc/0
#!/usr/bin/env python

def superfy(some_func):
    def wrapped(self, *args, **kwargs):
        # NOTE might need to be changed when dealing with
        # multiple inheritance
        base_fn = getattr(self.__class__.__bases__[0], some_func.__name__, lambda *args, **kwargs: None)

        # bind the parent class' function and call it
        base_fn.__get__(self, self.__class__)(*args, **kwargs)

        # call the child class' function
        some_func(self, *args, **kwargs)

    wrapped.__name__ = "superfy(%s)" % some_func.__name__
    return wrapped

class BaseClass(object):
    def access(self):
        print("in BaseClass access function")

class OtherClass(BaseClass):
    @superfy
    def access(self):
        print("in OtherClass access function")

print("OtherClass attributes")
print("----------------------")
for k,v in OtherClass.__dict__.iteritems():
    print("%15s: %r" % (k, v))
print("")

o = OtherClass()

print("Calling access on OtherClass instance")
print("-------------------------------------")
o.access()

The decorator above retrieves the BaseClass' function of the same name, and calls that first before calling the OtherClass' function.

A: May this simple approach can help.
class App:

    def __init__(self, testName):

        self.localLog = logging.getLogger(testName)

        self.application = None
        self.link = None

    def access(self):
        print('There is something BaseClass must do')
        print('The application is ', self.application)
        print('The link is ', self.link)

class App1(App):

    def __init__(self, testName):

        # ...
        super(App1, self).__init__(testName)

    def access(self):
        self.application = 'Application created by App1'
        self.link = 'Link created by App1'

        super(App1, self).access()

        print('There is something App1 must do')

class App2(App):

    def __init__(self, testName):

        # ...
        super(App2, self).__init__(testName)

    def access(self):
        self.application = 'Application created by App2'
        self.link = 'Link created by App2'

        super(App2, self).access()

        print('There is something App2 must do')

and the test result:
>>>
>>> app = App('Baseclass')
>>> app.access()
There is something BaseClass must do
The application is  None
The link is  None
>>> app1 = App1('App1 test')
>>> app1.access()
There is something BaseClass must do
The application is  Application created by App1
The link is  Link created by App1
There is something App1 must do
>>> app2 = App2('App2 text')
>>> app2.access()
There is something BaseClass must do
The application is  Application created by App2
The link is  Link created by App2
There is something App2 must do
>>>

A: Adding a combine function we can combine two functions and execute them one after other as bellow
def combine(*fun):
    def new(*s):
        for i in fun:
            i(*s)
    return new

class base():
    def x(self,i):
        print 'i',i

class derived(base):
    def x(self,i):
        print 'i*i',i*i
    x=combine(base.x,x)

new_obj=derived():
new_obj.x(3)

Output Bellow
i 3
i*i 9

it need not be single level hierarchy it can have any number of levels or nested


text:
Q: Is there a way to see a user's top tags relative to the global frequency of each tag? I'm talking about the tags at the bottom of the info->stats page.
For example, let's say my #3 tag is C# and my #10 tag is LISP. However, C# occurs much more frequently on SO, so relatively I'm stronger in LISP than most users, but not necessarily stronger in C# than most users. Is there a way to see these counters in a relative way?

A: If you hover over the tag, there is a "Top Users" link at the bottom of the pop-up. Is that what you want?

If you don't mind working with slightly old data, you could try running a query on SEDE to find out.
This query will list all the tags where you have a score of 1 or more and how many other users are doing better than you in it. Unfortunately it can get quite slow, if anyone has ideas on how to improve the performance, I'm happy to hear them.