text:
Q: Spring @ActiveProfiles no longer supports comma separated profiles We're currently in the process of updating to Spring Boot 2.4.8 (Spring 5.3.8) and our integration tests are failing.
After some long debugging I found out that our @ActiveProfiles annotation was no longer working for two profiles. We defined it as followed:
@ActiveProfiles("dev,postgres")

However with the new Spring Boot version this no longer loads our application-dev.yml and application-postgres.yml files. If I define it as the following, it works again:
@ActiveProfiles(value = {"dev", "postgres"})

Is this a known change? because I can't find anything about it.

A: Yes this is a known change and very annoying.
It came with Spring Boot 2.3 but I can't say the exact version.
On the other hand the value of ActiveProfiles was always a array so that the supported a comma separated value was a mistake.


text:
Q: json_encode() behavior for public properties I know this works:
<?php

class MyDTO
{
    public $foo;
    public $bar;
}

$dto = new MyDTO();
$dto->foo = 42;
$dto->bar = false;

echo json_encode($dto); // {"foo": 42, "bar": false}

But I cannot find any references to such json_encode() behavior in the PHP docs. So my question: is it ok to rely on it?
Alternatively, I can implement \JsonSerializable interface, but I don't like to repeat DTO fields inside \JsonSerializable#jsonSerialize() considering those DTOs will contain only public fields.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the difference between (0:2):4 and 0:(2:4)? What is the difference between (0:2):4 and 0:(2:4)?
Both neglects the 2nd part of the bracket thus printing values similar to writing (0:4) and (0:2) respectively.
I could generalize from this that the bracket's first element is only working in this vector. But I would like to know the actual reason why is it happening.

A: the colon operator has lower priority than (), so, matlab first evaluates the vector inside the parenthesis, then, if one of the operands is a vector, colon only takes the first value. here are the evaluation steps:
(0:2):4 -> (0:2)=[0 1 2] -> 0:4 -> [0,1,2,3,4]
0:(2:4) -> (2:4)=[2 3 4] -> 0:2 -> [0,1,2]


text:
Q: Fig Python 3 Compatible? I have a django app running python 3.4 and I want to use Fig to help set up dockerized containers for my application's components.
When I run fig up I get the following error:
Recreating app_db_1...
Recreating app_search_1...
Creating app_web_1...
Traceback (most recent call last):
  File "/usr/local/Cellar/fig/1.0.1/libexec/bin/fig", line 9, in <module>
    load_entry_point('fig==1.0.1', 'console_scripts', 'fig')()
  File "/usr/local/Cellar/fig/1.0.1/lib/python2.7/site-packages/fig-1.0.1-py2.7.egg/fig/cli/main.py", line 31, in main
  File "/usr/local/Cellar/fig/1.0.1/lib/python2.7/site-packages/fig-1.0.1-py2.7.egg/fig/cli/docopt_command.py", line 21, in sys_dispatch
  File "/usr/local/Cellar/fig/1.0.1/lib/python2.7/site-packages/fig-1.0.1-py2.7.egg/fig/cli/command.py", line 28, in dispatch
  File "/usr/local/Cellar/fig/1.0.1/lib/python2.7/site-packages/fig-1.0.1-py2.7.egg/fig/cli/docopt_command.py", line 24, in dispatch
  File "/usr/local/Cellar/fig/1.0.1/lib/python2.7/site-packages/fig-1.0.1-py2.7.egg/fig/cli/command.py", line 56, in perform_command
  File "/usr/local/Cellar/fig/1.0.1/lib/python2.7/site-packages/fig-1.0.1-py2.7.egg/fig/cli/main.py", line 427, in up
  File "/usr/local/Cellar/fig/1.0.1/lib/python2.7/site-packages/fig-1.0.1-py2.7.egg/fig/project.py", line 174, in up
  File "/usr/local/Cellar/fig/1.0.1/lib/python2.7/site-packages/fig-1.0.1-py2.7.egg/fig/service.py", line 199, in recreate_containers
  File "/usr/local/Cellar/fig/1.0.1/lib/python2.7/site-packages/fig-1.0.1-py2.7.egg/fig/service.py", line 176, in create_container
  File "/usr/local/Cellar/fig/1.0.1/lib/python2.7/site-packages/fig-1.0.1-py2.7.egg/fig/service.py", line 370, in _get_container_create_options
TypeError: unhashable type: 'dict'

Is this because of incompatibilities with Python 3? I.e. is there any way that I can use fig to help build my app, or am I out of luck? Fig was installed using homebrew.
Here's my fig file:
db:
    image: kartoza/postgis
web:
    build: .
    command: python manage.py runserver:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    links:
      - db
      - search
    environment:
      - ALLOWED_HOSTS:
      - STRIPE_CLIENT_ID:
      - STRIPE_CLIENT_SECRET:
      - GOOGLE_API_KEY:
search:
    image: dockerfile/elasticsearch
    links:
      - db

A: Turns out the problem was not with the version of Python, but with my fig file.
Fig file should not have dashes in front of environment variables. Corrected fig file is as follows:
db:
    image: kartoza/postgis
web:
    build: .
    command: python manage.py runserver:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    links:
      - db
      - search
    environment:
      ALLOWED_HOSTS:
      STRIPE_CLIENT_ID:
      STRIPE_CLIENT_SECRET:
      GOOGLE_API_KEY:
search:
    image: dockerfile/elasticsearch
    links:
      - db

Fig is a tool written in Python 2.7, and is not available in a Python 3 variety, but that does not mean it is incompatible with Python 3 projects because it is not integrated into the project code. It is a separate tool and is run on its own by python 2.7.

A: The package name contains a hint: fig-1.0.1-py2.7.egg
It seems you installed the Python 2 version of fig. Try to install with pip install fig from a Python 3 environment.


text:
Q: Removing user from Domain B from a group that is in Domain A I am trying remove users that from a group that is in Domain A, call it 'Group A'. This works for users within the same domain but there are also users in Domain B that are members of that group.
I am trying to do this using:
Remove-ADGroupMember -Server 'Domain A' -Identity 'Group A' -Member User

For the 'User' I have tried both the SamAccountName and DistinguishedName but both fail. Returns the message:
Remove-ADGroupMember : Cannot find an object with identity ... 'User'


text:
Q: How to add an arrow on each side-by-side subfigures in the document class 'cas-dc' in Latex? I want to point to a specific object (such as the following example) in each sub-images with an arrow. I have also seen some suggestions such as this link.  How can I do it in the following document?
Example:

\documentclass[a4paper,fleqn]{cas-dc}
\usepackage{lipsum,capt-of,graphicx}
\usepackage{geometry}% Just for this example
\usepackage{natbib}
%\usepackage[wby]{callouts}
%\usepackage{cite}
\usepackage{ragged2e}
\usepackage{setspace}
\usepackage[labelfont=bf,justification=raggedright,singlelinecheck=false, font={footnotesize}]{caption}
\captionsetup[figure]{name=Fig. ,labelsep=period, justification=justified, singlelinecheck=off}
\captionsetup[table]{labelsep=newline,font=footnotesize, justification=justified, singlelinecheck=off}%,skip=0pt,belowskip=0pt}
\usepackage{subcaption}

\usepackage{etoolbox}
\AtBeginEnvironment{table}{\sffamily}
\usepackage{booktabs,siunitx, multirow}
\sisetup{table-format=1.4, tight-spacing=true, separate-uncertainty}

\sisetup{
    output-exponent-marker = \text{e},
    exponent-product={},
    retain-explicit-plus,
    input-open-uncertainty  = ,
    input-close-uncertainty = ,
    table-align-text-pre    = false,
    table-align-text-post = false,
    round-mode=places,
    round-precision=2,
    table-space-text-pre    = (,
    table-space-text-post   = ),
}

\usepackage{amsmath}
\usepackage{adjustbox}
\usepackage{floatrow}
\floatsetup[table]{style=Plaintop, captionskip=0pt, capposition=top}

