text:
Q: How to set the dependence to a plugin inside another plugin in Cakephp 4? I'm creating a plugin FileManager in cakephp4. (This plugin is in app/plugins/FileManager)
This plugin has an UploaderHelper that contains a method to generate an input file + the files that are associated to the field.
In this method I'm using the plugin CakephpGlide (https://github.com/ADmad/cakephp-glide) to display thumbnails of the images that are associated to the field.
How can I set up properly the dependence to the plugin CakephpGlide in my plugin FileManager ?
Note that I also use CakephpGlide in my Application (e.g outside of FileManager).
For now, I've only added in app/plugins/FileManager/composer.json a line in require  :
"require": {
        "php": ">=7.2",
        "admad/cakephp-glide": "^5.0", // This one
        "cakephp/cakephp": "^4.3"
    },

Is there something else to do ?
I mean should I have to only write in the doc of my FileManager the way to configure CakephpGlide (in routes and AppView of the user's App) ?
And where will be stored the plugin admad/cakephp-glide in this way ? in app/vendors or in app/plugins/FileManager/vendors ?
I'm a bit confused..

A: If you do not distribute your plugin / make it a standalone plugin, then all the files in your plugin's root are irrelevant, you could delete them and everything would still run fine.
A first party plugin in the /plugins/ folder is part of your application, and therefore your application level composer.json should know about and require the dependencies for it.


text:
Q: I need to calculate percentage of counted items I have two tables:
1st: reasons
id   |   title
---------------------------------
1    |   Customer didn't like it
2    |   Needs improving
3    |   Wrong format

2nd: projects
id   |   title       |   rejected
------------------------------------
1    |   Priject 1   |   Null
2    |   Priject 2   |   1
3    |   Priject 3   |   1
4    |   Priject 4   |   Null
5    |   Priject 5   |   2

I need to display Reasons.Title and number of project rejected for that reason. I've managed to join those tables together, with this code
SELECT reasons.title as title, count(*) as num
FROM reasons
LEFT JOIN reasons on projects.rejected = reasons.id
WHERE projects.rejectedIS NOT NULL
GROUP BY projects.rejected

Now I need to add percentage, so my final table looks like this
title                    |   num   |  percentage
--------------------------------------------------
Customer didn't like it  |   2     |  66,6
Needs improving          |   1     |  33,3

The format of percentage is of course not important.
I would like to get this done with MySql, so I do not need to use two queries and extra PHP, but if there is another solution, other from MySql, I'm open to suggestions

A: You can do this by getting the total in the FROM clause:
SELECT r.title as title, count(*) as num,
       COUNT(*) / pp.cnt as ratio
FROM reasons r JOIN
     projects p
     ON p.rejected = r.id CROSS JOIN
     (SELECT COUNT(*) as cnt FROM projects p WHERE rejects IS NOT NULL) pp
GROUP BY r.title, pp.cnt;

Notes:

*

*This fixes the table names, so the query has a projects table.

*This removes the WHERE because it is not needed.

*This changes the LEFT JOIN to an inner join.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django Web Application, Facebook login I am building a basic social media web application and I would like my only login point to be via facebook login. After doing a fare amount of research, I have seen multiple third party authorization frameworks that plug in with facebook, but I was wondering if there were any opinions on what the best foot forward would be.
Additionally, how would I go about still being able to use sessions/cookies within Django if I use fb login?
All answers are appreciated!

A: You can use SocialAuth (https://github.com/python-social-auth/social-app-django), this app allows you to let users log in via many common SocialMedia-accounts, e.g. facebook. Upon login, the app will create a user in your database, which you can then use as if the user logged in with a local account. Therefore, the session will still be handled by django, fb only sends you some information about the user (e.g. first- and lastname, email, etc. [configurable in your settings.py])


text:
Q: Constraints problem with HTML element drag I made script for dragging element around my react application in the way that limits are parent container. I achieved what I want but not in the way I want. I want when I reach limits to block that axis from trying to go further to avoid this annoying effect of script calculating and returning div in position.

const drag = (id) => {
    const element = document.getElementById(id);
    const parent = element.parentNode;

    let newState = { x: 0, y: 0 };
    let oldState = { x: 0, y: 0 };

    const dragElement = (e) => {
      e = e || window.event;
      e.preventDefault();
      oldState.x = e.clientX;
      oldState.y = e.clientY;
      document.onmouseup = stopDrag;
      document.onmousemove = startDrag;
    };

    const startDrag = (e) => {
      e = e || window.event;
      e.preventDefault();
      newState.x = oldState.x - e.clientX;
      newState.y = oldState.y - e.clientY;
      oldState.x = e.clientX;
      oldState.y = e.clientY;

      const handleX = () => {
        let x = 0;

        if (element.offsetLeft < 0) {
          x = 0;
        } else if (element.offsetLeft + element.offsetWidth > parent.offsetWidth) {
          x = parent.offsetWidth - element.offsetWidth;
        } else {
          x = element.offsetLeft - newState.x;
        }

        return `${x}px`;
      };

      const handleY = () => {
        let y = 0;

        if (element.offsetTop < 0) {
          y = 0;
        } else if (element.offsetTop + element.offsetHeight > parent.offsetHeight) {
          y = parent.offsetHeight - element.offsetHeight;
        } else {
          y = element.offsetTop - newState.y;
        }

        return `${y}px`;
      };

      element.style.top = handleY();
      element.style.left = handleX();
    };

    const stopDrag = () => {
      document.onmouseup = null;
      document.onmousemove = null;
    };

    if (document.getElementById(element.id + "Header")) {
      document.getElementById(element.id + "Header").onmousedown = dragElement;
    } else {
      element.onmousedown = dragElement;
    }
  };

drag("test");
.parent {
display: flex;
justify-content: center;
align-items: center;
position: absolute;
inset: 16px;
background: red;
}

.draggable {
position: absolute;
width: 50px;
height: 50px;
background: green;
}


text:
Q: UIAlertController backgroundColor washed out trying to set a UIAlertController backgroundColor but the result is a "washed out" color
let alert = UIAlertController(title: "some title", message: "(tap to continue)", preferredStyle: .Alert)
            self.presentViewController(alert, animated: true, completion:{

                let subview = alert.view.subviews.first! as UIView
                let alertContentView = subview.subviews.first! as UIView
                alertContentView.backgroundColor = UIColor.yellowColor()

By "washed out" I mean it's not bright yellow but more like a faded yellow color...
Any ideas?

A: Ideas?  Well, somewhere in Apple's internal hierarchy of layers and views, something is semi-transparent.  You might track down what it is, but you are treading dangerous ground here.  The Apple docs explicitly state

You cannot customize the appearance of alert views.

so even if you solve this, it might not work on all iOS versions or all devices.  If you need to customize the appearance don't use Alert Views; create your own Modal View instead.


text:
Q: Weird insertion times into MongoDB I need to save lots of sensor measurements and I'm doing some benchmarks on MongoDB.
The data:
This is the "schema" I'm using:
public class BetterConsolidatedTag
{
    public ObjectId Id { get; set; }

    /// <summary>
    /// The base time to which the offset values relate.
    /// </summary>
    public DateTime BaseTime { get; set; }

    /// <summary>
    /// The name of the data series
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// Values of the series in this time frame. The values are saved as offsets in milliseconds from the BaseTime.
    /// </summary>
    [BsonElement]
    private SortedDictionary<int, object> OffsetValues { get; set; }
}

The idea is that instead of saving each measurement by itself I consolidate all the measurements for a specific sensor over an hour. So each document represents all the measurements for a specific sensor over an hour which starts on BaseTime.
There are two indexes defined: BaseTime_1_Name_1 and Name_1_BaseTime_1.
The database
MongoDB is running on Windows Server 2012 R2 Standard with the following hardware:

*

*Processor:   Intel(R) Xeon(R) CPU           X5675  @ 3.07GHz, 3059 Mhz, 6 Core(s), 12 Logical Processor(s)

*RAM: 96GB

*Disk: 300GB local disk with RAID 1 (IBM ServeRAID M5015)

*Network: Intel® 82575EB Gigabit Ethernet Controller

The benchmark
For simplicity, my simulation generates data at a constant rate - I generate data which represents an hour for all the different sensors and save it to the database. I log the time it takes to save this one-hour data (which as mentioned above, contains the same number of samples each time).
The data generation was on my desktop (Windows 7 Enterprise, i7, 8GB RAM, SSD) which sent the data to the MongoDB server over the network using the official MongoDB C# driver. I didn't do anything special with the desktop during the test - mainly internet browsing and plotting the measurements in Excel from time to time. No one but me was connected to the remote server during this time and no one but my benchmark was connected to the MongoDB during the benchmarking.
The results
This is a graph depicting insert time (in ms) as a function of the total number of samples in the database (the total size of the DB is about 200GB, saved across 101 files):

And with some zoom:

I'm having trouble understanding these results. I expected the insertion time to grow slightly over time - there are two indexes and as number of documents increases it's to be expected that maintaining these indexes takes longer. Also, I expected that once data doesn't fit into physical memory anymore and paging begins to occur more frequently the insertion times should become much higher, but the graph doesn't look like there's a single point in time when things get worse.
And what I really don't understand is why this graph looks as if it's made up of three different graphs -
 - One which grows very slowly, and holds almost all the data points (this is what I expected all the results to look like)
 - One which grows faster and holds less points (maybe these are the times when paging occurs? But it's expect a "jump" in the graph at the point where physical memory got filled up)
- One which grows insanely and holds about 40 data points. These data points seem to occur at a constant rate of about every 15 minutes. I thought perhaps these are the times MongoDB creates a new file but the data is saved across 101 files while there are only about 40 of these weird measurements.
Do these results make any sense? If not, what might be the problem? Should I look for mysterious background jobs on the server? A hardware problem?
EDIT: It doesn't make sense that the high points correspond to file creation because it shouldn't take more time to create files as data gets larger. Maybe there's some sort of compaction MongoDB is doing in the background? Something along the lines of most of the time small compactions (the second "graph" and sometimes full compactions (the third and highest "graph"). It would make sense that compaction takes longer as data grows larger. Or maybe garbage collection, which can also be represented by such behavior, I guess?
EDIT 2: Well, MongoDB is written in C++ so I guess GC is out of the question. So right now background compaction is my best guess.

A: By default MongoDB performs fsync once in a minute, so once in a minute you will have much slower insert - that's the point when data is actually saved to the disk, the rest of the time it's saved only in memory. Set it to sync data every second (or on every write if possible) and the graph will look different.


text:
Q: Bootstrap menu covering page content I'd like to use a menu bar with Bootstrap that always stays on top of the page. Therefore I used the class navbar-fixed-top. I used the code from the very end of this post and ran into a problem with visibility of my content
The main content is partly overlapped by the menue.

On http://getbootstrap.com/examples/starter-template/ the problem is "solved" by adding padding-top: 50px; to the body. But this does not work, when the menu is wrapping and becomes larger than 50px:

Is there a class in bootstrap that covers this problem? Or do I have to add a JavaScript that listens to changes of the window-size and adjusts the padding-top? I have no idea how to do that, but that's the only thing that came to my mind,...
CODE:
<!doctype html>

    <meta charset="utf-8">
    <title>Bootstrap</title>
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                    Toggle navigation

                </button>
                Project name

Home

About

Contact

Item01

Item02

Item03

Item04

Item05

Item06

Item07

Item08

Item09

Item10

Item11

My first template

Dummy content, dummy content, dummy content, dummy content, dummy content, dummy content, dummy content, dummy content.

Dummy content, dummy content, dummy content, dummy content, dummy content, dummy content, dummy content, dummy content.

Dummy content, dummy content, dummy content, dummy content, dummy content, dummy content, dummy content, dummy content.

Contact us

A: I am unaware of a bootstrap class that fixes this problem. You could certainly add a listener to you window resize as you mentioned. It would solve the problem of your height not always being 50px. Should be something to the effect of:
$(window).on('resize', function(){
    var navHeight = $('nav').height();
    $('body').css('padding-top', navHeight + 'px');
});

This is untested, but should get you started. Hope this helps!

A: The thing is when you use "position: fixed" the element is taken out of the "flow" and is positioned relative to the window and not to the other elements. Therefore you must add a margin, like they have done in the bootstrap example, for the menu to not cover the underlying content. You can also add padding to body but I would prefer using margin on the element instead.
If you don't know the height of the menu on forehand I would recommend you use the answer @wrxsti wrote.

A: Give .navbar a margin-bottom within your CSS.  That should fix it.


text:
Q: Is it grammatically incorrect to not change past continuous to past perfect cont. in reported speech? "When Bill called me I was discussing the outcome of the project
with Jessie," said Daniel.
Daniel said he was discussing the outcome of the project with Jessie
when Bill called him.
Is this correct?


text:
Q: Multithreaded use of Core Data (NSOperationQueue and NSManagedObjectContext) In Apple's Core Data documentation for Concurrency with Core Data, they list the preferred method for thread safety as using a seperate NSManagedObjectContext per thread, with a shared NSPersistentStoreCoordinator.
If I have a number of NSOperations running one after the other on an NSOperationQueue, will there be a large overhead creating the context with each task?
With the NSOperationQueue having a max concurrent operation count of 1, many of my operations will be using the same thread. Can I use the thread dictionary to create one NSManagedObjectContext per thread? If I do so, will I have problems cleaning up my contexts later?
What's the correct way to use Core Data in this instance?

A: Operations started using NSOperationQueue using a maximum concurrent operation count of 1 will not run all operations on the same thread. The operations will be executed one after the other, but a new thread will be created every time.
So creating objects in the thread dictionary will be of little use.

A: While this question is old, it's actually at the top of Google's search results on 'NSMangedObjectContext threading', so, I'll just drop in a new answer.
The new 'preferred' method is to use the initWithConcurrencyType: and tell the MOC whether it's a main thread MOC or a secondary thread moc.  You can then use the new performBlock: and performBlockAndWait: methods on it and the MOC will take care of serializing operations on it's 'native' thread.
The issue then becomes how do you intelligently handle merging the data between the various MOCs your application may spawn, along with a thousand other details that make life 'fun' as a programmer.

A: The correct way to use Core Data in this case is to create a separate NSManagedObjectContext per operation or to have a single context which you lock (via -[NSManagedObjectContext lock] before use and -[NSManagedObjectContext unlock] after use). The locked approach might make sense if the operations are serial and there are no other threads using the context.
Which approach to use is an empirical question that can't be asnwered without data. There are too many variables to have a general rule. Hard numbers from performance testing are the only way to make an informed decision.


text:
Q: Proof of Batch Gradient Descent's cost function gradient vector In the book Hands-On Machine Learning with Scikit-Learn & TensorFlow, the author only showed the formula for the Batch Gradient Descent method, such as:
$ \dfrac{\partial}{\partial \theta_{j}} MSE(\theta)= \dfrac{2}{m}\sum_{i=1}^{m}(\theta^T \cdot \boldsymbol{x}^{(i)}-y^{(i)})\cdot x^{(i)}$
So that the gradient vector of the cost function is:
$\bigtriangledown_{\theta}MSE(\theta) = \begin{bmatrix} \dfrac{\partial}{\partial \theta_{0}} MSE(\theta_0) \\ \dfrac{\partial}{\partial \theta_{1}} MSE(\theta_1) \\ \dfrac{\partial}{\partial \theta_{2}} MSE(\theta_2) \\ \vdots \\ \dfrac{\partial}{\partial \theta_{n}} MSE(\theta_n) \end{bmatrix} = \dfrac{2}{m} \cdot X^T \cdot (X \cdot \theta - y)$
The MSE cost function is defined as:
$MSE(\theta) = \dfrac{1}{m}\sum_{i=1}^{m}(\theta^T \cdot \boldsymbol{x}^{(i)}-y^{(i)})^2$
Is there anyway who could kindly step by step show me the proof of the cost function's gradient vector formula (using linear algebra) above?

A: The cost function is given by
$$J = \dfrac{1}{N}\sum_{n=1}^{N}\left[\boldsymbol{w}^T\boldsymbol{x}_n-y_n \right]^2.$$
Take the total derivative
$$dJ = \dfrac{1}{N}\sum_{n=1}^N\{2\left[\boldsymbol{w}^T\boldsymbol{x}_n-y_n \right]d\boldsymbol{w}^T\boldsymbol{x}_n \}.$$
As $d\boldsymbol{w}^T$ is not dependent on the summation index $n$ we can pull it out of the sum. We can put it in front of $ \left[\boldsymbol{w}^T\boldsymbol{x}_n-y_n \right]$ because it is a scalar. Hence we obtain
$$dJ = d\boldsymbol{w}^T\left[\dfrac{1}{N}\sum_{n=1}^N\{2\left[\boldsymbol{w}^T\boldsymbol{x}_n-y_n \right]\boldsymbol{x}_n \}\right].$$
Now, we know that the term in the bracket is the gradient of $J$ with respect to $\boldsymbol{w}$. Hence,
$$\text{grad}_{\boldsymbol{w}}J=\dfrac{1}{N}\sum_{n=1}^N\{2\left[\boldsymbol{w}^T\boldsymbol{x}_n-y_n \right]\boldsymbol{x}_n \}.$$

The explanation for gradient and total derivative relationship.
Let $J(\boldsymbol{w})=J(w_0,w_1,...,w_m)$ be a multivariate function. The total derivative of $J$ is given by
$$dJ = \dfrac{\partial J}{\partial w_0}dw_0+\dfrac{\partial J}{\partial w_1}dw_1+\ldots+\dfrac{\partial J}{\partial w_m}dw_m$$
$$=[dw_0, dw_1,\ldots, dw_m][\dfrac{\partial J}{\partial w_0},\dfrac{\partial J}{\partial w_1},\ldots,\dfrac{\partial J}{\partial w_m}]^T$$
$$=d\boldsymbol{w}^T\text{grad}_{\boldsymbol{w}}J.$$

A: I like the children-explanation style, I don't understand any equations the other way. And I don't want to create new notation or use different notation that has already been created. Just the same as in the book.
So, let's start from the book notation
Equation 4-3. MSE cost function for a Linear Regression model
$MSE(\theta) = \dfrac{1}{m}\sum_{i=1}^{m}(\theta^T \cdot \boldsymbol{x}^{(i)}-y^{(i)})^2$
$\theta$ is the model's parameter vector
$y$ is the real value, $\hat{y}$ is the predicted value.
$x$ is the instance's feature vector, containing $x_0$ to $x_n$, with $x_0$ always equal to 1.
Equation 4-1. Linear Regression model prediction
$\hat{y}=\theta_0 + \theta_1x_1 + \theta_2x_2 + \dots + \theta_nx_n$
Equation 4-2. Linear Regression model prediction (vectorized form)
$\hat{y}=\theta^Tx$
Based on defeninition we can replace $\theta^Tx^{(i)}=\hat{y}$ (Equation 4-2):
$MSE(\theta) = \dfrac{1}{m}\sum_{i=1}^{m}(\hat{y}-y^{(i)})^2$
Equation 4-5. Partial derivatives of the cost function
$\frac{\partial}{\partial\theta_j}[MSE(\theta)]=\frac{\partial}{\partial\theta_j}[\frac{1}{m}\sum_{i=1}^{m} (\theta^Tx^{(i)}-y^{(i)})^2]$
So, let's find the derivative of one item in the Gradient Vector

*

*Move the const term (The constant factor rule)

$\frac{1}{m}(\frac{\partial}{\partial\theta_j}[\sum_{i=1}^{m} (\theta^Tx^{(i)}-y^{(i)})^2])$

*

*Apply the chain rule
often abridged to:
$\frac{d}{{dx}}[h(x)] = \frac{d}{{dg(x)}}[f(g(x))]\frac{d}{dx}[g(x)]$
$\frac{1}{m}(\sum_{i=1}^{m}\frac{\partial}{\partial[\theta^Tx^{(i)}-y^{(i)}]}[(\theta^Tx^{(i)}-y^{(i)})^2]\frac{\partial}{\partial\theta_j}[\theta^Tx^{(i)}-y^{(i)}])$

*Apply the power rule
$\frac{\partial}{\partial[\theta^Tx^{(i)}-y^{(i)}]}[(\theta^Tx^{(i)}-y^{(i)})^2]=2(\theta^Tx^{(i)}-y^{(i)})$

*Calculate the second term

$\frac{\partial}{\partial\theta_j}[\theta^Tx^{(i)}-y^{(i)}]=\frac{\partial}{\partial\theta_j}[\theta^Tx^{(i)}]-\frac{\partial}{\partial\theta_j}[y^{(i)}]$

*Apply the constant rule:

$\frac{\partial}{\partial\theta_j}[y^{(i)}]=0$

*Let's calculate $\frac{\partial}{\partial\theta_j}[\theta^Tx^{(i)}]$
Based on Equations 4-1 we have
$\frac{\partial}{\partial\theta_j}[\theta^Tx^{(i)}]=\frac{\partial}{\partial\theta_j}[\theta_0 + \theta_1x_1 + \theta_2x_2 + \dots + \theta_nx_n]$

*Apply the sum rule:

$\frac{\partial}{\partial\theta_j}[\theta_0 + \theta_1x_1 + \theta_2x_2 + \dots + \theta_nx_n]=\frac{\partial}{\partial\theta_j}[\theta_0] + \frac{\partial}{\partial\theta_j}[\theta_1x_1] + \dots + \frac{\partial}{\partial\theta_j}[\theta_jx_j] + \dots + \frac{\partial}{\partial\theta_j}[\theta_nx_n]$
So every term of this equation is 0 (see the constant rule), except term $j$!
$\frac{\partial}{\partial\theta_j}[\theta^Tx^{(i)}]=\frac{\partial}{\partial\theta_j}[\theta_jx_j^{(i)}]$

*Apply the the constant rule and special case of the power rule
$\frac{\partial}{\partial\theta_j}[\theta_jx_j^{(i)}]=x_j^{(i)}\frac{\partial}{\partial\theta_j}[\theta_j]=x_j^{(i)}$

*Join all the pieces together and simplify it a little

$\frac{1}{m}(\frac{\partial}{\partial\theta_j}[\sum_{i=1}^{m} (\theta^Tx^{(i)}-y^{(i)})^2])=\frac{1}{m}\sum_{i=1}^{m}2(\theta^Tx^{(i)}-y^{(i)})x_j^{(i)}=$
$\frac{2}{m}\sum_{i=1}^{m}(\theta^Tx^{(i)}-y^{(i)})x_j^{(i)}$

*Simplify the sum notation

We are pretty close to the goal, we need to make just several Linear Algebra steps, to reach it!
The key is the $x_j^{(i)}$ term. What does it mean inside the sum notation?
Per every feature vector, we take $j^{th}$ item. Let's visualize matrix $X$
$\begin{bmatrix}
        x^{(1)}_1 & x^{(2)}_1 & \dots  & x^{(m)}_1 \\
        x^{(1)}_2 & x^{(2)}_2 & \dots  & x^{(m)}_2 \\
        \vdots    & \vdots    & \ddots & \vdots \\
        x^{(1)}_j & x^{(2)}_j & \ddots & x^{(m)}_j \\
        \vdots    & \vdots    & \ddots & \vdots    \\
        x^{(1)}_m & x^{(2)}_m & \dots  & x^{(m)}_6
\end{bmatrix}$
You can see the row $j$ in this notation. How can we take a row instead of a column from our feature matrix? Just take the transpose!
$\frac{2}{m}\sum_{i=1}^{m}(\theta^Tx^{(i)}-y^{(i)})x_j^{(i)}=\frac{2}{m}X^T\sum_{i=1}^{m}(\theta^Tx^{(i)}-y^{(i)})$

*Let's calculate the gradient now

$\nabla_{\theta}{MSE(\theta)} = \begin{bmatrix}
        \frac{\partial}{\partial\theta_1}[MSE(\theta)] \\
        \frac{\partial}{\partial\theta_2}[MSE(\theta)] \\
        \vdots   \\
        \frac{\partial}{\partial\theta_m}[MSE(\theta)]
\end{bmatrix}=
\begin{bmatrix}
\frac{\partial}{\partial\theta_1}[\frac{1}{m}\sum_{i=1}^{m} (\theta^Tx^{(1)}-y^{(1)})^2] \\
\frac{\partial}{\partial\theta_2}[\frac{1}{m}\sum_{i=1}^{m} (\theta^Tx^{(2)}-y^{(2)})^2] \\
\vdots \\
\frac{\partial}{\partial\theta_m}[\frac{1}{m}\sum_{i=1}^{m} (\theta^Tx^{(m)}-y^{(m)})^2]
\end{bmatrix}=
\frac{2}{m}X^T\begin{bmatrix}
\sum_{i=1}^{m}(\theta^Tx^{(1)}-y^{(1)}) \\
\sum_{i=1}^{m}(\theta^Tx^{(2)}-y^{(2)}) \\
\vdots \\
\sum_{i=1}^{m}(\theta^Tx^{(m)}-y^{(m)})
\end{bmatrix}=
\frac{2}{m}X^T\begin{bmatrix}
    \theta^T\begin{bmatrix}
        \vdots & \vdots & \vdots & \vdots \\
        x^{(1)} & x^{(2)} & \dots & x^{(m)} \\
        \vdots & \vdots & \vdots & \vdots
    \end{bmatrix}-
    \begin{bmatrix}
        \vdots & \vdots & \vdots & \vdots \\
        y^{(1)} & y^{(2)} & \dots & y^{(m)} \\
        \vdots & \vdots & \vdots & \vdots
    \end{bmatrix}
\end{bmatrix}$
You can easily find that the result of
$\theta^T\begin{bmatrix}
        \vdots & \vdots & \vdots & \vdots \\
        x^{(1)} & x^{(2)} & \dots & x^{(m)} \\
        \vdots & \vdots & \vdots & \vdots
    \end{bmatrix}-
    \begin{bmatrix}
        \vdots & \vdots & \vdots & \vdots \\
        y^{(1)} & y^{(2)} & \dots & y^{(m)} \\
        \vdots & \vdots & \vdots & \vdots
    \end{bmatrix} = \theta^TX-Y$
is just a vector. So it's doesn't matter how you write it because of the matrix multiplication props!
$\theta^TX-Y \iff X\theta-Y$
The answer is!
$\nabla_{\theta}{MSE(\theta)} = \frac{2}{m}X^T (X\theta-Y)$


text:
Q: SSAS Cube: different calculation only for one company Here's my problem: I have an SSAS cube for multiple production companies. Company data is part of the "machine" dimension:
[Machine].[Company code]

Then I have two measures:
[Measures].[OEE] and [Measures].[OEE for company X]

In this case, I have to use the second measure for company X and the first measure for all other companies.
Is there a way to make a single measure which would display one measure for company X and another measure for other companies?

A: Several scenarios are possible (based on sources, underlying logic etc.)

*

*For physical measures based on columns. Create calculated column in Data Source View with T-SQL: case when {company X} then {column for this company} else {columns for other companies} end. Use it as a physical measure in cube.

*For both physical and calculated measures. Hide existing measures, create new calculated measure with MDX: IIF([Machine].[Company code].CurrentMember is [Machine].[Company code].&[X],[Measures].[OEE for company X],[Measures].[OEE]).

*If only [OEE] name is allowed for both. Rename existing [OEE], hide both, create new calculated measure as [Measures].[OEE] as IIF([Machine].[Company code].CurrentMember is... from #2 above.

*Use SCOPE statement. SCOPE([Machine].[Company code].&[X],[Measures].[OEE]);
THIS=[Measures].[OEE for company X];
END SCOPE;

*Use direct way: ([Machine].[Company code].&[X],[Measures].[OEE])=[Measures].[OEE for company X];
Please use any of these or update your question with more details.


text:
Q: Setting %s in language not working When I submit my form I have set flash data, with a line from my language file. But I need to include the Uri segment which is the id in with it so it would out put like so Success: You have modified store id 20 settings!
Currently it shows id but in wrong place: Success: You have modified store id %s settings! 280
Language:
$lang['text_success'] = 'Success: You have modified store id %s settings!';
Set Flash Data
sprintf($this->session->set_flashdata('success', $this->lang->line('text_success') . $this->uri->segment(5)));

How can I make it so where the %s in language line the id will show when message is outputted?

A: Use this
I assume $this->uri->segment(5) is your id
$this->session->set_flashdata('success', sprintf($this->lang->line('text_success'), $this->uri->segment(5)));

A: I had another think about it and came up with this code here which works fine. I had to make another line with a variable and the place the variable in the set flash data.
$message = sprintf($this->lang->line('text_success'), $this->uri->segment(5));
$this->session->set_flashdata('success', $message);

Correct message out put now: Success: You have modified store id 280 settings!
And on language file:
$lang['text_success'] = 'Success: You have modified store id %s settings!';


text:
Q: how to restrict access to all .txt file in apache except robots.txt? I am configuring apache2 on debian and would like to allow only robots.txt to be accessed for searching engines, while other .txt files are restricted, I tried to add the followings to .htaccess but no luck:
<Files robots.txt>
Order Allow,Deny
Allow  from All
</Files>
<Files *.txt>
Order Deny,Allow
Deny from All
</Files>
Can anyone help or give me some hints? I am new comer to apache, thanks a lot.

A: Use mod_rewrite
RewriteEngine On
RewriteCond %{REQUEST_URI} !/robots\.txt$ [nocase]
RewriteRule \.txt$  -  [forbidden,last]

First, make sure the rewrite engine in enabled.
Next, use a negated-match (!) to apply a conditional to the RewriteRule that excludes any URI's ending in "/robots.txt"
Lastly, if the URI ends in ".txt" then issue a 403 Forbidden.
EDIT: Don't forget the comparison engine is using regex, so you need to escape special characters (ie, .)


text:
Q: Exchange Rate for specific date and currency on a data frame I need for each observation (each with different currency and date-stamp) the exchange rate for the specifica date and curreny.
This is my code so far:
library(priceR)
library(ggplot2)
library(tidyverse)
library(tibble)
library(dplyr)

#Data frame
df <- data.frame(
  currency = c("DKK", "USD", "DKK"),
  price = c(580.9, 539.75, 567.8),
  Date = c("2020-01-01", "2020-02-15", "2020-03-15")
)

#Function to pull conversions
avg_ex <- function(x){
  historical_exchange_rates(x, to = "EUR",start_date = "2020-01-01", end_date = "2020-03-15") %>%
    `colnames<-`(c('date','conv')) %>% summarise(mean(conv)) %>% as.numeric
}

#Apply across all needed
conversions = sapply(unique(df$currency),avg_ex) %>% data.frame() %>% rownames_to_column() %>%
  `colnames<-`(c('currency','conv'))

#Join and convert
df %>% left_join(conversions,by='currency') %>%
  mutate(price_euro = price*conv)

  currency  price       Date      conv price_euro
1      DKK 580.90 2020-01-01 0.1338419   77.74876
2      USD 539.75 2020-02-15 0.9047106  488.31752
3      DKK 567.80 2020-03-15 0.1338419   75.99543

The output is nearly what  i need. Except, that the conversion rate is acutal just the average from "2020-01-01" to "2020-03-15"
for example i need for the 1. Observation:  0.133754 instead on 0.1338419

A: Solution:
#Data frame
df <- data.frame(
  currency = c("USD", "DKK", "USD", NA),
  price = c(10, 11, 12, 13),
  date = as.Date(c("2020-01-01", "2020-02-01", "2020-03-01", "2020-04-01"))
)
head(df)

#Function to pull conversions
avg_ex <- function(x, y){
  if (is.na(x)) 0
  else historical_exchange_rates(x, to = "EUR", start_date = y, end_date = y) %>%
    `colnames<-`(c('date','conv')) %>% summarise(conv) %>% as.numeric
}

#Apply across all needed
df$conv = mapply(avg_ex, df$currency, df$date) %>% data.frame() %>% rownames_to_column() %>%
  `colnames<-`(c('currency','conv'))
df


text:
Q: Retrieve the WPA2 Enterprise username in iOS I have an interesting requirement that I'm not sure is even possible. Currently, I'm developing an iPad app for a fleet of tablets. The tablets connected to a WPA2 Enterprise WIFI network. Is it possible using Objective-C or Swift or C magic or whatever is necessary to get the identity/username that is connected to the wireless network?
I've poked around CaptiveNetwork, but it doesn't seem to be what I want. I'm not sure if there is something to CWNetwork, but that seems to be Mac only. You can do this on Android (I know, because I'm currently doing it with the key android.net.wifi.WifiConfiguration$EnterpriseField).
Can anybody help?

A: I did some reading and was thinking this would be possible through SCPreferences in the SystemConfiguration framework, but unless your device is jailbroken, the APIs you need are not available on iOS.

A: The only way that comes to mind is with an MDM such as AirWatch or Good.


text:
Q: Read and write a config file with Python3 without losing the comments in the file I want to read a configuration file in INI format that has comment lines. I don't want to lose those lines when the application writes the configuration back to the file.
How can I do this?
Python 3.6.5rc1 (default, Mar 14 2018, 06:54:23)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import configparser
>>> cfg = configparser.ConfigParser()
>>> cfg.read_string('''[DEFAULT]
... # comment
... parameter = 7''')
>>> f = open('my.conf', 'w')
>>> cfg.write(f)
>>> f.close()
>>>
$ cat my.conf
[DEFAULT]
parameter = 7

A: The ConfigObj is the solution.


text:
Q: How to make transparent Color background for camera preview exuding one View? I want to make a scanner-like view for my camera preview I have created a view with a rectangle view in the center of the camera preview now I want to add a transparent color background to the camera preview but want to make a rectangle clear view. I have tried with set alpha and background color but it is not working in my view.
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
    android:id="@+id/preview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<ImageView
    android:id="@+id/switchcamera"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="camera_change"
    android:onClick="onClick"
    android:src="@drawable/frontcamera_foreground"
    app:layout_constraintEnd_toEndOf="@+id/preview"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/text_animator"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:text="1"
    android:textColor="@color/white"
    android:textSize="70sp"
    android:textStyle="bold"
    android:visibility="gone"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintGuide_percent="0.5"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<View
    android:id="@+id/viewRectangle"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:background="@drawable/border"
    android:visibility="gone"
    android:alpha="1"
    android:layout_marginLeft="50dp"
    android:layout_marginRight="50dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

here FrameLayout is for the preview of the camera using custom SurfaceView
View is my RectangleView.

A: Try following:
Ignore com.otaliastudios.cameraview.CameraView it's just a camera library I have imported.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.otaliastudios.cameraview.CameraView
        android:id="@+id/camera"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:keepScreenOn="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <View
        android:id="@+id/viewRectangle"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/border"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Now the important part is how border.xml drawable is constructed:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@android:color/transparent"/>
    <stroke android:color="#a00" android:width="1dp"/>
</shape>

Notice that solid part is set to transparent and only stroke is given a solid color.This was you can achieve it.


text:
Q: Fitting 2nd Order multivariate quadratic with matrices Hopefully you at least entertain this question as it took forever to construct the below matrix using TeX. Any ways, so I have a list of data points ($X_1$,$X_2$,Y), with the X's being independent variables and Y being dependent. What I am attempting to find is the best fit multivariate quadratic using sum of the least squares.
The general 2nd order polynomial I am attempting to find is in the form of:
$$
y = B_0 + B_1 X_1 + B_2 X_2 + B_{11} X_1^2 + B_{22} X_2^2 + B_{12}X_1X_2
$$
1) Can anyone tell me if the below matrix is correct? In comparison, a traditional uni-variate quadratic fit can be seen on page 9.
$$
\begin{vmatrix}
n & \sum_{} X_1 & \sum_{} X_2 & \sum_{} X_1 X_2 & \sum_{} X_1^2 & \sum_{} X_2^2 \\
\sum X_1 & \sum_{} X_1^2 & \sum_{} X_1 X_2 & \sum_{} X_1^2X_2 & \sum_{} X_1^3 & \sum_{} X_1 X_2^2 \\
\sum X_2 & \sum_{} X_1 X_2 & \sum_{} X_2^2 & \sum_{} X_1 X_2^2 & \sum_{} X_1^2 X_2 & \sum_{} X_2^3 \\
\sum X_1 X_2 & \sum_{} X_1^2 X_2 & \sum_{} X_1 X_2^2 & \sum_{} X_1^2 X_2^2 & \sum_{} X_1^3 X_2 & \sum_{} X_1 X_2^3 \\
\sum X_1^2 & \sum_{} X_1^3 & \sum_{} X_1^2 X_2 & \sum_{} X_1^3X_2 & \sum_{} X_1^4 & \sum_{} X_1^2 X_2^2 \\
\sum X_2^2 & \sum_{} X_1 X_2^2 & \sum_{} X_2^3 & \sum_{} X_1 X_2^3 & \sum_{} X_1^2X_2^2 & \sum_{} X_2^4 \\
\end{vmatrix}
\begin{vmatrix}
B_0\\
B_1\\
B_2\\
B_{12}\\
B_{11}\\
B_{22}\\
\end{vmatrix}
=
\begin{vmatrix}
\sum_{} Y_i\\
\sum_{} X_1 Y_i\\
\sum_{} X_2 Y_i\\
\sum_{} X_1 X_2 Y_i\\
\sum_{} X_1^2 Y_i\\
\sum_{} X_2^2 Y_i\\
\end{vmatrix}
$$
2) When I solve for the $B_{12}$ which is the $X_1X_2$ coefficient, if that is ~ 0 or very small, then that means there is very little interaction between X & Y?

A: Yes, your derivation is correct.
$B_{12}$ being small (compared to $B_{11}$ and $B_{22}$) indeed indicates that the axis of the paraboloid are close to the coordinate axis.


text:
Q: software for ubuntu I M new user for Ubuntu 11.10...In Ubuntu 11.10 take much time for specified software via software center. for example I download wine for window uploader using usb data card @2g speed. its take nearly 3 hours for installation. But in winxp u can download .exe file with download manager very fast (100 MB in 40 min. with BSNL SIM) and installed it any time. Now I want to know how to download fast in Ubuntu 11.10
MY requirement is under please.

*

*FDM for video download via youtube.com using browser

*Audio/Video Codec for verious format like FLV, 3gp avi,

*HindiIndic(IME)/English option for office work (in MS Office I can change typing language   by pressing alt+shift key)

*Nero

A: sometimes a software you want to download needs to download extra libraries, not only it's binary to be run,
but the good news is that when the library is downloaded, it 'might' be used by another application, so in future you (again might) need to download less
for the issue of "being able to install anytime", it's possible,
copy the archives at this path somewhere: /var/cache/apt/archives/
you don't the folder partial, and the file 'lock', don't change permissions of lock or delete it
next time you want to install wine(let's say after a fresh installation) just copy back the archives to the path mentioned, but you have to update repository list before by
sudo apt-get update

you can even give the archives to your friend and all he same as you has to copy archives to path and update repositories, and install,
for codecs install packages "gstreamer" in software center, not all of them will show up, you should choose show "technical stuff" (maybe it had another name, but something like this)
 nero is not free,  instructions of downloading will be given after purchasing from ahead company,  but there many many free similar softwares, before spending money i suggest you to try them, if you have an image in nrg format use software nrg2iso to convert them
i dont know what fdm is, but for languages you just have to add them in settings/keyboard layouts/layouts, add it there,
if the key sequence alt+shift doesn'y work set it by clicking the "option" key, located it the same window you add languages
 good luck!


text:
Q: SetWindowText crashes program when printing wchar_t Why can't I print text in my window when I use SetWindowText()? This is what my window creation code looks like:
game_board[i] = CreateWindowEx(0,
                L"Static",
                board_elements[i],
                WS_CHILD | WS_VISIBLE | WS_BORDER,
                0,
                0,
                0,
                0,
                hwnd,
                (HMENU)IDC_STATICBOARD + i + 1,
                hInst,
                NULL);

And when I write something like:
wchar_t c;
for(i = 0; i < 15; i++){
   c = 'a' + i;
   SetWindowText(game_board[i], c);
   UpdateWindow(game_board[i]);
   }

my program crashes after I trigger that event.
If I use SetWindowText(game_board[i], L"TEXT"); then it prints TEXT everywhere normally.
I also had these issues with needing to precast everything and I don't know why.
I'm using VS 13 and project is a Windows app written in C++. If I copy the code over in Codeblocks then it pops an error for each cast I created in VS and after I remove them all, then it works normally.
Why? Can anyone help me to fix this?

A: The SetWindowText function expects a pointer to a nul-terminated string. But you're trying to pass it a single character.
As a commenter mentioned, this code shouldn't even compile. You mention something about "needing to precast everything". This is likely the problem. Casting is like telling the compiler "don't worry about it, I know what I'm doing". But in this case, you don't. The compiler errors were trying to protect you from making a mistake, you should have listened.
Change the code to look like this:
// Declare a character array on the stack, which you'll use to create a
// C-style nul-terminated string, as expected by the API function.
wchar_t str[2];

// Go ahead and nul-terminate the string, since this won't change for each
// loop iteration. The nul terminator is always the last character in the string.
str[1] = L'\0';

for (i = 0; i < 15; i++)
{
   // Like you did before, except you're setting the first character in the array.
   str[0] = L'a' + i;
   SetWindowText(game_board[i], str);
   UpdateWindow(game_board[i]);
}

Note the L prefix. That indicates to the compiler that you're using a wide character/string—required for the wchar_t type.


text:
Q: Missing Stack Frames from ClrStackWalk Event I try to use TraceProcessing Library to get from managed exceptions which have an associated Clr Stackwalk event the stack trace. In principle it should be pretty easy by parsing the event and getting the method addresses.
using Microsoft.Windows.EventTracing;
using Microsoft.Windows.EventTracing.Events;
using System;
using System.Collections.Generic;
using System.Linq;

namespace TraceProcessingStackDecoding
{
    class Program
    {
        static void Main(string[] args)
        {
            string etlFile = args[0];
            using ITraceProcessor processor = TraceProcessor.Create(etlFile, new TraceProcessorSettings
            {
                AllowLostEvents = true,
            });

            IPendingResult<IGenericEventDataSource> genericEvents = processor.UseGenericEvents();
            processor.Process();

            const int ClrStackWalkEventId = 82;
            const string DotNetRuntimeProviderName = "Microsoft-Windows-DotNETRuntime";

            foreach (IGenericEvent clrStackWalk in genericEvents.Result.Events.Where( x=> x.ProviderName == DotNetRuntimeProviderName && x.Id == ClrStackWalkEventId))
            {
                IReadOnlyList<Address> stackAddresses = clrStackWalk.Fields["Stack"].AsAddressList;
                uint frameCount = clrStackWalk.Fields["FrameCount"].AsUInt32;

                if( stackAddresses.Count != frameCount)
                {
                    Console.WriteLine($"Error: Address List has only {stackAddresses.Count} entries but expected were {frameCount} entries!");
                }
            }
        }
    }
}

But when I do this I find that almost all Stack frames are missing. I always get 2. If I am not mistaken it should return all data until the end of the event.
Error: Address List has only 2 entries but expected were 34 entries!
Error: Address List has only 2 entries but expected were 35 entries!
Error: Address List has only 2 entries but expected were 35 entries!
Error: Address List has only 2 entries but expected were 35 entries!
Error: Address List has only 2 entries but expected were 36 entries!
Error: Address List has only 2 entries but expected were 37 entries!
Error: Address List has only 2 entries but expected were 64 entries!
Error: Address List has only 2 entries but expected were 30 entries!
Error: Address List has only 2 entries but expected were 77 entries!
Error: Address List has only 2 entries but expected were 77 entries!
Error: Address List has only 2 entries but expected were 31 entries!
Error: Address List has only 2 entries but expected were 77 entries!

The Clr Stackwalk event manifest defines it as this:
            <template tid="ClrStackWalk">
                <data name="ClrInstanceID" inType="win:UInt16"/>
                <data name="Reserved1" inType="win:UInt8"/>
                <data name="Reserved2" inType="win:UInt8"/>
                <data name="FrameCount" inType="win:UInt32"/>
                <data name="Stack" count="2" inType="win:Pointer"/>
            </template>

The problem might be the count property which you take serious. But that is not how the event is actually logged and addresses lists are almost 100% dynamic list of stacks which do not have a fixed count. The best would be to return all data until the end of the event as address list if it is the last item in the manifested event.
Since I cannot access the raw event I have only a nice type safe albeit useless wrapper which makes it impossible to get the stack frames for .NET Stackwalk events.
Besides this does TraceProcessing support also JITed code when I try to lookup symbols? At API level I can only find a method at Image Level which will make it impossible to decode JITed code? But since TraceProcessing can decode JITed call stacks I think there might be something missing at API level.
foreach (Address stackAdr in stackAddresses)
{
    foreach (var image in ev.Process.Images)
    {
        var range = image.AddressRange;
        if (  ( (range.BaseAddress < range.LimitAddress) && (stackAdr > range.BaseAddress && stackAdr < range.LimitAddress)) ||
              ( (range.BaseAddress > range.LimitAddress) && (stackAdr < range.BaseAddress && stackAdr > range.LimitAddress)) )
        {
            IStackSymbol stackSymbol = image.GetSymbol(stackAdr);
            Console.WriteLine(stackSymbol?.FunctionName);
        }
    }
}

Will this approach work with JITed code out of the box or do I need to decode all JIT events manually?

A: If the manifest and the event payload do not match, parsing them yourself may be the best workaround. (I'm glad that worked for you.)
The best option would probably be to get the manifest fixed - does that team have a GitHub repository where you can file a bug? Maybe the folks at the following repository would know?
https://github.com/dotnet/diagnostics

A: I have got it working in some hacky way by parsing all events and then get the raw data of the events and store the addresses on my own. Later when I parse the generic events I can map the corresponding event by its time stamp and resolve the methods.
The managed methods nicely show up there also for JITed code.
    ...
     processor.Use(ProcessRawEvents);
    ...

    List<StackEvent> StackEvents = new List<StackEvent>();

    class StackEvent
    {
        public TraceTimestamp TimeStamp;
        public IReadOnlyList<Address> Stack;
    }

    bool myNeedsStack = false;

void ProcessRawEvents(EventContext eventContext)
{
    TraceEvent ev = eventContext.Event;

    if (ev.ProviderId == Constants.DotNetRuntimeGuid)
    {
        if (ev.Id == Constants.ExceptionEventId)
        {
            myNeedsStack = true;
        }

        // potentially every exception event is followed by a stackwalk event
        if (myNeedsStack && ev.Id == Constants.ClrStackWalkEventId)
        {
            myNeedsStack = false;

            StackEvent stackEv = new StackEvent()
            {
                TimeStamp = ev.Timestamp,
            };

            ReadOnlySpan<byte> frameData = ev.Data.Slice(8);
            List<Address> addresses = new List<Address>();
            stackEv.Stack = addresses;

            if (ev.Is32Bit)
            {
                ReadOnlySpan<int> ints  = MemoryMarshal.Cast<byte, int>(frameData);

                foreach(var intAdr in ints)
                {
                    addresses.Add(new Address(intAdr));
                }
            }
            else
            {
                ReadOnlySpan<long> longs = MemoryMarshal.Cast<byte, long>(frameData);
                foreach(var longAdr in longs)
                {
                    addresses.Add(new Address(longAdr));
                }
            }

            StackEvents.Add(stackEv);
        }
    }

}


text:
Q: Multiple Anchor tags have single click event to each I created anchor tags <a> surrounded by <li> tags dynamically and all are appended to <ul>.Then with click event of each anchor tags ajax request is made to controller and some data is get from it. Now I want each anchor tags to be clicked by once if any anchor tag is clicked twice than it should be disable or unclicked so that ajax call not made again Now the problem is how I check the click count of anchor <a> tag.
My html Code is here:
<ul class="nav nav-pills">

</ul>

And script part:
for (var c in data.categoryTypes)
{
    $('< a/>').attr('href','#'+data.ABC[c]).attr('data-toggle', "pill").text (data.ABC[c]).wrap('< li id='+c+'/>').parent().appendTo('.nav.nav-pills');
}

Click event is here:
$('ul').on('click', 'li', function (e)
{
    var categoryValue = $(this).text();
    alert(categoryValue);
    e.preventDefault();
});

A: You can to add a class like disabled after clicking the link and remove the class after the ajax call
$('ul').on('click', 'li:not("disabled")', function (e)
{
        $(this).addClass('disabled'); //add the class
        var categoryValue = $(this).text();
        alert(categoryValue);
        e.preventDefault();
       //do a ajax call, In ajax success remove the class disabled.
          $(this).removeClass('disabled');
  });


text:
Q: Finding Similar Geometries Given a set of coordinates in space:
a = [(0,0), (1,0), (10,10), ..., (x,y), (0,0)] # Closed Polygon
b = [(0,0), (1,0), (10,10), ..., (x,y)] # Polyline
c = (x,y) # Point

How can one go about and determine how closely related (similar) the shape is to another?
I was thinking I could use some variation on Cosine Similarity, but I am not able to find anything helpful on the internet to point me to a solution performing this type analysis on geometry objects.
Thank you


text:
Q: How to get data from multiple tables and send to html with '->with()' in laravel I have to tables 'users' and 'departments' and I want to get data from both tables and put in html form.
here is my code which not working because there is something missing in it.
here is the code of controller:
 public  function showProfileForm($id){
    $user = DB::table('users')->where('id','=',$id)->get();

    $dpt = DB::table('departments')->orderBy('department_name','asc')->get();
    return view('profile.showProfile')->with(['selDpt', $dpt, 'user', $user]);
}

A: The get() method retrieve data as a multi-dimensional array. So when you will retrieve only one array then you have to use first() method at the end of the query. So just Change the query from
$user = DB::table('users')->where('id','=',$id)->get();
to
$user = DB::table('users')->where('id','=',$id)->first();

Now, You have to pass data by array. So just change the line
return view('profile.showProfile')->with(['selDpt', $dpt, 'user', $user]);
To
return view('profile.showProfile')->with(['selDpt' => $dpt, 'user' => $user]);

shoProfile.blade.php
You have to use $selDpt & $user variable for use or echo data.
Hope it will work.
Learn more at https://laravel.com/docs/5.4/views#passing-data-to-views

A: You can use this syntax to pass multiple variables to a view:
return view('profile.showProfile', [
    'selDpt' => $dpt,
    'user' => $user
]);

https://laravel.com/docs/5.4/views#passing-data-to-views

A: Or you can use PHP function compact(). http://php.net/compact
$user = DB::table('users')->where('id','=',$id)->get();
$dpt = DB::table('departments')->orderBy('department_name','asc')->get();

return view('profile.showProfile', compact('dpt', 'user'));

You will have $user and $dpt in your view.


text:
Q: Include automatically generated methods in a java class I have a question which I am not sure can be answered.
I have a php script on a server that automatically generates a java method based on table contents in a MySQL Database. The script creates a .java file in which this method is saved.
I then download this method and copy and paste the method into my main java class. I think this is an unnecessary step. Is there a way to include the method in the java class rather than copying and pasting.
I am looking to write a reference to the method.java file at the point in the java class where the method should be copied and pasted.
Something like:
    public class ShowAlert {
            public void showAlert(String toast) throws IOException {
    System.out.println("alert = "+externalMethod());
    }

    include(externalMethod.java);

}

and then externalMethod.java has
public String externalMethod(){
return "hello world";
}

I am not sure if this is possible but it would be great if it was.

A: There is no "include file" facility in Java. I suggest that you generate this instead:
public class GeneratedClass {
    public static String externalMethod(){
        return "hello world";
    }
}

and call it like this:
GeneratedClass.externalMethod();

That way, the handwritten file and the generated file can be completely separate.

A: You should really consider to use something like Java ScriptEngine (described in JSR 223). Examples can be found here.
There are also LUA integrations for Java.

A: You would ideally keep generated code and manually written code in separate files. In that way  you wont have to do what you are doing. Use Aasmund's suggestion. That's the right way to go. You might have to restructure your code to allow this, but better now than later.
I would ask you to go the extra mile and use interfaces. Your generated code should implement an interface and your manual code should reference everything using the interface alone. You could have a Factory that returns the instance.
This will allow you to increase your decoupling of manual code and the generated code. I would think that would you are doing is using the DAO (data access object) pattern to a certain extent. The DAO pattern works best, if you keep the generated code separate and access it using interfaces. Using interfaces will allow you to change the implementation of the DAO to something else at runtime - such as to run unit tests.

A: You could use a PHP template engine like Smarty to create your complete java class. Your main class will be your template with a placeholder for the generated method.


text:
Q: On creating a JAR in android studio, how to add the external jar library in the module? On creating a jar for android application, i tried pulling up some external jar's in the module.but each time i try to build the jar im facing this issue.
Error:Execution failed for task ':mpos:compileJava'.

Compilation failed; see the compiler error output for details.
  Error:(9, 19) error: package android.app does not exist
  Error:(14, 30) error: cannot find symbol class Activity

"mpos" is my file name.

A: You have to put your JAR file in app/libs, and in app/build.gradle inside the dependencies section:
compile fileTree(dir: 'libs', include: ['*.jar'])

A: you can put your jar files in any directory you want to make inside module like app module or your library module
then you add an implementation command in build.gradle file of that module and specify the jar directories you made. like this
implementation fileTree(include: ['*.jar'], dir: 'libs')

or maybe
implementation fileTree(include: ['*.jar'], dir: 'path/to/dir')


text:
Q: Identify Orthogonal Proj. and Reflection within given choice of Matrices. The problem states that out of five given matrices, one represents an Orthogonal Projection onto a line and another a Reflection about a line; I'm supposed to identify them.
Rather than list the matrices here, I'd like to understand how one would go about identifying these two transformations. I should probably state that the matrices are all 3x3, and all have a coefficient of 1/3 (one of them -1/3).

A: An orthogonal projection has $A^2 = A^* = A$, where $A^*$ denotes the adjoint, that is $A^* = A^t$ for real matrices. Any such matrix is an orthogonal projection. A projection onto a line moreover has ${\rm rank}\, A = 1$.
A reflection around a line is characterised by $A^tA = {\rm Id}$, $A^2 = {\rm Id}$, $\det A = 1$ and $A \ne {\rm Id}$.

A: An orthogonal projection matrix is a matrix $P$ which satisfies $P^T = P$ and $P^2 = P$. You can check these conditions easily. And a reflection is an orthogonal matrix (i.e. if you take the dot product of two different columns, you get $0$) whose determinant is $-1$ (the eigenvalues should be all 1's, except for one eigenvalue of $-1$) [ I'd be surprised if you hadn't seen determinants -- they're at the beginning of almost all intro linear algebra books these days, with inane ways of calculating them by hand. ]
If you're reflecting a vector $v$ across the plane determined by vector $a$, the resultant vector is $v - 2 \frac{v \cdot a}{a \cdot a} a = (I - 2 \frac{1}{||a||^2} a a^T) {v}$. without loss of generality, you can assume $||a|| = 1$, so see if you can write the reflection matrix in the form of $I - 2 a a^T$ for a unit vector $a$. But the determinant check is easier.


text:
Q: Function overloading in multiple inheritance diamond problem in C++ This is just a question on the best practices to follow for function overloading in a diamond problem in multiple inheritance.
#include <iostream>

using namespace std;

class A {
    public:
    virtual void print() {
        cout << "In A" << endl;
    }
};

class B : public virtual A {
    public:
    virtual void print() {
        A::print();
        cout << "In B" << endl;
    }
};

class C : public virtual A {
    public:
    virtual void print() {
        A::print();
        cout << "In C" << endl;
    }
};

class D : public virtual B, public virtual C {
    public:
    virtual void print() {
        B::print();
        C::print();
        cout << "In D" << endl;
    }
};

Here, base class class A implements a print() function which is overloaded in derived classes class B and class C. However, the derived classes class B and class C also require the base class print() function, so they have calls to the base class print() function using A::print().
A a;
B b;
C c;

a.print();
Output:
In A

b.print();
Output:
In A
In B

c.print();
Output:
In A
In C

class D is derived from class B and class C.
class D also needs to overload the print() function and call all the print functions of its parent classes class B and class C as well as grandparent class class A.
Using B::print(); C::print(); in the overloaded print() function of class D:
d.print();
Output:
In A
In B
In A
In C
In D

which is expected since the overloaded print() functions in class B and class C both have calls to A::print().
What is the best practice to overload the print() function in class D so that:
d.print();
Output:
In A
In B
In C
In D

given that classes class A, class B and class C cannot be modified.


text:
Q: My Ubuntu installation (triple booting Ubuntu 13.04, WinXP and Win7) made my Win7 impossible to boot I really hope this question is appropriate for this place, since I have absolutely no idea who to ask, or what to do.
When I first tried to install Ubuntu (well, second time, but the previous time was irrelevant, I installed and uninstalled it with no problem, I couldn't connect to the internet on Ubuntu back then due to my very old modem), I used a USB flash drive. Apparently, there was some kind of a problem in the flash drive, and the installation didn't complete. It stopped halfway through every time I tried it. Ever since I half-installed it, every time I tried to boot Windows 7, it failed to boot. I have no GUI boot enabled, so the only indication of booting is 3 teal dashes in the upper left part of the screen. It starts booting and then suddenly the top of the screen (where those teal dashes are) becomes scrambled, like when you move around a cartridge inside an old game console.
My Windows XP partition works perfectly, and all my files are fine - nothing was lost. When I boot, the first thing that launches is the GNU GRUB bootloader that gives me options between Ubuntu and Windows 7. If I choose Windows 7, it gives me another boot manager (the one that I used previously to choose between XP and 7). If I choose Windows XP (listed as an "older version of Windows"), everything works fine. If I choose Windows 7, the problem that I mention pops up. It just stays scrambled like that no matter how much I wait.
I tried running the repair tools. I ran the startup problem detector and it detected no problems. Someone suggested that it might be a problem with GRUB.
Any ideas? Thanks.
P.S: Apologies for not pointing it out, but after the USB installation failed, I managed to install Ubuntu successfully using a DVD, and I have been using it for like a month already. I have been in the mood for some games on my Win7 partition, so I decided to find a way to restore it (the Win7 itself, the files themselves are fine, as I said).

A: Really a Windows issue.
Windows can only boot thru one partition with the boot flag (or active partition in Windows). So Windows 7 installed its boot loader into your XP partition and that is what you are using to boot with. Once grub has chainloaded to the Windows boot loader, grub is not involved, so not a grub issue.
Did you at some point resize the Windows 7 partition? Often better to use Windows tools, but the installer or gparted often works. But you need to immediately boot Windows 7, so it can run chkdsk and make its repairs to its new partition size.
You may just need to run chkdsk from a Windows repair console on your Windows 7 partition. Do not use XP's chkdsk for that as it will  convert partition to XP type not Windows 7 type.


text:
Q: Ensemble of boolean predictors Lets say we have a 0/1 predictor, that is right in p % of cases.
If we ensemble N of those uncorrelated predictors, what is (an elegant solution for) their accuracy? (The ensemble's answer is the most voted variant.)
(Disclaimer: Not a homework, just came across this and I believe that there must be some more elegant solution than doing it by hand)


text:
Q: Error: database names cannot contain the character ' ' Notes before: this is updated, and there is a question with the name 'error: database names cannot contain the character '.' but this is with a space or a null character, not a dot! I am not sure if that could be a major difference, but apart from that question, the answer supposed there did not help me further. Also, I use Windows 7 (32 bits (not the best thing for mongodb, I know) and I made the description a bit more detailed).
To the point: I wanted to start meteor again for the first time after a couple of days (everything worked fine before) and suddenly this error appeared:
W20150803-18:44:47.168(2)? (STDERR) C:\Users\Laptop\AppData\Local\.meteor\packag
es\meteor-tool\1.1.3\mt-os.windows.x86_32\dev_bundle\server-lib\node_modules\fib
ers\future.js:245
W20150803-18:44:47.168(2)? (STDERR)
throw(ex);
W20150803-18:44:47.168(2)? (STDERR)
      ^
W20150803-18:44:47.168(2)? (STDERR) Error: database names cannot contain the cha
racter ' '
W20150803-18:44:47.169(2)? (STDERR)     at validateDatabaseName (C:\Users\Laptop
\AppData\Local\.meteor\packages\mongo\1.1.0\npm\node_modules\mongodb\lib\mongodb
\db.js:235:59)
W20150803-18:44:47.169(2)? (STDERR)     at new Db (C:\Users\Laptop\AppData\Local
\.meteor\packages\mongo\1.1.0\npm\node_modules\mongodb\lib\mongodb\db.js:97:3)
W20150803-18:44:47.169(2)? (STDERR)     at connectFunction (C:\Users\Laptop\AppD
ata\Local\.meteor\packages\mongo\1.1.0\npm\node_modules\mongodb\lib\mongodb\mong
o_client.js:275:29)
W20150803-18:44:47.169(2)? (STDERR)     at Function.MongoClient.connect (C:\User
s\Laptop\AppData\Local\.meteor\packages\mongo\1.1.0\npm\node_modules\mongodb\lib
\mongodb\mongo_client.js:345:5)
W20150803-18:44:47.170(2)? (STDERR)     at Function.Db.connect (C:\Users\Laptop\
AppData\Local\.meteor\packages\mongo\1.1.0\npm\node_modules\mongodb\lib\mongodb\
db.js:2094:23)
W20150803-18:44:47.170(2)? (STDERR)     at new MongoConnection (packages/mongo/m
ongo_driver.js:173:1)
W20150803-18:44:47.170(2)? (STDERR)     at new MongoInternals.RemoteCollectionDr
iver (packages/mongo/remote_collection_driver.js:4:1)...
W20150803-18:44:47.171(2)? (STDERR)     at Object.<anonymous> (packages/mongo/re
mote_collection_driver.js:38:1)
W20150803-18:44:47.171(2)? (STDERR)     at Object.defaultRemoteCollectionDriver
(packages/underscore/underscore.js:750:1)
W20150803-18:44:47.171(2)? (STDERR)     at new Mongo.Collection (packages/mongo/
collection.js:98:1)

A database name being empty while I haven't created any database in the meantime left me in utter darkness since then.
I thought it had to do with one specific project I tried to run (that project already had a load of issues by setting it up, but in the end it worked anyway), but I hadn't changed anything in there, neither did I change any other project. What made me more confused, is that I got this same error on every single other project I have tried to start.
After a while, I rebooted, and the projects started again, but the actual project where all of this began, failed again, this time showing an old known error:
Unexpected mongo exit code 14. Restarting.
Unexpected mongo exit code 100. Restarting.
Unexpected mongo exit code 100. Restarting.
Can't start Mongo server.
MongoDB had an unspecified uncaught exception.
This can be caused by MongoDB being unable to write to a local database.
Check that you have permissions to write to .meteor/local. MongoDB does
not support filesystems like NFS that do not allow file locking.

The original solution to that, was running this in CMD:
"c:\mongodb\bin\mongod.exe" --port 27017 --dbpath "C:\Users\Laptop\TheDatabaseFolder\rs2" --replSet rs2 --smallfiles --setParameter failIndexKeyTooLong=false //note: this had to be done due to 32 bit issue

rs.initiate()

This still gave the same 'cannot write' error although the CMD showed that writing was permitted. Finally I did this:
set MONGO_URL=mongodb://localhost:27017/meteor

Then I fired meteor with a specific config file (due to packages failing to load)
meteor --settings ../config/development/settings.json.dist

And there was the main problem with the database name containing a space or null character again.
In general: what is the most efficient way to get rid of this problem? Why could this have been suddenly sneaking into every project to make them fail? And, where is this 'packages/mongo/collection.js' (in general 'packages/mongo' as such) located anyway? I cannot find it at all...
Thanks in advance.

A: I would get this error every time I restarted my computer and then tried to make any sort of request. It appears to be something with the favicon.ico file. I'm just using local host to test out API calls so I obviously did not have this file. I'm pretty sure my requests were reading this as a database name, which would have the illegal '.' character. I finally added:
app.get('/favicon.ico', function(req, res) {
    res.sendStatus(204);
});

And now everything seems to work again. There is a 204 response for the favicon.ico request every time I put through a request, but it works.


text:
Q: How to scale thousands of Firebase app instances I need to initialize potentially thousands of Firebase app instances server-side using firebase-admin with a service account and then listen to specific Realtime DB and Firestore events on these app instances. These instances have nothing to do with one another and the only access I have to them is through their service account credentials files.
My main concern is scaling because new project app instances will be initialized on the fly. It is important that the events listened to should not be duplicated, so I can not have multiple server instances initialize listen to the events of all the apps.
Ideally, I would love to have an auto-scaling serverless solution and to keep it inside the Google Cloud Platform family. If there was a way to work with the app instances, while they are auto-scaled behind the scenes - like a load balancer for a collection of app instances. I've looked at the Google Cloud Pub/Sub solution to potentially do something like this, but could not come up with something concrete.
The non-scaling solution I have so far, using cloud functions:
EDIT: After feedback regarding Cloud Functions

*

*on startup of my project's cloud functions, initialize all the current app instances

*have a cloud function listen to newly added service accounts and initialize a new app instance for it. Currently, I have no idea how many project instances I can keep in memory before it becomes a problem.
Start up a single Node server to initialize all the current app instances. As new projects are added, simply add a reference for it. Monitor the server closely to ensure it doesn't run out of memory. Scale vertically as far as possible. When it gets to the point where necessary, start up a second server instance, but manually distribute project instances between servers, so there are no duplicates.

Bonus question: are only the individual cloud functions scaled as needed? ie. what happens to other standard JS functions/objects created outside a cloud function but inside the cloud functions index.js file?

Any advice would be greatly appreciated. Happy to elaborate on anything.


text:
Q: Error firing up meteor app in android emulator I'm getting this error when trying to run using meteor run android:
=> App running at: http://localhost:3000/
I20150430-17:43:21.410(-4) (android:cordova.js:927) Uncaught Error: Error calling method on NPObject.
I20150430-17:43:24.425(-4) (android:cordova.js:1169) deviceready has not fired after 5 seconds.
I20150430-17:43:24.450(-4) (android:cordova.js:1162) Channel not fired: onCordovaReady
I20150430-17:43:24.487(-4) (android:cordova.js:1162) Channel not fired: onFileSystemPathsReady
I20150430-17:43:24.516(-4) (android:cordova.js:1162) Channel not fired: onCordovaInfoReady

Running inside an Ubuntu VirtualBox. Ideas?

A: Looks like its a new bug in Meteor/Cordova, running meteor run android --release 1.0.3.1 works.


text:
Q: Fatal error: Call to a member function query() on a non-object in (CodeIgniter) I am new to codeigniter, this is my first model-controller connection,so anything you suggest is helpful for me and point will be considered for my future understanding,Kindly help to resolve here
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\xampp\ci\CI_test\application\models\testquery.php on line 7

My Controller:
class Testdb extends CI_Controller
   {
    public function Index()
    {
        $this->load->model("testquery");
        $data['results'] = $this->testquery->query1();

        $this->load->view("view_db");
    }
   }

My Model is:
class Testquery extends CI_Model
{
    public function query1()
    {
        $query = $this->db->query("SELECT * from color"); //this is line 7 error

        /**
        $sql = "SELECT * from color";
        $query = $this->db->query($sql);
        foreach ($query->result() as $row)
        {
           echo $row->color_id;
           echo $row->color_name;
           echo $row->color_desc;
        }
         */
        return $query->result();
    }
}

My view is:
<<!DOCTYPE unspecified PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Welcome db

<?php
print_r($results);
?>

My connection details:
config/database.php has-
$active_group = 'default';
$active_record = TRUE;

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'varundb';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;

My config/autoload.php has-
$autoload['libraries'] = array('database');

Am i missing something? I have gone through other posts as well
Where people suggested to-

*

*load database in each function where i use db.

*do not chain the query(which i will try once this is done).

*change the group_name.

And i am using XAMPP server, database is fine(i am seeing the table,data in it).
did all,still i get error!!

A: Try this:
Keep the case true
$this->load->model("Testquery",'',TRUE);

A: You must need to load the database .
class Testdb extends CI_Controller
   {
function __construct() {
        parent::__construct();

        $this->load->database();
        $this->load->model("testquery");
    }
    public function Index()
    {
       $data['results'] = $this->testquery->query1();
       $this->load->view("view_db");
    }
   }

A: Add __construct() methods to both controller and model.
You don't need to omit those.


text:
Q: Similar but incompatible classes What is a good practice for the following problem (in C++ foremost)?
I want to implement two (and later more) classes that are very similar but should be incompatible. For example I'll name them class Apple and class Orange. Obviously, then have common properties, like species, age, location and whatnot, but a apple object should never be assigned to an orange variable.
More importantly: there should be member functions that accept (or return) the own class and never the others. For example, the class Apple would have: Apple[] getAllFromTheSameTree(); and the class Orange would have: Orange[] getAllFromTheSameTree(); Also something like void addToSameTree(Apple) etc, having in mind that apples can not be on the same tree as oranges.
One idea is to have an abstract root class (class Fruit) that would define the common properties. But that would allow a function to accept a Fruit type parameter, which I want to prohibit - if possible).
Another idea is templates: Fruit<Apple> and Fruit<Orange> (Apple and Orange would be some dummy empty types here).

A:
One idea is to have an abstract root class (class Fruit) that would define the common properties

Yep, that's the ideea I advise you with.

But that would allow a function to accept a Fruit type parameter,
  which I want to prohibit - if possible).

Well, that's a non-issue. Because being abstract, there can't be objects of type Fruit
E.g. a function with this signature:
void consume_fruit(Fruit& fruit)

Will accept any kind of fruit (Apple, Orange). And since Fruit is abstract it won't accept objects of type Fruit simply because objects of type Fruit cannot exist.
Similarity a collection e.g. std::vector<std::shared_ptr<Fruit>> would hold objects of types derived from Fruit (Apple, Orange) but again there can't be objects of type Fruit.


text:
Q: Definite integral of even and odd functions proof Let $f$ be continous on [-a,a]
a) prove : $\int^{a}_{-a} f(x) dx = 0$
Because $f$ is odd $f(-x) = -f(x)$
$$\int_{x=-a}^0 f(x) \, dx = \int_{x=-a}^0 -f(-x) \, dx$$
letting $t = -x, dt = -dx$
$\int_{x=-a}^0 -f(-x) \, dx = \int_{t=a}^0 f(t) \, dt$
$\int_{t=a}^0 f(t) \, dt = -\int_{t=0}^a f(t) \, dt$
$\int_{-a}^{a}f(x)dx=\int_{-a}^{0}f(x)dx+\int_{0}^{a}f(x)dx$
$\int_{-a}^{a}f(x)dx=-\int_{0}^{a}f(x)dx+\int_{0}^{a}f(x)dx$=0
b) prove : $\int_{-a}^{a}f(x)dx=2\int_{0}^{a}f(x)dx$
Because $f$ is even : $f(x) =f(-x)$
letting $t = -x, dt = -dx$
$\int_{x=-a}^0 f(-x) \, dx = -\int_{u=a}^0 f(t) \, dt$=$\int_{u=0}^a f(t)dt$
Because $t$ is a dummy variable it can be replaced by x.
Is this rigorous proof ( is there any flaws? ) or is there better way of proving this?
Thanks in advance.

A: It might be nit picking but your proof should be as follows:
Assume $f$ is odd. First observe
\begin{align}
\int^a_{-a}f(x)\ dx = \int^a_0 f(x)\ dx + \int^{0}_{-a} f(x)\ dx.
\end{align}
Using $x=-u$ substitution in the second integral yields
\begin{align}
\int^0_{-a} f(x)\ dx = -\int^0_{a} f(-u)\ du= \int^a_0 f(-u)\ du.
\end{align}
And since $f$ is odd, then it follows
\begin{align}
\int^a_0 f(-u)\ du = -\int^a_0 f(u)\ du
\end{align}
which means
\begin{align}
\int^a_{-a} f(x)\ dx = \int^a_0 f(x)\ dx -\int^a_0 f(u)\ du = 0.
\end{align}


text:
Q: CMBlockBufferGetDataPointer datapointer is empty I am trying to send a H264 elementary stream to a server via TCP. The video is coming from the camera then straight to the device's encoder.  The Media server is unable to playback the video it received from the iOS app. I saved the stream buffer to a file an open it in an H264 analyser and I think it is missing some video data(non-IDR perhaps). Some of my code was taken from another post here in Stackoverflow(Outputcallback) while the encoding part from another source file online. I was checking for the CMBlockBufferGetDataPointer if it has some value but it is always empty. I am not sure if that is the reason why the stream is not playing on the other end. I hope you could tell me what is missing and what I could fix.
static void OutputCallback(void *outputCallbackRefCon,
                                   void *sourceFrameRefCon,
                                   OSStatus status,
                                   VTEncodeInfoFlags infoFlags,
                                   CMSampleBufferRef sampleBuffer) {
// Check if there were any errors encoding
if (status != noErr) {
    NSLog(@"Error encoding video, err=%lld", (int64_t)status);
    return;
}

// In this example we will use a NSMutableData object to store the
// elementary stream.
NSMutableData *elementaryStream = [NSMutableData data];

// Find out if the sample buffer contains an I-Frame.
// If so we will write the SPS and PPS NAL units to the elementary stream.
BOOL isIFrame = NO;
CFArrayRef attachmentsArray = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, 0);
if (CFArrayGetCount(attachmentsArray)) {
    CFBooleanRef notSync;
    CFDictionaryRef dict = CFArrayGetValueAtIndex(attachmentsArray, 0);
    BOOL keyExists = CFDictionaryGetValueIfPresent(dict,
                                                   kCMSampleAttachmentKey_NotSync,
                                                   (const void **)&notSync);
    // An I-Frame is a sync frame
    isIFrame = !keyExists || !CFBooleanGetValue(notSync);
}

// This is the start code that we will write to
// the elementary stream before every NAL unit
static const size_t startCodeLength = 4;
static const uint8_t startCode[] = {0x00, 0x00, 0x00, 0x01};

// Write the SPS and PPS NAL units to the elementary stream before every I-Frame
if (isIFrame) {
    CMFormatDescriptionRef description = CMSampleBufferGetFormatDescription(sampleBuffer);

    // Find out how many parameter sets there are
    size_t numberOfParameterSets;
    CMVideoFormatDescriptionGetH264ParameterSetAtIndex(description,
                                                       0, NULL, NULL,
                                                       &numberOfParameterSets,
                                                       NULL);

    // Write each parameter set to the elementary stream
    for (int i = 0; i < numberOfParameterSets; i++) {
        const uint8_t *parameterSetPointer;
        size_t parameterSetLength;
        CMVideoFormatDescriptionGetH264ParameterSetAtIndex(description,
                                                           i,
                                                           &parameterSetPointer,
                                                           &parameterSetLength,
                                                           NULL, NULL);

        // Write the parameter set to the elementary stream
        [elementaryStream appendBytes:startCode length:startCodeLength];
        [elementaryStream appendBytes:parameterSetPointer length:parameterSetLength];
    }
}

// Get a pointer to the raw AVCC NAL unit data in the sample buffer
size_t blockBufferLength;
uint8_t *bufferDataPointer = NULL;
CMBlockBufferGetDataPointer(CMSampleBufferGetDataBuffer(sampleBuffer),
                            0,
                            NULL,
                            &blockBufferLength,
                            (char **)&bufferDataPointer);

// Loop through all the NAL units in the block buffer
// and write them to the elementary stream with
// start codes instead of AVCC length headers
size_t bufferOffset = 0;
static const int AVCCHeaderLength = 4;
while (bufferOffset < blockBufferLength - AVCCHeaderLength) {
    // Read the NAL unit length
    uint32_t NALUnitLength = 0;
    memcpy(&NALUnitLength, bufferDataPointer + bufferOffset, AVCCHeaderLength);
    // Convert the length value from Big-endian to Little-endian
    NALUnitLength = CFSwapInt32BigToHost(NALUnitLength);
    // Write start code to the elementary stream
    [elementaryStream appendBytes:startCode length:startCodeLength];
    // Write the NAL unit without the AVCC length header to the elementary stream
    [elementaryStream appendBytes:bufferDataPointer + bufferOffset + AVCCHeaderLength
                           length:NALUnitLength];
    // Move to the next NAL unit in the block buffer
    bufferOffset += AVCCHeaderLength + NALUnitLength;
}
}

 -(void)compressSample:(CMSampleBufferRef)sampleBuffer {
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);

VTCompressionSessionRef session;
OSStatus ret = VTCompressionSessionCreate(NULL, (int)width, (int)height, kCMVideoCodecType_H264, NULL, NULL, NULL, OutputCallback, (__bridge void * _Nullable)(self), &session);
if (ret == noErr) {

    VTSessionSetProperty(session, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue);

    CMTime xpts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
    //kCMTimeInvalid
    VTCompressionSessionEncodeFrame(session, imageBuffer, xpts, kCMTimeInvalid, NULL, NULL, NULL);
    VTCompressionSessionEndPass(session, false, NULL);
}else{
    NSLog(@"Error encoding");
}

if (session) {
    VTCompressionSessionInvalidate(session);
    CFRelease(session);
}
}


text:
Q: SSRS Pie chart series labels getting cut off I am using SQL Server 2012
Visual Studio 2010
I have made a report with a pie chart. I want the series data labels outside the chart as you see in the images below. However the label value ClassificationMemberName is getting cut off at the top and bottom when I run the report.
As you see below for example, International Funds is getting trimmed at the top and bottom as are several of the other labels. You can't see the entire letter.

In design mode I see no way to resize the series labels through the GUI. I experimented extensively with various properties settings, but could not find a way to work around this problem including altering the font size.

The report has a parent and a subreport. The chart is in the subreport. If it's helpful here are the rdls
https://dl.dropboxusercontent.com/u/29851290/Sector%20Allocation.rdl
https://dl.dropboxusercontent.com/u/29851290/SectorAllocationSubreport.rdl
Thank you for your help.

A: I figured this out. The software vendor had placed custom code in the series label properties that was actually sizing the text based on the corresponding pie chart size. So the bigger the pie slice, the more the label was being cut off. I removed this code in the expression editor and used a static value for the property of the pie slices (classificationmembername) and now the text is not being cut off.


text:
Q: I am getting error after uploading my Laravel project to server I am getting this error after uploading my laravel project to the server. I have searched this error multiple times but not get some specific answer. I am using laravel 5.5 and PHP version 7.1.

Uncaught Error: Call to undefined function
  Symfony\Component\VarDumper\Dumper\json_encode() in
  /home/cp959319p17/public_html/vendor/symfony/var-dumper/Dumper/HtmlDumper.php:131

A: install json plugin for php < 5.2.0
apt install php-json
or
yum install php-json
As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.
http://php.net/manual/en/json.installation.php


text:
Q: Let $\gamma_r(t) = 1+re^{it}$ for $0\leq t \leq \pi/4$. Calculate $\lim\limits_{r\rightarrow 0+} \int_{\gamma_r} \frac{\cos (\pi z)}{\log z}$ Let $\gamma_r(t) = 1+re^{it}$ for $0\leq t \leq \pi/4$. Calculate $\lim\limits_{r\rightarrow 0+} \int_{\gamma_r} \frac{\cos (\pi z)}{\log z}$ where $\log z$ is the principle branch of the logarithm.
I made a few calculations. $\frac{\cos(\pi z)}{\log z}$ is analytic on $\mathbb{C}$ except a simple pole at $z=1$ and the residue at $z=1$ is $-1$.
I tried to enlarge $\gamma_r(t)$ to get a closed path which has $z=1$ in its interior. However, it is hard to calculate the integral on other parts of the path.

A: I must again refer to @SangchulLee 's
super useful lemma:

Lemma. Suppose $f(z)$ is holomorphic near $z = z_0$. Fix $\theta_0 \in (0, 2\pi)$. If $\gamma_{\epsilon}$ denotes a counter-clockwise oriented arc of angle $\theta_0$ on the circle of radius $\epsilon$ centered at $z_0$, then
  $$ \lim_{\epsilon\to0} \int_{\gamma_{\epsilon}} \frac{f(\zeta)}{\zeta-z_0}\;d\zeta=i\theta_0 f(z_0).$$

Thus, your integral equals
$$\frac\pi4 i(-1)=-\frac{\pi i}4$$


text:
Q: optimizing CSS selectors. Is `*+p` less costy than `p+*` According to what I know about browsers' algorithm of CSS processing, selector *+p has less perfomance impact than p+*, doesn't it?
So, in the p+* browser scans through all elements on the page, and those that follow p are applied a corresponding rule.
In the *+p firstly it looks only for p, but does it stop the search immediateliy after finding some element before p, thus making less "search iterations"? Or * still scans here everything.
Also, which tools can show CSS loading time and other 'heavyweight' information. Found only those that search for unused or excess rules and compress the CSS for getting less size.
In context - I need to apply top-margin to any element that follows p (except p+p), the content is generated dynamically.
Having read that old browsers suffer much of universal selector, this very question had arised.

A:
I need to apply top-margin to any element that follows p (except p+p)

What about:
p + :not(p) {
    background:red;
}

As far as performance/efficiency, look at either the Page Speed (FF) or Speed Tracer (Chrome)  browser extensions, both of which will help you analyse/identify problem CSS.

A: How about just adding bottom margin to all p elements, wouldn't that have the same result? You can then add a rule for p+p with negative top margin to counteract the effect, e.g.:
p {
    margin-bottom: 10px;
}

p + p {
    margin-top: -10px;
}


text:
Q: How to create a Pandas dataframe for each table meta data (Column Name, Type, Format) stored within a Database Schema in nested JSON file I have a JSON file which contains the meta data for tables held within a schema.
I would like to create a dataframe for each table defined within the JSON file i.e. Person, HomeAddress, Employment.  The Person and Employment are at the same level, but HomeAddress in nested within Person.
e.g. dataframe(Person)
 Column_Name     Type     Format      Required
 Person_ID       Integer              Yes
 DateOfBirth     String   date-time   Yes
 ...........

The contents of the file is as follows;
{
    "$id": "12121212",
    "type": "object",
    "properties": {
        "PersonId": {
            "type": "integer"
        },
        "Person": {
            "type": ["object", "null"],
            "properties": {
                "PersonId": {
                    "type": "integer"
                },
                "DateOfBirth": {
                    "type": "string",
                    "format": "date-time"
                },
                "DateOfBirthVerified": {
                    "type": "boolean"
                },
                "Sex": {
                    "type": ["string", "null"]
                },
                "Surname": {
                    "type": ["string", "null"]
                },
                "Initials": {
                    "type": ["string", "null"]
                },
                "Forenames": {
                    "type": ["string", "null"]
                },
                "Title": {
                    "type": ["string", "null"]
                },
                "NationalIdNumber": {
                    "type": ["string", "null"]
                },
                "HomeAddress": {
                    "type": ["object", "null"],
                    "properties": {
                        "EffectiveDate": {
                            "type": "string",
                            "format": "date-time"
                        },
                        "EndDate": {
                            "type": "string",
                            "format": "date-time"
                        },
                        "Category": {
                            "type": ["string", "null"]
                        },
                        "Line1": {
                            "type": ["string", "null"]
                        },
                        "Line2": {
                            "type": ["string", "null"]
                        },
                        "Line3": {
                            "type": ["string", "null"]
                        },
                        "Line4": {
                            "type": ["string", "null"]
                        },
                        "City": {
                            "type": ["string", "null"]
                        },
                        "County": {
                            "type": ["string", "null"]
                        },
                        "Country": {
                            "type": ["string", "null"]
                        },
                        "CareOfAddressee": {
                            "type": ["string", "null"]
                        },
                        "PostCode": {
                            "type": ["string", "null"]
                        },
                        "SuspectAddress": {
                            "type": "boolean"
                        },
                        "Overseas": {
                            "type": "boolean"
                        }
                    },
                    "required": ["EffectiveDate", "EndDate", "Category", "Line1", "Line2", "Line3", "Line4", "City", "County", "Country", "CareOfAddressee", "PostCode", "SuspectAddress", "Overseas"]
                }
            },
            "required": ["PersonId", "DateOfBirth", "DateOfBirthVerified", "Sex", "Surname", "Initials", "Forenames", "Title", "NationalIdNumber", "HomeAddress"]
        },
        "Employment": {
            "type": ["object", "null"],
            "properties": {
                "EmployeeReference": {
                    "type": ["string", "null"]
                },
                "DateFirstEmployed": {
                    "type": "string",
                    "format": "date-time"
                },
                "PayrollNumber": {
                    "type": ["string", "null"]
                }
            },
            "required": ["EmployeeReference", "DateFirstEmployed", "PayrollNumber"]
        }
    },
    "required": ["PersonId", "Person", "Employment"]
}

A: Let d be the dictionary of the file contents. Then you could address this recursively as follows:
import pandas as pd
import numpy as np

def get_props(d, required=[]):
    props = []
    for k, v in d.items():
        if isinstance(v, dict):
            if 'type' in v.keys():
                props.append({
                    'Column_Name': k,
                    'Format': v['format'] if 'format' in v.keys() else np.NaN,
                    'Type': v['type'] if isinstance(v['type'], str) else v['type'][0],
                    'Required': 'Yes' if k in required else 'No'
                })
            props.extend(get_props(v, required=d['required'] if 'required' in d else []))
    return props

df = pd.DataFrame(get_props(d))
print(df)

prints

index
Column_Name
Format
Type
Required

0
PersonId
NaN
integer
Yes

1
Person
NaN
object
Yes

2
PersonId
NaN
integer
Yes

3
DateOfBirth
date-time
string
Yes

4
DateOfBirthVerified
NaN
boolean
Yes

5
Sex
NaN
string
Yes

6
Surname
NaN
string
Yes

7
Initials
NaN
string
Yes

8
Forenames
NaN
string
Yes

9
Title
NaN
string
Yes

10
NationalIdNumber
NaN
string
Yes

11
HomeAddress
NaN
object
Yes

12
EffectiveDate
date-time
string
Yes

13
EndDate
date-time
string
Yes

14
Category
NaN
string
Yes

15
Line1
NaN
string
Yes

16
Line2
NaN
string
Yes

17
Line3
NaN
string
Yes

18
Line4
NaN
string
Yes

19
City
NaN
string
Yes

20
County
NaN
string
Yes

21
Country
NaN
string
Yes

22
CareOfAddressee
NaN
string
Yes

23
PostCode
NaN
string
Yes

24
SuspectAddress
NaN
boolean
Yes

25
Overseas
NaN
boolean
Yes

26
Employment
NaN
object
Yes

27
EmployeeReference
NaN
string
Yes

28
DateFirstEmployed
date-time
string
Yes

29
PayrollNumber
NaN
string
Yes