\let\sum\relax % To change the style of summation symbol
\DeclareSymbolFont{otherlargesymbols}{OMX}{cmex}{m}{n}
\DeclareMathSymbol{\sum}{\mathop}{otherlargesymbols}{"50}

\setlength{\mathindent}{0pt}

\makeatletter
\@dblfpsep=20pt
\makeatother

\usepackage{array, cellspace}
\setlength\cellspacetoplimit{3pt}
\setlength\cellspacebottomlimit{3pt}

\begin{document}\sloppy
\begin{figure*}[htbp]
%\begin{annotate}
\centering
\subcaptionbox{\label{sfig:a}}{\includegraphics[width=.12\linewidth,height=1.9cm]{example-image-a.png}}\hfill
%\arrow{-3,-2.4}{-4.5,-3}
\subcaptionbox{\label{sfig:b}}{\includegraphics[width=.12\linewidth,height=1.9cm]{example-image-a.png}}\hfill
\subcaptionbox{\label{sfig:c}}{\includegraphics[width=.12\linewidth,height=1.9cm]{example-image-a.png}}\hfill
\subcaptionbox{\label{sfig:d}}{\includegraphics[width=.12\linewidth,height=1.9cm]{example-image-a.png}}\hfill
\subcaptionbox{\label{sfig:e}}{\includegraphics[width=.12\linewidth,height=1.9cm]{example-image-a.png}}\hfill
\subcaptionbox{\label{sfig:f}}{\includegraphics[width=.12\linewidth,height=1.9cm]{example-image-a.png}}\\
\subcaptionbox{\label{sfig:g}}{\includegraphics[width=.12\linewidth,height=1.9cm]{example-image-a.png}}\hfill
\subcaptionbox{\label{sfig:h}}{\includegraphics[width=.12\linewidth,height=1.9cm]{example-image-a.png}}\hfill
\subcaptionbox{\label{sfig:i}}{\includegraphics[width=.12\linewidth,height=1.9cm]{example-image-a.png}}\hfill
\subcaptionbox{\label{sfig:j}}{\includegraphics[width=.12\linewidth,height=1.9cm]{example-image-a.png}}\hfill
\subcaptionbox{\label{sfig:k}}{\includegraphics[width=.12\linewidth,height=1.9cm]{example-image-a.png}}\hfill
\subcaptionbox{\label{sfig:l}}{\includegraphics[width=.12\linewidth,height=1.9cm]{example-image-a.png}}\\
\caption{bbbbb.}
\label{fig1:MalBen}
%\end{annotate}
\end{figure*}

\end{document}

A: It may serve as starting point:
\documentclass{cas-dc}
\usepackage{natbib}
\usepackage{tikz}
\usetikzlibrary{arrows.meta}

\begin{document}
    \begin{figure*}
    \tikzset{every node/.style = {inner sep=0pt},
             every path/.style = {-{Triangle[scale=0.8]}, ultra thick, red},
                 s/.style args = {#1/#2}{shift={(#1mm,#2mm)}}
            }
    \setkeys{Gin}{width=.14\linewidth,height=20mm}
\tikz{\node (n1) {\includegraphics{example-image-a.png}};
      \draw ([s=-2/4] n1.east) -- ([s=-8/-2] n1.east);
      }      \hfill
\tikz{\node (n1) {\includegraphics{example-image-a.png}};
      \draw ([s=-2/8] n1.east) -- ([s=-8/3] n1.east);
      }      \hfill
\tikz{\node (n1) {\includegraphics{example-image-a.png}};
      \draw ([s=-3/6] n1.east) -- ([s=-8/2] n1.east);
      }      \hfill
\tikz{\node (n1) {\includegraphics{example-image-a.png}};
      \draw ([s=-4/8] n1.east) -- ([s=-8/-1] n1.east);
      }      \hfill
\tikz{\node (n1) {\includegraphics{example-image-a.png}};
      \draw ([s=-1/3] n1.east) -- ([s=-8/-1] n1.east);
      }      \hfill
\tikz{\node (n1) {\includegraphics{example-image-a.png}};
      \draw ([s=-1/3] n1.east) -- ([s=-8/-1] n1.east);
      }

\medskip
\tikz{\node (n1) {\includegraphics{example-image-a.png}};
      \draw ([s=2/-4] n1.west) -- ([s=8/-2] n1.west);
      }      \hfill
\tikz{\node (n1) {\includegraphics{example-image-a.png}};
      \draw ([s=2/-8] n1.west) -- ([s=8/-3] n1.west);
      }      \hfill
\tikz{\node (n1) {\includegraphics{example-image-a.png}};
      \draw ([s=3/-6] n1.west) -- ([s=8/-2] n1.west);
      }      \hfill
\tikz{\node (n1) {\includegraphics{example-image-a.png}};
      \draw ([s=4/-8] n1.west) -- ([s=8/-1] n1.west);
      }      \hfill
\tikz{\node (n1) {\includegraphics{example-image-a.png}};
      \draw ([s=1/-3] n1.west) -- ([s=8/-1] n1.west);
      }      \hfill
\tikz{\node (n1) {\includegraphics{example-image-a.png}};
      \draw ([s=1/-3] n1.west) -- ([s=8/-1] n1.west);
      }
\caption{bbbbb.}
\label{fig1:MalBen}
    \end{figure*}
\end{document}

Determining exact positioning of arrows I left to you. You need to select start and end coordinates of arrows. Determined are by s (shift) options.


text:
Q: Open all files with a partial name in subfolders - VBA I am trying to open all files with names ending with ToDo.xlsx, by doing a loop that goes through all subfolders.
I found this loop in another post in StackOverflow, but it takes too much time when there are a lot of files (~35k in my case) :
Public Sub NonRecursiveMethod()
    Dim fso, oFolder, oSubfolder, oFile, queue As Collection

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    queue.Add fso.GetFolder("your folder path variable") 'obviously replace

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue
        Next oSubfolder
        For Each oFile In oFolder.Files
            '...insert any file processing code here...
        Next oFile
    Loop
End Sub

My processing code is :
If InStr(oFile.Name,"ToDo"= <> 0 Then Workbooks.Open Filename:=oSubfolder & oFile

Is there a way to put this condition in the for loop, in order to minimize the processing time ?
Thank you

A: In stead of the For each loop, try if the following lop is faster:
filename = Dir(oFolder.Name & "\*ToDo.xlsx")
While (filename <> "")
    ' processing... Full name is oFolder.Name & "\" & filename
    filename = Dir
Wend


text:
Q: combining php, javascript and html I have the following .phtml file, but I am having trouble making it work.
look at the rendered script block, there is nothing after the equals.
http://screencast.com/t/zJ2DTnLF
and the code is this:
<?php
class ThePrinterDepo_Commissionjunction_Helper_Data extends Mage_Core_Helper_Abstract
{

    /**
     * Get SKU, quantity, price and discount amount for each product in a given order
     * @param object $order
     * @return array
     */
    private function _getOrderProductsList($order)
    {
        $orderItems = $order->getAllItems();
        $purchasedSkus = array();
        $count_orderItems = count($orderItems);
        for($i = 0; $i < $count_orderItems; $i++) {
            $purchasedSkus[$i] = array(
                'ITEM' => $orderItems[$i]['sku'],
                'QTY' => number_format($orderItems[$i]['qty_ordered'],0), // no decimals
                'AMT' => number_format($orderItems[$i]['price'],2), // 2 decimal places
                'DCNT' => number_format(abs($orderItems[$i]['discount_amount']),2)
            );
        }

        return $purchasedSkus;
    }

    /**
     * Get the Universal Data (JSON) Object for Commission Junction.
     * This object contains the order details passed on to Commission Junction for reporting purposes
     * on the Checkout Success / Order Confirmation page.
     * Notes:
     *  - CID, TYPE AND CURRENCY are hard coded
     * @param string $orderId
     * @return JSON object Universal Data Object for Commission Junction $json_masterTmsUdp
     */
    public function getCommissionJunctionUdo($orderId)
    {
        $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
        $udo = array();
        $udo['CID'] = 'XXXX';
        $udo['TYPE'] = 'XXXX';
        $udo['CURRENCY'] = 'USD';
        $udo['OID'] = $orderId;
        $udo['DISCOUNT'] = number_format(abs($order->discount_amount),2);

        $order_coupon_code = $order->coupon_code;
        if(!is_null($order_coupon_code) && !empty($order_coupon_code))
        {
            $udo['COUPON'] = $order_coupon_code;
        }

        $udo['PRODUCTLIST'] = self::_getOrderProductsList($order);

        if(Mage::getModel('core/cookie')->get('aff_commissionjunction') == 'cjafflx')
        {
            $udo['FIRECJ'] = "TRUE";
        }
        else
        {
            $udo['FIRECJ'] = "FALSE";
        }

        $masterTmsUdo['CJ'] = $udo;
        $json_masterTmsUdo = json_encode($masterTmsUdo);

        return $json_masterTmsUdo;

    }

}

?>

<script>var MasterTmsUdo = <?php echo $this->getCommissionJunctionUdo($this->getOrderId()); ?></script>
<script>/*DO NOT ALTER *** Th/(function(e){var t="1340",n=document,r,i,s={http:"http://cdn.mplxtms.com/s/MasterTMS.min.js",https:"https://secure-cdn.mplxtms.com/s/MasterTMS.min.js"},o=s[/\w+/.exec(window.location.protocol)[0]];i=n.createElement("script"),i.type="text/javascript",i.async=!0,i.src=o+"#"+t,r=n.getElementsByTagName("script")[0],r.parentNode.insertBefore(i,r),i.readyState?i.onreadystatechange=function(){if(i.readyState==="loaded"||i.readyState==="complete")i.onreadystatechange=null}:i.onload=function(){try{e()}catch(t){}}})(function(){});</script>

A: Have you tried replacing the order id call with this:
var MasterTmsUdo = <?php echo $this->getCommissionJunctionUdo(Mage::getSingleton('checkout/session')->getLastRealOrderId()); ?>

Edit to try and provide an answer to your comment below:
<script>
var prod_array = new Array();
</script>

<?php
$items = $order->getAllItems();
foreach ($items as $item) {
    $item_sku = $item->getSku();
    $price = $item->getPrice();
    $prod_quantity = $item->getQtyOrdered();

    echo ("<script>var product = {ITEM: '$item_sku', AMT: '$price', QTY: '$prod_quantity'}; prodList[prod_array.length] = product; </script>");
}
?>


text:
Q: Android: Changing visibility of components in fragment at runtime In Android app, I am using a menubar with tabs attached to it. And each tab has a fragment.
I am trying to set visibility of components (like button) in a fragment to invisible at runtime. But it is not taking effect.
What am I missing?
Main activity class calls a method in Fragment class to set visibility of the button.
But it is not taking effect.
In fragment class,
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState){
        View view = inflater.inflate(R.layout.fm_hd_fragment, container, false);
        multicastUp = (Button) view.findViewById(R.id.FmHdMulticastUp);
        multicastDown = (Button) view.findViewById(R.id.FmHdMulticastDown);
        multicastDisplay = (TextView)view.findViewById(R.id.FmHdCurrentMulticast);
        .
        .
        .
}

public static void showcontrol(){
        multicastDisplay.setVisibility(View.VISIBLE);
        multicastDown.setVisibility(View.VISIBLE);
        multicastUp.setVisibility(View.VISIBLE);
}

In class that wants to update this fragment
 FragmentWrapper.showcontrol();

A: Figured out the issue...
I was trying to update activity from Service directly.
When I use intents from service to update Activity, the UI update works fine.


text:
Q: How does this deduction come about? -(trig,convergence,complex analysis) I'll start it off, and highlight what I don't understand:
Lets assume that $z_0= \rho_0(\cos \varphi_0+i \sin \varphi_0)\neq0, where  -\pi<\varphi_0<\pi,$ or $z_0$ isn't a negative real number.
Let's look at the function $$l(\varphi)=\cos \varphi+i \sin \varphi. \\ \text{ then } |l(\varphi_n)-l(\varphi)|=2|\sin\frac{\varphi-\varphi_n}{2}|$$ Up to here, all is clear but then(this is the unclear part):
So for $|\varphi_n-\varphi|< \pi$
$$\frac{|\varphi_n-\varphi|}{\pi}\leq |l(\varphi_n)-l(\varphi)|\leq|\varphi_n-\varphi|$$

A: It's just an application of the inequality
$$\frac{2}{\pi}x \leqslant \sin x \leqslant x$$
that holds for $x \in \bigl[0,\frac{\pi}{2}\bigr]$. For $\lvert \varphi - \varphi_n\rvert < \pi$, we have $0 \leqslant \frac{\lvert \varphi - \varphi_n\rvert}{2} < \frac{\pi}{2}$, so we can apply the above inequality to $x = \frac{\lvert \varphi - \varphi_n\rvert}{2}$.


text:
Q: findDependentRowset returning all rows I have these two models:
class Application_Model_List extends Zend_Db_Table_Abstract
{
    protected $_name = 'list';
    protected $_primary = 'list_id';
    protected $_dependentTables = array('Application_Model_Task');

    public function getUserLists($user)
    {
        $select = $this->select()->from($this->_name)->where('list_user = ?',$user);
        return $this->fetchAll($select);
    }

}

and
class Application_Model_Task extends Zend_Db_Table_Abstract
{
    protected $_name = 'task';
    protected $_primary = 'task_id';

    protected $_referenceMap = array(
        'List' => array(
            'columns'       => 'task_list_id',
            'refTableClass' => 'Application_Model_List',
            'refColumns'    => 'list_id'
        )
    );
}

I call getUserLists within my controller like this:
public function indexAction()
{
    $lists = new Application_Model_List();
    $userLists = $lists->getUserLists(1);
    $this->view->lists = $userLists;
}

and pass it to my view and then call findDependentRowset like this:
foreach($this->lists as $list){
    echo $list->list_title;
    $tasks = $list->findDependentRowset('Application_Model_Task');
    foreach($tasks as $task){
        echo $task->task_title;
    }
}

but the problem is it outputs all rowsets from the dependent table, not just the ones matching the where clause

A: Oops. It turns out this was working but invalid HTML was hiding the output i was expecting


text:
Q: How to Implement Back-Face Culling in a 3D Javascript Engine Recently I've been working on creating a 3D graphics engine in Javascript. Currently, the camera can move in the x, y, and z axis (working on learning how to rotate the camera) and shapes can be rotated. Shapes are generated based on groups of vertices that make up a face.
An example of the drawing code for the shapes is as below:
function renderShapes() {
for (i = 0; i < objects.length; i++) { // For each object
    for (j = 0; j < objects[i].faces.length; j++) { // For each face
        var face = objects[i].faces[j];

        var P = project(face[0],objects[i].type);
        if (P == false) { // project the coordinates based on camera.
            continue;
        }
        ctx.beginPath();
        ctx.moveTo(P.x + cx, - P.y + cy); // Start line at first vertex

        // Draw the other vertices that make up the face
        for (l = 0; l < face.length; l++) {
            P = project(face[l],objects[i].type);
            if (P == false) {
                continue;
            }
            ctx.lineTo(P.x + cx, -P.y + cy); // Draw line to the next vertex
        }

        // Close the path and draw the face
        ctx.closePath();
        ctx.stroke();
        if (objects[i].color != undefined) { // Fill in a color if the object has color property
            ctx.fillStyle = objects[i].color;
            ctx.fill();
        }
    }
}
}

This above code, generates something roughly like this depending on how I rotate it:

Everything works perfectly, except that all faces are drawn, and based on their order in the object array, may overlap one or the other. The red cube is an example of my problem. The blue diamond is an example of what I want to achieve, clean faces that are only rendered based on what the camera can see. Instead of rendering all 8 faces of the diamond, it should only render the 4 visible ones. Instead of rendering all 6 faces of the cube, it should only render the 2 visible ones.
I have researched into it to find back-face culling, although the examples were either non-existent, in the wrong language, or simply hard to understand or fit into my case.
Can anyone explain to me, in layman's terms how back-face culling works? And if possible, a Javascript example of it that could be implemented into my code?
Alternatively, is there a different word or phrase for what I'm trying to achieve or a different process or algorithm that would be better suited?
Thanks


text:
Q: Select a substring of characters from the end of a character string in R I have a vector of character strings
vec <- c("1ZQOYNBAA55", "2JSNHGKLRBB66", "3HVXCC77", "4LDD88", "5CIFMTLYXEE99")

> vec
[1] "1ZQOYNBAA55"   "2JSNHGKLRBB66" "3HVXCC77"      "4LDD88"        "5CIFMTLYXEE99"

...and I would like to get the last 3 characters from each string. To get the first 3 characters, I can use substr()
substr(vec,1,3)

I would have thought something like substr() with a "fromLast" argument might exist
vec_ends <- substr(vec,1,3, fromLast = TRUE)

With an expected output
> vec_ends
[1] "A55" "B66" "C77" "D88" "E99"

But substr() only works one way. In my dataset the string lengths are variable so no reference to absolute character numbers or string lengths can be made, and there are no consistent separators of delimiting characters for a string split. Does anyone know of an easy way to do this in R?

A: You could use a sub() approach:
vec_ends <- sub(".*(.{3})$", "\\1", vec)
vec_ends

[1] "A55" "B66" "C77" "D88" "E99"

A: > gsub(".*(.{3})$", "\\1", vec)
[1] "A55" "B66" "C77" "D88" "E99"

Here´s an alternative without using regex:
> sapply(strsplit(vec, split=""),  function(x) paste(tail(x, 3), collapse = ""))
[1] "A55" "B66" "C77" "D88" "E99"

A: Here is an approach that doesn't use regex (which often but not always means it's faster).
get_last_n_chars  <- function(vec, n = 3) {

    substr(vec, nchar(vec)-(n-1), nchar(vec))

}

get_last_n_chars(vec)
# [1]  "A55" "B66" "C77" "D88" "E99"

Benchmarking - just for fun
Often (usually?!) performance is irrelevant and you should use whatever code is clearest.
However, I was interested, and it does appear in this case that avoiding regex is faster. However the really big win is not using sapply(strsplit()) method - I actually had to cut off the final point from the plot because it broke the scale.
input_vec  <- c("1ZQOYNBAA55", "2JSNHGKLRBB66", "3HVXCC77", "4LDD88", "5CIFMTLYXEE99")

num_iterations  <- c(10, 1e3, 1e4)
results <- bench::press(
    rows = num_iterations,
    {
        vec  <- rep(input_vec, rows)
        bench::mark(
            min_iterations = 100,
            sub = {
                sub(".*(.{3})$", "\\1", vec)
            },
            gsub = {
                gsub(".*(.{3})$", "\\1", vec)
            },
            strsplit = {
                sapply(strsplit(vec, split=""),  function(x) paste(tail(x, 3), collapse = ""))
            },
            get_last_n_chars_fun = {
                get_last_n_chars(vec)
            },
            stringi = {
                out <- stringi::stri_reverse(vec)
                out <- substr(out,1,3)
                out <- stringi::stri_reverse(out)
                out
            }
        )
    }
)

Plot of results:

Output of autoplot(results) + theme_bw():

A: I also found this package stringi, and with double use of stri_reverse() it can be done.
library(stringi)

out <- stri_reverse(vec)
out <- substr(out,1,3)
out <- stri_reverse(out)


text:
Q: AWS Lambda @ng-toolkit failing for TypeError: express is not a function in angular 9 app I started deploying my demo Angular 9 application on AWS lambda and provide SSR. In order to achieve this, I used @ng-toolkit/universal and @ng-toolkit/serverless. Deployment happened successfully but demo application is not opening. Upon investigating AWS lambda logs, I found the following exception.

Here is the package.json, where I have added express js in dependencies.
{
"name": "my-appg",
"version": "0.0.0",
"scripts": {
  "ng": "ng",
  "start": "ng serve",
  "build": "ng build",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e",
  "build:browser:prod": "ng build --prod",
  "build:browser:serverless": "ng build --prod --base-href /production/",
  "build:serverless": "npm run build:browser:serverless && npm run build:server:serverless",
  "build:prod": "npm run build:browser:prod && npm run build:server:prod",
  "server": "node local.js",
  "build:prod:deploy": "npm run build:prod && npm run deploy",
  "build:serverless:deploy": "npm run build:serverless && npm run deploy",
  "deploy": "serverless deploy --aws-profile leaks",
  "build:server:prod": "webpack --config webpack.server.config.js --progress --colors",
  "build:server:serverless": "webpack --config webpack.server.config.js --progress --colors"
},
"private": true,
"dependencies": {
  "@angular-devkit/schematics": "^9.1.3",
  "@angular/animations": "~9.0.5",
  "@angular/common": "~9.0.5",
  "@angular/compiler": "~9.0.5",
  "@angular/core": "~9.0.5",
  "@angular/forms": "~9.0.5",
  "@angular/platform-browser": "~9.0.5",
  "@angular/platform-browser-dynamic": "~9.0.5",
  "@angular/router": "~9.0.5",
  "@ng-toolkit/serverless": "^8.1.0",
  "@ng-toolkit/universal": "^1.1.21",
  "@schematics/angular": "^9.1.3",
  "aws-serverless-express": "^3.3.6",
  "cors": "^2.8.5",
  "express": "^4.17.1",
  "rxjs": "~6.5.4",
  "serverless-api-compression": "^1.0.0",
  "tslib": "^1.10.0",
  "zone.js": "~0.10.2"
},
"devDependencies": {
  "@angular-devkit/build-angular": "~0.900.5",
  "@angular/cli": "~9.0.5",
  "@angular/compiler-cli": "~9.0.5",
  "@angular/language-service": "~9.0.5",
  "@types/node": "^12.11.1",
  "@types/jasmine": "~3.5.0",
  "@types/jasminewd2": "~2.0.3",
  "codelyzer": "^5.1.2",
  "jasmine-core": "~3.5.0",
  "jasmine-spec-reporter": "~4.2.1",
  "karma": "~4.3.0",
  "karma-chrome-launcher": "~3.1.0",
  "karma-coverage-istanbul-reporter": "~2.1.0",
  "karma-jasmine": "~2.0.1",
  "karma-jasmine-html-reporter": "^1.4.2",
  "protractor": "~5.4.3",
  "ts-node": "~8.3.0",
  "tslint": "~5.18.0",
  "typescript": "~3.7.5",
  "ts-loader": "^6.2.1",
  "webpack-cli": "^3.3.10",
  "opencollective": "^1.0.3",
  "serverless": "^1.60.0",
  "serverless-apigw-binary": "^0.4.4"
}}

and here is server.ts which also seems okay.
// generated by @ng-toolkit/serverless
import 'zone.js/dist/zone-node';
import 'reflect-metadata';

import * as express from 'express';
import * as cors from 'cors';
import * as compression from 'compression';

import {join} from 'path';

export const app = express();

app.use(compression());
app.use(cors());

const DIST_FOLDER = join(process.cwd(), 'dist/myPleaks-ng9');

app.get('*.*', express.static(join(DIST_FOLDER), {
    maxAge: '1y'
}));

app.get('/*', (req, res) => {
    res.sendFile(join(DIST_FOLDER + '/index.html'));
});

Please help me to find out the issue, thanks in advance.

A: I found the solution on github post where "esModuleInterop": true from tsconfig file was required to remove.


text:
Q: Getting multiple line input from console I want to paste a JSON as an input to the console and convert it to string.
input:
{
    "age":"23",
    "name":"abc",
    "blog":"asskakasjsa",
    "messages":["msg1","msg2","msg3"]
  }

A: Sounds like a parsing disaster. You'd probably have to loop Scanner.nextLine() and figure out relative positions, parse values, and assign them properly.
I guess you could parse it line by line, make it a big String, save it to a .json file, and then use a framework to unmarshal it...?
Generally, this whole concept is not a good idea.

A: The following code reads the line by line input from the user until user enters '}'
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity  {

public static void main(String[] args) {
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

    String ip= null;
    try {

        String next;
        do
       {
          next=br.readLine().toString();
           ip+=next;
       }
      while(!next.equalsIgnoreCase("}"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("You have entered:");
    System.out.println(""+ip);

}
}


text:
Q: how to resolve this Error: "physical file does not exist" I couldn't resolve this error where I'm specifying a path to a file. But it seems that the compiler cannot recognize it.
 Please help

A: If SAS says the file doesn't exist then it is not there.  Not surprising as that is a really strange name for a file.
Why would you name a file xlsx?  That is the extension that Excel uses for workbooks.  If it actually is an Excel workbook then why would you try to read it as if it was a simple text file?
Also note that it looks like your file explorer window is not showing you the full filename. None of the files in your picture have the extension part of the filename displayed.  What is the full name for that file? Either turn on the display of the extension or use properties to see the real filename.

A: You cannot access an Excel file that way anyway, so this is using the wrong approach entirely. INFILE is for reading  in text type files, not for reading in an Excel file. Assuming you're trying to import your data, this is what you're likely looking to do this:
 proc import out=want datafile='c:\users\pi\Documents\xlsx.xlsx' dbms=xlsx replace; run;

PLEASE do not post code and log as images in the future.  It makes it harder to help you and answer your question when we first have to type out your code or data.


text:
Q: Use dataframes for fill another dataframe I have a list of 76 dataframes, here is one :
    Unnamed: 0            0          1
0            0   Nutriments  Quantités
1            1    Protéines      0.4 g
2            2      Lipides      0.2 g
3            3     Glucides     11.3 g
4            4          Eau       86,5
5            5       Fibres      1.2 g
6            6   Vitamine C      18 mg
7            7  Vitamine B1    0.08 mg
8            8  Vitamine B6    0.09 mg
9            9    Magnésium      15 mg
10          10    Potassium     146 mg
11          11    Phosphore      11 mg

And I have an other dataframe :
Manganèse  Calcium  Eau  ...  Vitamine B3  Vitamine B9  Magnésium
Nom                                   ...
Abricot            NaN      NaN  NaN  ...          NaN          NaN        NaN
Acérola            NaN      NaN  NaN  ...          NaN          NaN        NaN
Airelles           NaN      NaN  NaN  ...          NaN          NaN        NaN
Ananas             NaN      NaN  NaN  ...          NaN          NaN        NaN
Argousier          NaN      NaN  NaN  ...          NaN          NaN        NaN
               ...      ...  ...  ...          ...          ...        ...
Rhubarbe           NaN      NaN  NaN  ...          NaN          NaN        NaN
Roquette           NaN      NaN  NaN  ...          NaN          NaN        NaN
Tomate             NaN      NaN  NaN  ...          NaN          NaN        NaN
Topinambour        NaN      NaN  NaN  ...          NaN          NaN        NaN
Yuzu               NaN      NaN  NaN  ...          NaN          NaN        NaN

My list of dataframes is a list of vegetables and fruits. For example, the dataframe "Pineapple" (Ananas in French) must fill in the general dataframe.
I need a result like :
Manganèse  Calcium  Eau  ...  Vitamine B3  Vitamine B9  Magnésium
Nom                                   ...
Abricot            NaN      NaN  NaN  ...          NaN          NaN        NaN
Acérola            NaN      NaN  NaN  ...          NaN          NaN        NaN
Airelles           NaN      NaN  NaN  ...          NaN          NaN        NaN
Ananas             86,5     NaN  ...               NaN          15         NaN
Argousier          NaN      NaN  NaN  ...          NaN          NaN        NaN
               ...      ...  ...  ...          ...          ...        ...
Rhubarbe           NaN      NaN  NaN  ...          NaN          NaN        NaN
Roquette           NaN      NaN  NaN  ...          NaN          NaN        NaN
Tomate             NaN      NaN  NaN  ...          NaN          NaN        NaN
Topinambour        NaN      NaN  NaN  ...          NaN          NaN        NaN
Yuzu               NaN      NaN  NaN  ...          NaN          NaN        NaN

So I need to fill the general dataframe with the corresponding lines. The rows of my small dataframe are the columns of my general dataframe. And there is not on all the small dataframes the same number of "columns" as in the general dataframe.
Now I have a dict = {"apple": df1, "apricot":df2 etc}. I have :
dicttest["Ananas"]
Out[317]:
   Unnamed: 0           0         1
0           0         Eau    88.9 g
1           1    Glucides       9 g
2           2     Lipides    0.15 g
3           3   Protéines       1 g
4           4      Fibres       2 g
5           5  Vitamine A     91 UI
6           6  Vitamine C    240 mg
7           7     Calcium     15 mg
8           8     Energie   25 kcal
9           9     Energie  104.5 kJ

in 'Ananas' value.
Do you have a solution to make what I need?

A: Here's a way to do that using pd.concat and 'pivot`:
dfs = []
for k, v in dicttest.items():
    v["fruit"] = k
    dfs.append(v)

df = pd.concat(dfs, axis=0)
df = df[[2, 3, "fruit"]] # you may have to change the names of the columns 2 and 3,
                         # based on the column names in your data
df.columns = ["item", "amt", "fruit"]
res = pd.pivot_table(df, index="fruit", columns="item", aggfunc=",".join)

The output is:
            amt
item    Calcium     Eau Energie Fibres Glucides Lipides Protéines Vitamine A Vitamine C
fruit
ananas    15 mg  88.9 g      []    2 g      9 g  0.15 g       1 g      91 UI     240 mg
apricot   12 mg  88.9 g      []    5 g     12 g  0.12 g       3 g     100 UI     180 mg


text:
Q: Navigate back and show snackbar I want to show SnackBar when the page1 is showing. When the user navigates from page2 to page1.
But i works only from page1 to page2
That ist my Code
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text(
                ' Homepage',
              ),
            ),
            body: Center(
              child: RaisedButton(
                ***onPressed: () {
                                Navigator.push(context,
                                    BouncyPageRoute3(widget: Page2()));
                              }***
                child: Text('go to Page2'),
              ),
            )));
  }
}

class BouncyPageRoute3 extends PageRouteBuilder {
  final Widget widget;

  BouncyPageRoute3({this.widget})
      : super(
            transitionDuration: Duration(milliseconds: 700),
            transitionsBuilder: (BuildContext context,
                Animation<double> animation,
                Animation<double> secondaryAnimation,
                Widget child) {
              animation =
                  CurvedAnimation(parent: animation, curve: Curves.ease);

              return ScaleTransition(
                scale: animation,
                alignment: Alignment.center,
                child: child,
              );
            },
            pageBuilder: (BuildContext context, Animation<double> animation,
                Animation<double> secondaryAnimation) {
              return widget;
            });
}

When you use the RaisedButton on Page2 to return to HomePage, i want that a SnackBar on HomePage to show
I used also BouncyPageRoute3, that ist for the animation.

A: try this:
class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            ' Homepage',
          ),
        ),
        body: Center(
          child: RaisedButton(
        onPressed: () async {
          await Navigator.of(context).push(
            PageRouteBuilder(
              pageBuilder: (c, a1, a2) => Page2(),
              transitionsBuilder: (c, animation, a2, child) {
                var begin = Offset(0.0, 1.0);
                var end = Offset.zero;
                var curve = Curves.ease;

                var tween = Tween(begin: begin, end: end)
                    .chain(CurveTween(curve: curve));

                return SlideTransition(
                  position: animation.drive(tween),
                  child: child,
                );
              },
              transitionDuration: Duration(milliseconds: 2000),
            ),
          );
          showSnackBar();
        },
        child: Text('go to Page2'),
      ),
        ));
  }

  showSnackBar() {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("page 1")));
  }
}

in page 2:
RaisedButton(
        child: Text('go to homepage '),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),


text:
Q: Python Read Directory And Output to CSV I am just trying to read a directory and out put the file names to a csv.  The directory read works fine.  It is when I try to write to the csv that I am getting this error.
line 148, in _dict_to_list
wrong_fields = rowdict.keys() - self.fieldnames
AttributeError: 'str' object has no attribute 'keys'
import os
import csv

path = 'F:\Production\FocusPoint'
filename = 'storage.csv'
fields = ['Name']

with os.scandir(path) as listOfEntries:
    for entry in listOfEntries:
        if entry.is_file():
            f = (entry.name)

with open(filename,'w', newline='') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames= fields)
    writer.writeheader()
    writer.writerows(f)

A: Your variable fields is not a dictionary. So csv.DictWriter will not work. How about?
writer = csv.writer(csvfile)


text:
Q: 6 different time series using np.random.norm I want to use the np.random.norm function for 6 different means and standard deviations. I did this to get the means and standard deviations:
stdev_rebuilt_ts = []

mean_rebuilt_ts = []

#noise_rebuilt_time_series = []

for basin in range(6):
    stdev_rebuilt_ts.append(np.std(merge_months_detrended_1992_2016[basin,:]))
    mean_rebuilt_ts.append(np.mean(merge_months_detrended_1992_2016[basin,:]))

stdev_rebuilt_ts = np.array(stdev_rebuilt_ts)
mean_rebuilt_ts = np.array(mean_rebuilt_ts)

Which works and and gives:
print(mean_rebuilt_ts)
print(stdev_rebuilt_ts)

[4.1007996e-07 3.0199686e-07 1.5735627e-07 8.7420142e-09 1.3732911e-06
 1.6403199e-06]
[7.070564   4.4405646  1.2779348  0.16246584 5.2273583  3.023601  ]

Using the mean and standard deviations, for the first mean and first standard deviation, I want one time series, like np.random.norm(mean_rebuilt_ts[0],stdev_rebuilt_ts[0],time_months[-300:].size), and then another time series for mean_rebuilt_ts[1], [2], etc.
I tried a nested for loop:
mean = []
stdev = []

noise_rebuilt_time_series = []

for basin in range(6):
    mean.append(np.mean(merge_months_detrended_1992_2016[basin,:]))
    stdev.append(np.std(merge_months_detrended_1992_2016[basin,:]))
    for i in mean:
        for j in stdev:
            noise_rebuilt_time_series.append(np.random.normal(i,j,time_months[-300:].size))

noise_rebuilt_time_series = np.array(noise_rebuilt_time_series)

But it makes only one time series of the size 91, 300, rather than of the shape 6,300.

A: It appears as though you are just overwriting the noise_rebuilt_time_series each time.  For each mean you are iterating over all the stdevs which sounds like that is unintended.
noise_rebuilt_time_series = np.zeros((6,300))
for c,(i, j) in enumerate(zip(a,b)):
    noise_rebuilt_time_series[c] = np.random.normal(i,j,time_months[-300:].size)


text:
Q: imagem responsiva - aparecendo uma linha de pixel quando passa o mouse Estou tentando ajustar uma imagem com borda dentro da tabela, mas ao redimensionar a janela e ao passar o mouse aparece uma linha de pixel na vertical no lado direito da imagem. Tentei corrigir removendo margem e espaçamento na div, imagem, tabela etc mas a linha continua aparecendo
Não sei como faço para que essa linha desapareça
HTML abaixo

        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="newcss.css" rel="stylesheet" type="text/css">

Descreve sobre a imagem

Descreve sobre a imagem

Descreve sobre a imagem

CSS abaixo
@charset "utf-8";

body{
    font-family: fonteTrebuchet;
    color: #333;
    padding: 0px;
    margin: 0px;
    overflow: hidden;
}
nav#item .table {
    padding: 0px;
    margin: 20px auto 20px auto;
    width: 100%;
    display: table;
}
nav#item .tr {
    display: table-row;
}
nav#item .td {
    text-align: center;
    padding: 4px;
    margin: 0px;
    width: 33%;
    display: table-cell;
}
nav#item a{
    padding: 0px;
    margin: 0px;
}
nav#item div.opacidade{
    background: #111;
    padding: 0px;
    display: inline-block;
}
nav#item div.opacidade:hover img.imagem {
    border: solid 1px #d1d1d1;
    opacity: 0.7;
}
nav#item div.opacidade img.imagem {
    border: solid 1px #ddd;
    width: auto;
    display: block;
    -webkit-transition: all 1s linear;
    -moz-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -o-transition: all 1s linear;
    transition: all 1s linear;
}
nav#item .imagem{
    width: auto;
    max-width: 100%;
}
nav#item .sub-titulo{
    font-size: small;
    padding: 0;
    margin: 10px 0px 0px 0px;
}

A: As imagens com as bordas está ultrapassando 2 pixels na largura da div.opacidade, fazendo com que, no efeito de transparência, o fundo preto, do contêiner, não "cubra" toda a imagem, ou seja, 2 pixels à direita da imagem está fora do fundo preto, formando uma "linha vertical" (na verdade 2 pixels à direita fica com o fundo branco da página).
Você resolve isso colocando box-sizing: border-box; na imagem para que a borda fique também dentro da área do fundo preto:
nav#item div.opacidade img.imagem {
    border: solid 1px #ddd;
    width: auto;
    display: block;
    -webkit-transition: all 1s linear;
    -moz-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -o-transition: all 1s linear;
    transition: all 1s linear;
    box-sizing: border-box; /* AQUI! */
}

Saiba mais sobre o box-sizing no MDN.
Com box-sizing:
Veja que a imagem se encaixa perfeitamente no contêiner.

Sem box-sizing:
A imagem extrapola (à direita) a área do contêiner por causa das bordas.


text: Q: List running services along with EXECSTART command My main goal is to be able to find the service linked with a given process id assuming process was started by a service. In this direction, I'm trying to find a way to list all running services along with there EXECSTART command or it's pid so I could use grep after to narrow down. Please help me out.


text:
Q: If $G$ is a finite group then ... Let $G$ be a finite group. Let $I(G)$ be the set of elements of $G$ that have order 2. Suppose $|I(G)| \ge \frac 3 4 |G|$. Let $x \in I(G)$. We note $I_x(G)$ the subset $\{xg \in I(G)\}_{g \in I(G)}$. Show that $|I_x(G)| \ge \frac 1 2 |G|$.
I have shown that $I_x(G) \subset C_G(x)$ but I have no idea how to continue from there.. Can somebody please give me a hint (I'm not asking for the answer, I'd like to find that myself).

A: You are looking at the intersection of two sets, both of which have size $\ge \frac{3}{4}|G|$.


text:
Q: Is dagger2 necessary in firebase project? I know firebase + android architecture 1.0 is a good combination.
but how about firebase + android architecture 1.0 + dagger2?
I am creating a social app and I have been studying on the Internet alone and I am confused.
I did a lot of research. but I did not get a clear answer.

A: There is no requirement to use Dagger in a project that uses Firebase. Whether you do is a matter of personal preference.


text:
Q: Laravel commands and jobs I was wondering what the difference is between the different command-like classes in Laravel 5.1. As far as I can tell Laravel 5.1 has the following available:

*

*Console commands (artisan make:console)

*Commands (artisan make:command)

*

*Handlers (artisan make::command --handler)

*Jobs (artisan make:job)

I have come straight from 4.2 to 5.1 so I don't know what happened in between 4.2 and 5.1, but I have been told that the middle one (just commands) are basically not really supposed to be used any more - they are in from when queue-able jobs became 'commands' in 5.0, but Laravel since decided against this, and they're just in for compatibility. However, I'm not 100% on this point, so clarification would be appreciated.
My specific use-case is that I want a place to put a self-contained 'runnable' task. For example, something that will remove files older than 5 days from a given directory (but it could do anything).
At first this sounds like a console command - I want to be able to run it from artisan, for a start. But I may also want it on a schedule (great, artisan schedule:run runs console commands). But I may also want to execute it asynchronously from code. Console commands can be run synchronously with Artisan::call(), but for asynchronous, this is (I think) where queues come in, and it suddenly has to be a job.
Okay so we have a job. We can now add it to a queue from code, but how do we execute it as an artisan command (synchronously)? Can I just create a thin console command and add the DispatchesJobs trait (or the code therein) to it, and then dispatch the job? Does the job always have to go on a queue, or can we make a job execute synchronously (and, ideally, output to the console command's output?) The same question goes for running it on a schedule - am I supposed to create this console command and add that to the scheduler, or can I make the scheduler run the job directly?
And finally, we have 'commands' that aren't console commands nor are they jobs. As I said before, people tell me these are just hangers-on from a Laravel 5.0 code change that was (kinda) reverted. But the artisan make command still exists for them, so they can't be that dead. Also, what's the deal with a self handling command (the default, comes with a handle method) and one that 'requires' a handler class (run artisan make:command --handler)? How do you actually make these execute? Manually with (new App\Command\SomeCommand)->handle(); or (new App\handlers\SomeCommandHandler)->handle(new App\Command\SomeCommand), or is there some hidden system I don't know about (maybe they can be dispatched using the job/queue dispatcher)? Also you can create 'queued' commands artisan make::command --queued, so how do these differ, too?
I guess my question boils down to the following:

*

*What is the real (semantic and functional) difference between them all?

*What is the correct way to 'run' them?

*Which is best for my purposes of a generally-standalone bit of code that needs to be run, in whatever manner I feel appropriate?

I found information in the documentation on how to use queues and create console commands, but nothing on exactly when to use them or really anything on command classes and handlers.

Related but not exactly the same (also, it's unanswered): Laravel 5.1 commands and jobs

A: Console Commands
Laravel has had console "commands" for some time. They are basically unchanged, and work as they always have. In simple terms, they are the equivalent of routes for the command line - the entry point into the application. They are in no way related to...
The Command Bus
Laravel 5.0 introduced an implementation of the Command Bus pattern - Command Bus Commands. (I believe these were renamed to Jobs because of the resulting confusion between them and CLI Commands).
A command bus as two parts - an object that represents a command to be executed, with any and all data it needs (the job), and a class to execute the command (the handler).
The Handler
In laravel, you can declare a job to be self handling - that is, it has a handle method itself.
If you want to register a command handler, you can call the following in a service provider:
app('Illuminate\Bus\Dispatcher')->maps(['Job' => 'Handler']);

where Job is the class name for the job, and Handler is the class name for the handler.
The handlers directory in laravel 5.0 was a way of implicitly declaring those relationships (ie. EmailCommand in the commands folder would have an EmailCommandHandler in the handlers folder).
Dispatching a Command
You can use the following to dispatch a command.
app('Illuminate\Bus\Dispatcher')->dispatch(new EmailPersonCommand('email@you.com', $otherdata));

Queues
Jobs, by default, will run as soon as they are called (or dispatched). Setting them as ShouldQueue will always pass them to a queue when they are dispatched.
If you want to run them synchronously sometimes, and asynchronously other times, you can call $dispatcher->dispatchToQueue($job) when you want them to be queued. This is all that happens internally when you pass a ShouldQueue job to ->dispatch().
edit: To Queuing (or not)
I've just had a longer look at the dispatcher. The dispatch method checks if the command is a ShouldQueue, and either forwards it to dispatchToQueue or dispatchNow. You can call either of those methods directly instead of dispatch with your command should you wish to override the default behaviour.
So in your case, depending on what the "default" behaviour of your job is (ie. will it normally be queued?) either:
- have it ShouldQueue, and use dispatchNow in the CLI Command.
- don't have it ShouldQueue, and use dispatchToQueue where you call it in your code.
From the sounds of it, i'd do the former.

A: I see those "objects" like so: (I added some code examples from one of my side projects)
Console
Things I want to execute from the command line (As you mentioned with your example with "Delete Files older than x"). But the thing is, you could extract the business logic of it to a command.
Example: A console command with fires a command to fetch images from Imgur. The Class FetchImages  contains the actual business logic of fetching images.
Command
Class which contains the actual logic. You should also be able to call this command from your application with app()->make(Command::class)->handle().
Example: Command mentioned in Example 1. Contains logic which does the actual API calls to Imgur and process returned data.
Jobs
I made this app with Laravel 5.0 so jobs weren't a thing back then. But as I see it, Jobs are like commands but they are queued and can be dispatched. (As you may have seen in those examples, those commands implement your mentioned Interfaces SelfHandling and ShouldBeQueued).

I see myself as an experienced Laravel Developer but those changes in Commands and Jobs are quite difficult to understand.
EDIT:
From the Laravel Docs:

The app/Commands directory has been renamed to app/Jobs. However, you are not required to move all of your commands to the new location, and you may continue using the make:command and handler:command Artisan commands to generate your classes.
Likewise, the app/Handlers directory has been renamed to app/Listeners and now only contains event listeners. However, you are not required to move or rename your existing command and event handlers, and you may continue to use the handler:event command to generate event handlers.
By providing backwards compatibility for the Laravel 5.0 folder structure, you may upgrade your applications to Laravel 5.1 and slowly upgrade your events and commands to their new locations when it is convenient for you or your team.

A: Just an addition to the actual answers.
Jobs in Laravel >= 5.1 are Commands Bus in Laravel 5.0.
It is only a naming change because of the confusion between Console\Commands (commands run from the console) and The Command Bus (containing Commands) for the Application Tasks.
You should not confound :

*

*Command Bus : used for "encapsulating tasks your application" (from laravel 5.0 doc) which is now renamed a Jobs

*Console\Commands : used for "Artisan [...] the command-line interface included with Laravel" (from laravel 5.1 docs) which is unchanged in Laravel since 4.x


text:
Q: use javascript variable in href went wrong - why? there are many Questions and Answers out there for how to get a Javascript Variable into the href tag, but I am running into a Problem which no one seems to have.
I have a slider and depending on what position the slider is set, the value should be taken into the href.
So if the sliders value is 50 the link should be "http//testurl.de/50"
However I get always back "http://testurl.de/[object%20HTMLSpanElement]" And don't know what's wrong.

<input type="range" min="1" max="100" value="50" class="slider" id="ValueSlider">

Value:

link

Any help would be much appreciated! :)
Best Mo

A: You have two ways to fix this, and you actually do them both already a few lines above that code.

*

*SetValue is the ID of your span element, so to get the data from that element, you can use SetValue.innerHTML, SetValue.innerText or a few others.

*Or, you can just reference the input element you have there (looks like you call it slider) and grab slider.value again.

link
// or
link
// or
link
// or
link

A: You should use output.innerHTML and not SetValue on the link, as bellow:
link

A: simply this

const slider = document.getElementById("ValueSlider")
  ,   output = document.getElementById("SetValue")
  ,   aLink  = document.getElementById("SliderLink")
  ;
function SetSliderVal() {
  output.textContent = slider.value
  aLink.href         = 'http://testurl.de/'+slider.value
  aLink.textContent  = 'link = '+slider.value
}
SetSliderVal();

slider.oninput = SetSliderVal

  <input type="range" min="1" max="100" value="50" class="slider" id="ValueSlider">

Value:

link


text:
Q: One Button To Toggle Form's BackGround Color I am a novice in C# WindowForm projects, and I am facing some issues on how to toggle 'one button' into changing between 2 backcolors in C# WindowForm.
In order to toggle 'one button', I am required to use IF function in this assignment. However, my problem is that I do not know how to transition from color1 to 2 by pressing the button when running the code, I somewhat know the syntax structure of IF and else.
Could anyone help please?
namespace draft
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
    }

    private void btn1_Click(object sender, EventArgs e)
    {
      bool btnclick = true;
      if (btnclick == true)
      {
        BackColor = Color.Purple;
        return;
      }
      if (btnclick == false)
      {
        BackColor = Color.Green;
        return;
      }
    }
  }
}

A: As you are declaring btnclick on click event and setting it to true, it will be true every time and only if block will be executed. Check current background color and change it.
private void btn1_Click(object sender, EventArgs e)
    {
        if (BackColor == Color.Purple)
        {
            BackColor = Color.Green;
            return;
        }
        else
        {
            BackColor = Color.Purple;
            return;
        }
    }

A: Here's the simplest code:
private void btn1_Click(object sender, EventArgs e)
{
    BackColor = BackColor == Color.Purple ? Color.Green : Color.Purple;
}


text:
Q: Testing whether a polygon is simple or complex For a polygon defined as a sequence of (x,y) points, how can I detect whether it is complex or not?  A complex polygon has intersections with itself, as shown:

Is there a better solution than checking every pair which would have a time complexity of O(N2)?

A: See Bentley Ottmann Algorithm for a sweep based O((N + I)log N) method for this.
Where N is the number of line segments and I is number of intersection points.

A: There are sweep methods which can determine this much faster than a brute force approach.  In addition, they can be used to break a non-simple polygon into multiple simple polygons.
For details, see this article, in particular, this code to test for a simple polygon.

A: In fact, this can be done in linear time use Chazelle's triangulation algorithm. It either triangulates the polygon or find out the polygon is not simple.


text:
Q: Grub not loading after Windows 8 Install
Possible Duplicate:
How can I repair grub? (How to get Ubuntu back after installing Windows?)

My system was configured to dual boot Ubuntu 12.04.1 LTS and Windows 7. Today I got my hands on the MSDN release of Windows 8 and I installed it over my Windows 7. Now the computer just boots to Windows 8 directly without loading the GRUB screen.
So I followed the steps as suggested in: https://help.ubuntu.com/community/RecoveringUbuntuAfterInstallingWindows. Running this command:
    ls -l /dev/disk/by-label/

gives the following output:
    total 0
    lrwxrwxrwx 1 root root 10 Sep 11 07:51 Entertainment -> ../../sda2
    lrwxrwxrwx 1 root root 10 Sep 11 02:45 PENDRIVE -> ../../sdb1

Also fdisk -l command gives this as the output:
    Disk /dev/sda: 320.1 GB, 320072933376 bytes
    255 heads, 63 sectors/track, 38913 cylinders, total 625142448 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk identifier: 0x1246aa23

       Device Boot      Start         End      Blocks   Id  System
    /dev/sda1   *        2048   319582199   159790076    7  HPFS/NTFS/exFAT
    /dev/sda2       319582208   602906623   141662208    7  HPFS/NTFS/exFAT
    /dev/sda3       602908672   625135615    11113472   83  Linux

    Disk /dev/sdb: 1939 MB, 1939865600 bytes
    64 heads, 63 sectors/track, 939 cylinders, total 3788800 sectors
    Units = sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disk identifier: 0xc3072e18

       Device Boot      Start         End      Blocks   Id  System
    /dev/sdb1   *        2248     3788799     1893276    c  W95 FAT32 (LBA)

So I assume that I have to run this: sudo grub-install /dev/sda3 to get GRUB up and running. But I am getting this error:
    /usr/sbin/grub-probe: error: cannot find a device for /boot/grub (is /dev mounted?).

Can anyone please guide me in the right direction? The current Ubuntu installation is far too customized to my needs to lose it to a boot manager issue! Any help is much appreciated!

A: The GRUB needs to reside in front of all partitions on the device, therefore you should run
sudo grub-install /dev/sda

whereas using /dev/sda3 would install it only to the third partition. See the guide Recovering Ubuntu After Installing Windows you referred to:

From here, find only the drive name, ignore the partition number, that is, for partitions labeled "root", "data2", "fat", "home" and "swap" it's all still just sda. This is due to the fact that GRUB is installed in the MBR of the drive, and not on a partition.

A: You might have to run
sudo grub-install /dev/sda

instead. It will find your /boot/ folder on any of the partitions.
If this does not work, you can try the following (assuming you do not have a separate boot partition, as it should show from your commands):
Boot into the live cd and open a terminal.
sudo mount /dev/sda3 /mnt

This will mount your ubuntu install to /mnt
Then run this command
sudo grub-install /dev/sda --root-directory=/mnt/boot/

This will tell grub that it should install grub to sda, and that it should not look for /boot/, as this is located on sda3.


text:
Q: Screenreader to automatically read the h1 - React JS When landing on the page screenreader to automatically read the h1 tag. But in my app heading is read only on tab press.
Below are few methods I tried which didn't work.
<fieldset>

        Component B
      {' '}

  </fieldset>

Below is my stackblitz link, when user clicks on the Next button it should read the Heading text.
https://stackblitz.com/edit/react-ts-hd6en7


text:
Q: Hard time interpreting r output, p value confusion?
I think I'm overthinking it, but this p-value for the exp.c:anx.c interaction (3.84e-09) is significant, right? In other words, it's much smaller than 0.001? Irrational numbers are confusing for me, and I also have a negative t-value that is throwing me off.
I'm also confused at the bottom where it shows: p-value: < 2.2e-16, what does this mean? Overall for the model?

A:
p-value for the exp.c:anx.c interaction (3.84e-09) is significant, right?

Yes, at the typical $\alpha=0.05$ level (i.e. $p=3.8 \times 10^{-9} \ll 0.05$) ($\ll$ means "much less than")

In other words, it's much smaller than 0.001?

Not sure what you mean here.  Do you mean you want to use a cutoff of $\alpha=0.001$?  If so, then yes, $3.8 \times 10^{-9} \ll 0.001 $.

Irrational numbers are confusing for me

Not sure what you mean here. Mathematically, an "irrational" number is something like $\sqrt{2}$, a number that can't be represented as a ratio of whole numbers. Maybe you're confused by the 3.84e09 notation, where AeB stands for "A times 10 raised to the power of B" (?)

and I also have a negative t-value that is throwing me off.

A negative t-statistic means that the estimated parameter value is that many standard errors below zero. There's no difference between positive and negative t-statistics for standard two-tailed significance tests.

I'm also confused at the bottom where it shows: p-value: < 2.2e-16, what does this mean? Overall for the model?

Yes, that's a p-value for the full model vs. the null hypothesis of a constant model with $\hat y$ equal to the mean of the response variable.


text:
Q: State/Toggling variables in tmux I was wondering if there is a way of defining a state variable in ./tmux.conf, such that depending on this variable, the keyboard binding would invoke a different command.
For example, I would like to use M-F to toggle the maximization of a pane in tmux (if the pane is not maximized, M-F would maximize it, otherwise it will unmaximize it)
Here is the pseudo-code that I have so far:
# Maximize pane: -------
# IF PANE_MAXIMIZED=False:
# THEN: PANE_MAXIMIZED=True, and:
bind -n M-F new-window -d -n tmux-zoom  \; swap-pane -s tmux-zoom.0 \; select-window -t tmux-zoom

# Unmaximize pane -------
# IF PANE_MAXIMIZED=True:
# THEN: PANE_MAXIMIZED=False, and:
bind -n M-F last-window \; swap-pane -s tmux-zoom.0 \; kill-window -t tmux-zoom

A: You can use the run-shell command to execute arbitrary shell commands, so this is certainly possible. This answer has a great example of this.
If all you're looking for is to toggle maximizing a window, as of version 1.8 that's a native tmux feature by use of the -Z flag to resize-pane (see this answer on superuser).
It's bound to tmux-prefix-z by default on my installation (via Homebrew on OS X).


text:
Q: Background image doesn't display in CodeIgniter My background image call by css
css
 background: url('../images/slider/download.jpeg') no-repeat 0 0!important;

and location like
C:\xampp\htdocs\ivory2\resources\images\slider

here the image does not take why?
IVORY2 is my project name


text:
Q: Successfully push the record into Firebase, but Google Chrome hangs while pushing the data This is the controller file of my app. It adds the data perfectly, but when it reaches the then key word google chrome hangs but key parameter is also added to the data base. I can't figure out where the problem is.
 .controller('recordsCtrl', ['$scope','$firebaseArray',function($scope,$firebaseArray) {

        $scope.records = $firebaseArray(rootRef);

        //show form
        $scope.showAddForm = function(){
            $scope.addFormShow = true;
        }

        // hide form
        $scope.hide = function(){
            $scope.addFormShow = false;
        }

        // submit contact
        $scope.addFormSubmit = function() {

            console.log("adding form...")
            // Assign values
            if ($scope.lname) { var lname = $scope.lname; } else { var lname = null; }
            if ($scope.mname) { var mname = $scope.mname; } else { var mname = null; }
            if ($scope.fname) { var fname = $scope.fname; } else { var fname = null; }
            if ($scope.email) { var email = $scope.email; } else { var email = null; }      if ($scope.conId) { var conId = $scope.conId; } else { var conId = null;}

            // Build Object
            $scope.records.$add({

                fname: fname,
                lname: lname,
                mname: mname,
                email: email,
                company: company,
                conId: conId

            }).then(function(rootRef) {
                ***//this is not printed in the console but the key is assigned to the database***
                console.log("Assign root key");
                var id = rootRef.key();
                console.log("Added Record with ID: " + id);

                // clear Form
                clearFields();

                // Hide Form
                $scope.addFormShow = false;

                // send message to use
                $scope.msg = "Record Added";
            });
        }

    }]);

A: My team ran into this issue when we updated to Firebase 3.7.x. I believe this is a known bug.
Try downgrading to Firebase 3.6.x.


text:
Q: Converting between function pointer types I have a program that has to store functions as void (*) (void*). Creating functions with that signature leads to code duplication (usually the first line is to cast the void pointer to the correct type) and reduces type safety (the void pointer can be cast to anything, such as the wrong type), so I was wondering if I can take a function of type void (*)(T*), and then convert it to a void(*)(void*) and call it like that, in a way similar to this:
#include <iostream>
#include <string>

void printer(std::string* string)
{
    std::cout << *string << std::endl;
}

int main()
{
    //Cast the function to a one that takes a void pointer
    auto func = reinterpret_cast<void(*)(void*)>(&printer);
    //Create a string and call the function with it
    std::string string = "Hello World";
    func(&string);
    return 0;
}

The above code compiles and runs fine (on ideone) but I was wondering if it's at all standards compliant or if it's undefined behaviour and is just working correctly for my specific example and OS

A: This is undefined behavior.
[expr.call]/1:

Calling a function through an expression whose function type is different from the function type of the called function's definition results in undefined behavior.

[expr.reinterpret.cast]/6:

A function pointer can be explicitly converted to a function pointer of a different type. Except that converting a prvalue of type "pointer to T1" to the type "pointer to T2" (where T1 and T2 are function types) and back to its original type yields the original pointer value, the result of such a pointer conversion is unspecified.

C++ doesn't allow for very many function casts at all to work, even for things you might think would be safe like changing const details.  When you need such a thing, use an explicit wrapper function instead.  A non-capturing lambda could be one easy way to write one without naming it; or you could define a general template to wrap other functions in a way you need.
[Strangely, C++17 allows an implicit conversion from a pointer to nonthrowing function to a pointer to potentially-throwing function even though C++17 makes those different function types - but then doesn't have any wording I can see saying you're allowed to actually call the function via that converted pointer.]

A: Behaviour of doing so is undefined. Standard (draft) says:

[expr.reinterpret.cast] A function pointer can be explicitly converted to a function pointer of a different type. [Note: The effect of
  calling a function through a pointer to a function type (9.2.3.5) that is not the same as the type used in the
  definition of the function is undefined. — end note] Except that converting a prvalue of type "pointer to T1"
  to the type "pointer to T2" (where T1 and T2 are function types) and back to its original type yields the
  original pointer value, the result of such a pointer conversion is unspecified. [Note: See also 7.3.11 for more
  details of pointer conversions. — end note]

You could use a lambda:
void(*func)(void*) = [](void *string) {
    printer(static_cast<std::string*>(string));
};


text:
Q: Read everything that's displayed in the terminal I am creating a terminal application that writes stuff to the terminal. And in order to test it, I really should test what's actually displayed in the terminal. Is there a way to read the data that's actually displayed in the terminal somehow?
The terminal must be some file somewhere or something, so there must be some way to read what's there.
cat /dev/tty

seems to give me a stream of data that's in there..But I don't want to see key strokes, just what I have written.

A: A few terminal programs provide screen dumps (such as xterm), but most do not (see Existing command line text on screen to file? (non-graphical Linux) for instance).  You could make a screenshot using a tool such as gimp, but that will not tell you what the actual characters are.  For development, I need to know that.
I'd use script to record the output into typescript.  You can cat it back to the screen (or use less -R, if the escape sequences are simple enough).  For more complicated things or long traces, I use other tools:

*

*slowcat to slow down the cat progress

*vile-pager to filter the escapes into readable form (better than less — color sequences work across lines, but still limited to single-line cursor-movement).  That's a filter using vi-like-emacs, via a special-purpose utility.

To illustrate the difference, here is a screenshot of less -r on a typescript file from running apt-get update on one of my Debian machines:

In contrast, vile-pager highlights the places where the text was overwritten:

Either way (less or vile), if your application moves the cursor around the screen, the only way to review the output would be to use cat/slowcat/etc.

A: One option is to use the tee tool before all the commands you want to track. This way, you can store all your output in a selected log file.
See the example below where I save all the bash output to a text file called log.txt:
bash | tee log.txt
echo 'hello world'
ls
exit
cat log.txt

You can exit the new BASH session with a CTRL+D or simply type exit (as shown in the example above) when you're done.
If you are only looking for the commands actually passed to the terminal (it wasn't clear to me if this was what was desired by the original question), you can always just run history or check ~/.bash_history

A: PARAMETER_EMMC=10
while [ $PARAMETER_EMMC -eq 10 ]
    do
    read -u $USBFPI -r -n 3000 -t .3  text
        if [[ $text == *"text read from USB"* ]];  then

Execute
fi
done


text:
Q: Eclipse PDE Build: how to organize plugins and features with the "fetch" step skipped? I'm building my Eclipse plugin by means of Eclipse PDE build, i e I've defined all the required targets in "custom.xml"
But I do not want to fetch my plugins from a repository, so I'm skipping this step. However, all plugins have to be located under plugins directory, and all the features have to be located under features folder accordingly. This is actually done with map files but I've skipped the step. So, I'm copying my elements as follows:
<target name="init">

     <mkdir dir="${buildDirectory}" />
     <mkdir dir="${buildDirectory}/plugins" />
     <mkdir dir="${buildDirectory}/features" />

     <copy todir="${buildDirectory}/${type}s">
         <fileset dir="${buildDirectory}/../">
         <include name="${id}/**" />
         </fileset>
     </copy>
</target>

<target name="preGenerate">
     <antcall target="allElements">
        <param name="genericTargets" value="${builder}/customTargets.xml"/>
        <param name="target" value="init"/>
     </antcall>
</target>

That works perfect! The only thing I do not like is that in "allElements" target I have to specify the set of all plugins and features I have. And I do this only for the goal of copying. Specifying in the elements only one 'main' feature is enough for the rest of the build process.
So, my question is: how to specify only one 'main' feature without need of specifying the rest set of plugins (which are already listed within this feature) to prepare the Eclipse build process? Or, it is possible to start the build without that copying? Probably, specify map files somehow?
Thanks in advance!

A: Why you have allElements.xml? PDE itself creates a dummy feature project to build the stuff you ask it to. Is it an RCP app that you wish to build? If yes, you can use a product configuration to invoke the build. If not, you can create a dummy root level  feature project and add everything to it, generate its build.xml and headlessly build it.
You may want to have a look at this post series (apologies for shamelessly forwarding you  to my blog) .


text:
Q: How to control the outer margin on Flot graph I am having some difficulties figuring out how to control the outer margin on the Flot graph I have implemented. I have tried many options; minBorderMargin, margin, axisMargin, labelMargin. Neither, set individually or all together, didn't change a thing.
Want I want to achieve is complete control over the width of the right margin.
As you will see in this example, there's a margin to the right, even with minBorderMargin set to 0 (zero).
Here's the source code:
var $wrapper = $('<div />').addClass('wrapper'),
    $graph = $('.graph'),
    data = {
        color: '#dba400',
        hoverable: true,
        data: [
            // [1, 215000],
            // [2, 205000],
            // [3, 0],
            // [4, 70000],
            [35, 270000],
            [36, 105000],
            [37, 60000],
            [38, 0],
            [39, 110000]
        ]
    },
    options = {
        xaxis: {
            color: '#f0f0f0',
            min: 34.5,
            max: 39.5,
            tickColor: 'transparent',
            tickFormatter: function(val) {
                return 'RND' + val;
            }
        },
        yaxis: {
            color: '#f0f0f0',
            tickColor: null,
            tickFormatter: function(val) {
                var units = ['', 'K', 'M'],
                    unit = units.shift();

                while (val > 1000 && units.length > 0) {
                    val /= 1000;
                    unit = units.shift();
                }

                return val + unit;
            }
        },
        grid: {
            borderWidth: 0,
            minBorderMargin: 0
        },
        hooks: {
            processOffset: function(plot, offset) {
                console.log(plot, offset);
            }
        },
        series: {
            points: {
                radius: 0,
                lineWidth: 0
            }
        }
    };

$graph.append($wrapper);
$.plot($wrapper, [data], options);

Bonus question: Is there an easy way to left align first tick label and right align last tick label?

A: If you can't find a way to alter the plot, you might consider placing the placeholder div within another div that has overflow set to hidden.  Then you can 'chop off' extra margin on any side by controlling the size of the outer div or placement of the inner.


text:
Q: How to implement timer callback independent of the system time in C++ using boost I need to create a timer which will call my function periodically (e.g. every 50ms).
BUT the problem is I will need to change the system time while the timer is running.
I would like to do this using boost so that the code is portable. Otherwise I am running it on Linux machine.
Things I have tried:

*

*Tried using a while loop and thread::sleep. Calculated the sleep time using steady_clock.

*Also tried using deadline_timer

Both of these stop working when the system time is adjusted.
Question:
Is there any way (using boost preferably) to create a callback timer which is independent of the system time? (Bonus karma for sample code)

A: Seems to be a bug under linux. You need to use a sleep method, that uses the CLOCK_MONOTONIC (boost::this_thread::sleep uses CLOCK_REALTIME). boost::this_thread::sleep_for with the boost chrono library should do this, because it uses the monotonic clock.
while (true) {
    // Call your function here.
    boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
}

Alternatively you could use boost::this_thread::sleep_until. With that function you could use a custom clock.
But the underlying CLOCK_MONOTONIC could be influenced by adjtime(). Therefore you could use CLOCK_MONOTONIC_RAW as a linux only alternative.
One more possibility: If you are able to use C++11 you could use std::chrono::steady_clock to get a strict monotonic clock.
auto start = std::chrono::steady_clock::now();
while (true) {
    std::cout << (start - std::chrono::steady_clock::now()).count() << std::endl;
}

The output here will not change, if the system clock gets adjusted. But do not use this with boost::this_thread. Use it with std::this_thread::sleep_for to get proper results.
The last possibility is just to use usleep or nanosleep.
But be aware, that you will not be able to interrupt the sleep with the last two options (STL and OS specific calls).


text:
Q: input type not working in IE 7 & 8 with anchor  &  tags Following is my code:
<a href="<?php echo $url; ?>" id="quotenow" class=""> <input type="submit" value="Quote Now" class="">

A: Your code is wrong, you don't need anchor tags around an input element. It should look something like:
<a href="<?php echo $url; ?>" id="quotenow" class="">My Anchor

Or, if you wanted an onclick event on the button then you can do:

<button onclick="window.open('<?php echo $url; ?>', '_self'); return false;">My Button</button>

Here are the rules with that The element input must not appear as a descendant of the a element. Here is a demo.


text:
Q: How do I proceed with the following coulomb integral? I am trying to solve the $H_{2}^{+}$ ion problem using Fourier transform approach.
The Hamiltonian that I am trying to solve is as follows, $$H=-\frac{\hbar^{2}}{2m_{e}}\nabla^{2}_{e}-\frac{e^{2}}{4\pi\epsilon_{0}|\vec{r}-\vec{R}|}-\frac{e^{2}}{4\pi\epsilon_{0}|\vec{r}|}+\frac{e^{2}}{R}$$ I have put one of the nucleus at the origin. To solve   this I have used the following trial wave functions for the ground state $$\psi=c_{1}\psi_{s}(\vec{r})+c_{1}\psi_{s}(\vec{r}-\vec{R})$$ Here S represents the s orbital. I have excluded spin parts and make the nucleus stationary. To solve this I evaluated the  following integral.$$J=\int d^{3}\vec{r}\frac{1}{\pi a_{0}^{3}}\exp(-{2r/a_{0}})\bigg(\frac{e^{2}}{R}-\frac{e^{2}}{r'}\bigg)$$
where, $r'=|\vec{r}-\vec{R}|$ and Here, R is the distance of the second nucleus from the origin and first nucleus is already placed at the origin.
I used Fourier transform to solve this integral,
$$\frac{1}{\pi a_{0}^{3}}\exp(-{2r/a_{0}})=\frac{a^{4}}{8\pi^{3}}\int \frac{\exp(i\vec{k}\cdot \vec{r})}{(k^{2}+a^{2})^{2}}d^{2}\vec{k}$$ and $\frac{2}{a_{0}}=a$ and $\vec{r'}=\vec{r}-\vec{R}$ The other Fourier transform that is required is to solve this integral is ,$$\frac{1}{r'}=\frac{1}{2 \pi^{2}}\int\frac{\exp(i\vec{k'}\cdot \vec{r'})}{k'^{2}}d^{3}\vec{k'}$$ I really don't know how to get the following step,
$$J=\frac{e^{2}}{2 \pi^{2}}\int d^{3}\vec{k} \exp(i\vec{k}\cdot\vec{R})\Bigg(\frac{1}{(k^{2}+a^{2})}+\frac{a^{2}}{(k^{2}+a^{2})^{2}}\Bigg)$$ Now reverting back to the space coordinates we get the following answer $$J=\frac{e^{2}}{R}\exp(-2R/a_{0})\bigg(1+\frac{R}{a_{0}}\bigg)$$
Can someone explain how to get that intermediate step just before the final answer using the Fourier transform. I struggled a lot but I didn't get the answer. I followed the book "/Quantum  Mechanics B.K Agarwal & Hari Prakash PHI publication" chapter 17. Molecules , page number 366


text:
Q: How to know if child views are rendered in a region I'm working on an application that uses Backbone marionette. I have a layout containing regions which in turn contains child regions. In the onRender function of the parent region, the child regions are rendered by calling 'showChildView' function. I would like to set tab indexes after the child regions are rendered. Is there a way to know if my child regions are rendered?
I tried using onShow/onAttach on parent region's view. But no luck!

A: to check if the region "myRegion" is currently showing a view try
var childView = parentView.getRegion('myRegion').currentView;

then you can check if the view has been already rendered
if (childView && childView.isRendered) { ...

In your case, after the call of "showChildView" your child views should be rendered, aren't they?

A: In chrome dev tools you can check if the dom element for the region is showing up in the source code. If yes then your region is rendered.
Alternatively, you can also debug by adding a onRender() method in the child view and adding a console.log() statement inside it.


text:
Q: Multiple LinearLayouts inside LinearLayout not working properly I have few LinearLayouts inside a LinearLayout as follows:
<LinearLayout
android:layout_gravity="center|top"
android:padding="10dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:orientation="horizontal"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content">
    <TextView
        android:gravity="center"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />
    <Spinner
        android:minWidth="100dp"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

    </Spinner>
</LinearLayout>

<LinearLayout
    android:orientation="horizontal"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content">
    <TextView
        android:gravity="center"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />
    <Spinner
        android:minWidth="100dp"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

    </Spinner>
</LinearLayout>

<LinearLayout
    android:orientation="horizontal"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content">
    <TextView
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_height="match_parent" />
    <Spinner
        android:minWidth="100dp"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

    </Spinner>
</LinearLayout>

<LinearLayout
    android:orientation="horizontal"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="wrap_content">
    <TextView
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />
    <Spinner
        android:minWidth="100dp"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

    </Spinner>
</LinearLayout>

</LinearLayout>

now the layout looks all fine in Design window inside Android Studio but once the app is executed the layout is displayed twice on the device - once dead (not working at all) and once working like it should.
I've had a simple TextView inside the main LinearLayout before and it worked fine, but once removed it doesn't work anymore.
I can actually remove this behavior by adding a TextView with "layout_width" and "layout_height" set to "0dp" but there has to be a proper solution. I've already tried replacing the LinearLayouts w/ RelativeLayouts but that doesn't work either.

A: You're setting
android:layout_weight="1"
without setting weightSum in parent LinearLayout. Is that on Purpose?
Also, I suggest you to use ConstraintLayout instead of nested LinearLayouts.


text:
Q: Ubuntu Installation Root partition I have decided to install Ubuntu for office, programming and GFX along Windows 8.
I have made a USB - Bootstick and so on, created a 100GB partition for Ubuntu, so I wanted to install it on this partition, but he asks me for a root partition, but i still dont get what to do now.
Can u help me?
I am using Windwos 8 and have a Mainboard with UEFI.

A: Update for Ubuntu 18.04 and above
New installations of recent versions of Ubuntu does not use a separate swap partition any more. They use a swap file by default.
Original Answer
Some Basics
Ubuntu needs at least two partitions to work well. One is called the root partition denoted by / and is formatted ext4 and the other is called Swap with its own format. Windows does not understand these formats.
So you can't use Windows to create these partitions.
What to do?
The partition you created in Windows is not suitable for Ubuntu. Delete the 100GB partition you have created and leave the space unallocated.
When you install Ubuntu, it will find the unallocated space and create the partitions it needs automatically. The Swap will be a small partition (2-4 GB) used as virtual RAM and the rest of 100GB will be /.
See How do I install Ubuntu alongside a pre-installed Windows with UEFI?
and Ubuntu installation on Windows7 with D partition for more details.
Hope this helps


text:
Q: How to detect if SCNBox was touched in scenekit? How to detect if SCNBox was touched in scenekit? I am building a VR app

A: you can use this:
let tapGR = UITapGestureRecognizer(target: self, action: #selector(tapGesture(sender:)))
sceneView.addGestureRecognizer(tapGR)

@objc func tapGesture(sender: UITapGestureRecognizer) {

    let location: CGPoint = (sender.location(in: self.sceneView))
    let hits = self.sceneView.hitTest(location, options: nil)
    if let tappedNode : SCNNode = hits.first?.node {
        tappedNode.position.y += 0.5
        print(tappedNode)
    }
}


text:
Q: juju openstack juju-bootstrap not working properly I have configured juju with local and openstack. I followed the instructions here: Bootstrapping JuJu on top of an OpenStack private cloud for configuring juju on a private openstack deployment.
Juju spawns a new VM in openstack and it is visible in the horizon dashboard but the problem occurs when juju tries to ssh into the newly spawned VM for installing juju agent. This is what I get in the terminal:
Bootstrapping environment "openstack"
Starting new instance for initial state server
Launching instance
 - 66a39b56-5e47-495d-a3ba-5278f492cf14
Building tools to upload (1.25.0.1-trusty-amd64)
Installing Juju agent on bootstrap instance
Waiting for address
Attempting to connect to 192.168.5.3:22
ERROR failed to bootstrap environment: waited for 10m0s without being able to connect: ssh: connect to host 192.168.5.3 port 22: Connection timed out

I have been stuck for quite a while now and unable to resolve the issue. Any help would be great.


text:
Q: Custom String for combobox I have a combobox that generates a value for other textboxes depending on the combobox selection.  Currently my combobox selection has two values "Reject Title" and "Reason" combined in one cell. I'd like to separate but no sure how to write the string?
Reject Title is named "RejectTitle"
Reason is named "Reason"
I would like the string to show in the user form as:
RejectTitle - Reason with the hyphen in between
What I currently have
 Dim f As Range, v

 v = Me.RejectTitleNm.Value
 'find the selected value in the source range from ColB(RejectTitle)
 Set f = Range("RejectTitle").Find(v, lookat:=xlWhole)

Thank you


text:
Q: Java MergeSort Arraylist import java.util.*;
import java.io.*;

public class MergeSortLines {

public static void main(String[] args) {
  ArrayList<String> list = new ArrayList<String>();
  //String []list ;
  try{
     Scanner tn = new Scanner(new File("phj.txt"));
     while(tn.hasNext()){
        String temp = tn.next();
        String otherTemp = removeSpecial(temp);
        for(int r =0; r<list.size();r++){

        list.add(otherTemp);
     }
     }
  }
  catch(Exception e){
     System.out.println("Sorry there was an error");

  }

  mergeSort(list);

   }

   public static void mergeSort(String[]a){
      if(a.length >= 2){
         String[] left = new String[a.length/2];
         String[]right = new String[a.length-a.length/2];
         System.out.println("Left:  " + Arrays.toString(left));
         System.out.println("Right:  " + Arrays.toString(right));

         for(int i = 0 ; i< left.length;i++){
            left[i] = a[i];
         }

         for (int b = 0; b <right.length;b++){
            right[b] = a[b+a.length/2];
         }

         mergeSort(left);
         mergeSort(right);
         merge(a, left,right);
      }
   }
   public static void merge(String[]result,String[]left,String[]right){
      int i1 = 0;
      int i2 = 0;
      for(int i =0;i<result.length;i++){
         if(i2 >=right.length|| i1< left.length &&
left[i1].compareToIgnoreCase(right[i2]) < 0){
            result[i] = left[i1];
            i1++;
         }
         else{

            result[i] = right[i2];
            i2++;
         }

      }

   }

I've tried to use an ArrayList but I get the following error:
MergeSortLines.java:25: error: incompatible types: ArrayList cannot be converted to String[]
I understand ArrayLists are faster than regular Arrays. I have tried to convert the Array to ArrayList, but I keep getting errors. I would appreciate any help.

A: Use
mergeSort(list.toArray(new String[list.size()]))

instead of
mergeSort(list);

I understand ArrayLists are faster than regular Arrays.

False. ArrayLists using regular Arrays inside, so ArrayList is little bit slow than regular Arrays (in most case, it is doesn't matter)


text:
Q: Dimension of tangent spaces Consider the set
$$ S^{2} = \{ (x,y,z) \in \mathbb{R} \mid x^{2} + y^{2} + z^{2}=1 \}$$
as a manifold with two charts given by the stereographic projections from the points N $= (0,0,1)$ and S $= (0,0,-1)$.
The chart obtained from the projection from N is a homeomorphism
$$ \phi : S^{2} \setminus \{N\} \longrightarrow \mathbb{R^{2}} $$
and, if $p\in S^{2} \setminus \{N\}$, the tangent spaces $T_{p}S^{2}$ and $T_{\phi(p)}\mathbb{R^{2}}$ are both vector spaces of dimension 2.
Consider now the differential of $\phi $ in $p$, the linear application
$$ d \phi_{p}:T_{p}S^{2}\longrightarrow T_{\phi(p)}\mathbb{R^{2}}.$$
In my opinion, this application should be represented by a $2 \times 2$ matrix. Nevertheless, I am working out a solved exercise in which that application is represented by a $3 \times 2$ matrix, whose coefficients are functions of $x,y$ and $z$.
Why is this? Is it because $\phi$ is viewed as a function from a subset of $\mathbb{R^{3}}$ to $\mathbb{R^{2}}$? Why then this apparent inconsistency?

A: The two-dimensional tangent space $T_pS^2$ is naturally a subspace of the three-dimensional space $T_p\mathbb R^3$.  Since stereographic projection extends to (a neighborhood of $p$ in) $\mathbb R^3$, I suspect that you have computed the derivative of the extension.  This restricts to the derivative you are after along the embedding $T_pS^2 \hookrightarrow T_p\mathbb R^3$.
Note that $T_pS^2$ doesn't have a canonical basis.  Without choosing a basis, linear maps $T_pS^2 \to \dots$ cannot be written as matrices.  For any choice of basis they can be.  For example, if $p = (x,y,z) \neq S,N$, you could decide to use latitude and longitude $-z(\partial_x + \partial_y) + r \partial z$ and $y \partial_x - x \partial_y$, where $r = \sqrt{x^2 + y^2}$ is the distance to the pole (and $\partial_x,\partial_y,\partial z$ are the standard basis in $T_p\mathbb R^3 \cong \mathbb R^3$).  Or you could decide that you prefer unit vectors, and rescale the vector pointing along latitude lines $y \partial_x - x \partial_y \leadsto r^{-1}(y \partial_x - x \partial_y)$.


text:
Q: Converting XML doc to String I am using the follwing code to change a xml document:
DocumentBuilderFactory fty1 = DocumentBuilderFactory.newInstance();
   fty1.setNamespaceAware(true);
   DocumentBuilder builder1 = fty1.newDocumentBuilder();
   ByteArrayInputStream bais1 = new ByteArrayInputStream(tr1.getBytes());//tr1=xml string
   Document xmldoc1=builder1.parse(bais1);
   xmldoc1.getElementsByTagName("userID").item(0).setTextContent("123123132");

The xmldoc1 contains the changed form. Now how convert it to a string so that the new doument can be passed to others.

A: Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(xmldoc1);
transformer.transform(source, result);
String xmlString = sw.toString();


text:
Q: TypeORM entity relationship doesn't seems to be working I've got these 2 entities:
@Entity('user_table')
export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column()
    user_id: string;

    @Column()
    deleted: boolean;

    @Column()
    real_name: string;

    @Column()
    timezone: string;

    @OneToOne(type => UserProfile, userProfile => userProfile.id, { cascade: true })
    @JoinColumn({ name: 'profile_id' })
    userProfile: UserProfile;
}

@Entity('user_profile')
export class UserProfile {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    status_text: string;

    @Column()
    status_emoji: string;

    @Column()
    image_512: string;
}

I'm able to insert the User entity data correctly, but the UserProfile data isn't being added. The foreign key seems to be created, but it's null.
Hope somebody can help me, thanks in advance.


text:
Q: js error when trying to dynamically update gmaps Trying to get gmaps to update in place once a new location is typed out. (anyone know a good tutorial for this actually? :P)
Anyways when running the Gmaps4Rails.replaceMarkerst method, I seem to bring up a js error seen when using chrome's inspection tool as seen below. any ideas?
http://stuff.saikonet.org/images/misc/2011-07-22-030217_1024x768_scrot.png

A: Ok gotcha, your problem is not the replace_marker function.
Indeed, using the good old document-ready buddy, the google maps isn't yet created. So yep everything is failing.
That's where Gmaps4Rails.callback makes it's entry.
After the declaration of your map (for an obvious reason: Gmaps4Rails must be defined):
<% content_for :scripts do %>
<script>
Gmaps4Rails.callback = function() {
  Gmaps4Rails.replaceMarkers([{"lng": "-92.5294574", "lat": "45.1969796"}]);
};
</script>
<% end %>


text:
Q: GCP VMWare engine- connection to Vsphere Client is not working After creating a private cloud using Google Cloud VMware Engine, I can't login to the Vsphere Client, the browser shows '''ERR_NAME_NOT_RESOLVED'''.
the following steps I performed
1 enable the ports mentioned in the documentation:
https://cloud.google.com/vmware-engine/docs/quickstart-prerequisites
2 Remove the antivirus.
But the problem still persist