text:
Q: "Undefined property" error in CodeIgniter code I am following a TutsPlus "Build a CMS" tutorial for Codeigniter. It includes this bit of code:
if (!count($this->db->ar_orderby)) {
    $this->db->order_by($this->_order_by);
}

Which results in this message:

Undefined property: CI_DB_mysqli_driver::$ar_orderby.
  Filename: core/MY_Model.php
  Line Number: 29

How can I fix this error?
Here is the code in MY_Model.php:
<?php
class MY_Model extends CI_Model {
    protected $_table_name = '';
    protected $_primary_key = 'id';
    protected $_primary_filter = 'intval';
    protected $_order_by = '';
    public $rules = array();
    protected $_timestamps = FALSE;

    function __construct() {
        parent::__construct();
    }

    public function get($id = NULL, $single = FALSE){
        if ($id != NULL) {
            $filter = $this->_primary_filter;
            $id = $filter($id);
            $this->db->where($this->_primary_key, $id);
            $method = 'row';
        }
        elseif($single == TRUE) {
            $method = 'row';
        }
        else {
            $method = 'result';
        }

        if (!count($this->db->ar_orderby)) {
            $this->db->order_by($this->_order_by);
        }
        return $this->db->get($this->_table_name)->$method();
    }

    public function get_by($where, $single = FALSE){
        $this->db->where($where);
        return $this->get(NULL, $single);
    }

    public function save($data, $id = NULL){
        // Set timestamps
        if ($this->_timestamps == TRUE) {
            $now = date('Y-m-d H:i:s');
            $id || $data['created'] = $now;
            $data['modified'] = $now;
        }

        // Insert
        if ($id === NULL) {
            !isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
            $this->db->set($data);
            $this->db->insert($this->_table_name);
            $id = $this->db->insert_id();
        }
        // Update
        else {
            $filter = $this->_primary_filter;
            $id = $filter($id);
            $this->db->set($data);
            $this->db->where($this->_primary_key, $id);
            $this->db->update($this->_table_name);
        }

        return $id;
    }

    public function delete($id){
        $filter = $this->_primary_filter;
        $id = $filter($id);

        if (!$id) {
            return FALSE;
        }
        $this->db->where($this->_primary_key, $id);
        $this->db->limit(1);
        $this->db->delete($this->_table_name);
    }
}

A: if you are using Code Ignitor 3.x then you can replace these lines:
if (!count($this->db->ar_orderby)) {
    $this->db->order_by($this->_order_by);
}

with:
if(!count($this->db->order_by($this->_order_by))) {
    $this->db->order_by($this->_order_by);
}


text:
Q: How to add custom styles to 3rd party components? What is the recommended way to customize styles for a 3rd party component that I have downloaded via npm?
For example the component ng2-tag-input. I run a webpack build that bundles all the 3rd party js-files into a vendor.js and all the 3rd party css into a vendor.css.
Since this is generated upon build, I don't want to make changes to vendor.css or commit it.
Say that I want to add my own styles to ng2-tag-input, how does one best do that? Should I just override its styles in my own site.css or is there another way?

A: Obviously you cannot modify it in node_modules folder because node_modules should never be included in code repository and your changes .
So, there are two options:

*

*override styles with your own css (more specific rules)

*do not use npm and include ts/css manually

I actually prefer the second option if I need to alter the component because sometimes compatibility is not guarantee between different plugin versions.

A: You can use :host >>> .third-party-class.
Use the /deep/ and >>> selectors only with emulated view encapsulation.
source: https://angular.io/guide/component-styles#deep

A: You can set encapsulation: ViewEncapsulation.none in your outermost component to apply styles globally. Then use that css file as your place for global styles.
app.component.ts:
import { Component, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
    // apply styles globally
    encapsulation: ViewEncapsulation.None
})
export class AppComponent implements OnInit {
    constructor() {
    }

    ngOnInit() {
    }
}

As @anonymvs mentioned you need to use higher specificity. One easy way to help with this, if you are using sass or similar, is to put all of your styles in a very specific block, eg:
app.component.scss:
$danger: #dc3545;
$info: purple;

body:not(.added-for-higher-specificity) {

.simple-notification {
    &.error {
        background: $danger;
    }

    &.info {
        background: $info;
    }
}

}

redpajama_set_name: RedPajamaStackExchange


text: Q: Closing tag won't respond I'm building a news web app in react and closing tag won't respond as when splitting components, what can be done?... I have tried restarting vs code and still encounter the same problem.


text:
Q: Getting ASP.NET session value in javascript? im trying call a session variable stored in c#. My code is
var sesion_values= '<%= Session["userEmail"].ToString() %>';
console.log("sesion is: ", sesion_values);

this return:
sesion is:  <%= Session["userEmail"].ToString() %

A: From what I see the asp.net code is not run, so you probably place it inside the javascript file - where asp.net not compile it.
One trick is to add it on .aspx page (or on master page) just before you load the javascript file...
for example, inside the asp.net code do this.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script>
        var sesion_values = '<%=Session["userEmail"].ToString()%>';
    </script>
    <script src="yourscript.js"></script>
</head>

then you can use the sesion_values inside the javascript file.


text:
Q: How to append to the right ID's column in CSV with pandas? I have got a test file and 100 model which I would like to evaluate on the test.
In the test file there are 2 column, first is IDs and the second is Probability.
I would like that each model would append it's evaluation to a new column next to the relevant ID.
My code right now build it under each other, like this:
1 0.1
2 0.12
3 0.32
1 0.21
2 0.22
3 0.17

And I would need form like this:
1 0.1 0.21
2 0.12 0.22
3 0.32 0.17

to a csv.
My code looks like this:
for chunk in pd.read_csv('test_numeric_out.csv', chunksize=10000):
chunk = chunk.drop(chunk.columns[len(chunk.columns)-1], axis=1)
for model in models:
    X_test = chunk.drop(['Id'],axis=1)
    inputnames = X_test.columns.values
    X_test['p_0']=0
    X_test['p_1']=0
    X_test[ ['p_0','p_1'] ]  = model.predict_proba(X_test[inputnames])
    submission = pd.DataFrame({
        "Id":chunk['Id'],
        "Response":X_test['p_1']
        })
    if (head==0):
        submission.to_csv(proba_out_csv,
        index=False,
        header=True,
        mode='a',
        chunksize=100000)
    else:
        submission.to_csv(proba_out_csv,
        index=False,
        header=False,
        mode='a',
        chunksize=100000)
    head = 1

A: I believe it can be done a bit easier.
inputnames = chunk.columns.drop('Id').values
# drop works here too, so no need to create additional dataframe
# to get inputnames
for i, model in enumerate(models):
    chunk['p_1_{}'.format(i)]  = model.predict_proba(chunk[inputnames])[:, 1]
    # we are interested only in the second column
    # do not need to create different dataframe to store results
    # just create distinct column for each model
chunk.to_csv(proba_out_csv)


text:
Q: SSL connection with certificate I would like to replicate the following Python code into an equivalent in Java:
import socket, ssl, pprint

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s,
                           ca_certs="server.crt",
                           cert_reqs=ssl.CERT_REQUIRED)

ssl_sock.connect(('localhost', 10023))
ssl_sock.write("boo!")

if False:
    data = ssl_sock.read()
    ssl_sock.close()

I came up with the following code (which is not working) but I still have two questions:
abstract class Connection extends AsyncTask<String, Void, String> {

    boolean Connect(){
        try
        {
           SSLSocketFactory factory=(SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket mySSLSocket=(SSLSocket) factory.createSocket("localhost", 10023);

            DataOutputStream myOutPutStream = new DataOutputStream(mySSLSocket.getOutputStream());
            myOutPutStream.writeBytes("Hello World!");

            myOutPutStream.close();
            mySSLSocket.close();

            return true;

        }
        catch(Exception e)
        {
            return false;
        }

    }

}

By executing the code I get the following Java Error:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

*

*Where do I save the certificate in my Android Application Project (Android Studio)?

*What is the equivalent for the code below in Java?
ssl_sock = ssl.wrap_socket(s,
                           ca_certs="server.crt",
                           cert_reqs=ssl.CERT_REQUIRED)

A: Try -Djavax.net.ssl.trustStore=/path/to/keystore, where '/path/to/keystore' is the absolute file path of the alternative keystore.
This needs to be a VM option for running your code / project.


text:
Q: What is the Fourier transform of a sequence of random variables? I understand the Fourier transform of a signal f(t). It is an integral of f(t) times the Fourier basis. However, if f is a random function of t and $\omega$, what would be the fourier transform of f(t, $\omega$) represent?  ($\omega$ is an element from the sample space $\Omega$)
Blindly applying the integral generates a  random function which I could not quite wrap my mind around.


text:
Q: "can't assign to keyword" error with python "except" command Do anyone know why do the follow python (3.7) codes:
1 # Python backward-compatibility...
2 try:
3    True
4 except:
5    True = 1
6 try:
7    False
8 except:
9    False = 0
10 #
11 # Cheap hack for testing purposes
12 #

give the "can't assign to keyword (line 5)" error?
I will appreciate any help.
Best

A: You can't assign values to the inbuilt python keywords, 'True' and 'False'. Change the name of the variable in line 5, eg:
my_var = 1

You will also need to change line 9 for the same reasons.


text:
Q: problems with .htaccess redirection and RewriteRule (with or without RewriteCond) I have to set up the url http://subdomain.example.com/test and make it able to call the real file /my-test-script.php.
I can't understand why the following code works:
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^\/?test\/?$
RewriteRule ^\/?(.*)$ /my-test-script.php [NC,L,QSA]

while this one does not work:
RewriteEngine On
RewriteBase /

RewriteRule ^\/?test\/?$ /my-test-script.php [NC,L,QSA]

Is it mandatory the RewriteCond? If not, what do I miss?
Thanks!
EDIT:
.htaccess and my-test-script.php are both in the root /.
EDIT 2:
Funny update: I see it works with
RewriteRule test /my-test-script.php [NC,L,QSA]

but not with
RewriteRule ^test$ /my-test-script.php [NC,L,QSA]

EDIT 3:
I created a script that shows the $_GET parameters:
RewriteCond %{REQUEST_URI} !^\/?show\-parameters\.php$
RewriteRule ^(.*)$ /show\-parameters.php?path=$1 [NC,L,QSA]

and when I call http://subdomain.example.com/test I see:
Array ( [path] => /var/www/html/client/project_name/domain/subdomain/test )

EDIT 4:
Here my VirtualHost:
<VirtualHost *>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    RewriteEngine On

    ### HTTP: from www to non-www ###
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1$1 [R=301,L]

    <Directory /var/www/html>
        Options -Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Order allow,deny
        allow from all

        RewriteBase /

    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName subdomain.example.com
    ServerAlias www.subdomain.example.com
    DocumentRoot /var/www/html/client/project_name/domain/subdomain

    RewriteEngine On

    ### HTTP: from www to non-www ###
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1$1 [R=301,L]

    <Directory /var/www/html/client/project_name/domain/subdomain>
            Options -Indexes +FollowSymLinks +Multiviews
            AllowOverride All
            Order allow,deny
            allow from all

            RewriteBase /
    </Directory>

</VirtualHost>

[SOLVED] EDIT 5:
I simply removed the RewriteBase / line from the .htaccess and the following rule now works:
RewriteEngine On
RewriteRule ^\/?test\/?$ /my-test-script.php [NC,L,QSA]

A: Is your my-test-script.php located at the same level of your .htaccess? If so, just do this:
RewriteEngine On
RewriteBase /

RewriteRule ^test/?$ my-test-script.php [NC,L,QSA]

A: RewriteEngine On
RewriteBase /

RewriteRule ^/test/?$ /my-test-script.php [NC,L,QSA]

Try that instead. That works for me on a test environment I have.


text:
Q: Expected variance of biased estimators Suppose that $\mu$ is an unknown $k$-vector, which one seeks to guess. You observe $n$ i.i.d. normal variates $x_i \sim \mathcal{N}\left(\mu,\Sigma\right)$, say stacked in the matrix $X$, then produce estimate $\hat{\mu}\left(X\right)$. Cramer-Rao theorem gives a lower bound on $Var\left(\hat{\mu}\left(X\right)\right)$ when $\hat{\mu}$ is unbiased.
However, the variance (and MSE) for a biased $\hat{\mu}$ might be lower than an unbiased one. You might be tempted to choose a biased estimator. My question is whether there is a "free lunch" type argument against a biased estimator. Suppose that one will draw $\mu$ uniformly from all $k$-vectors with unit norm, then generate the $X$, and compute the estimate. Is there a lower bound for
$$
E_{\mu}\left[E_{X} \left[\left(\hat{\mu}\left(X\right) - \mu\right)^2\right]
\right]
$$
that applies to all estimators?

A: If one picks a probability distribution $\pi$ on $\mu$ and minimises the integrated risk, this is equivalent to running a Bayesian decision analysis with this prior distribution. In this case the optimal solution is the posterior mean
$$\hat\mu(x)=\mathbb E^\pi[\mu|x]$$
and the estimator is always biased. There is thus gains to be found by reaching outside unbiasedness.


text:
Q: Redirect response from Event Subscriber in Symfony PHP I'm trying to return a permanent (301) redirect response from a event subscriber hooked into the kernel events in Synfony PHP.
My subscriber is as follow:
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

use Symfony\Component\HttpFoundation\RedirectResponse;

class KernelSubscriber implements EventSubscriberInterface {

    public function __construct() {

        // some stuff here but not relevant for this example
    }

    public static function getSubscribedEvents(): array {

        return [ KernelEvents::REQUEST => 'onRequest' ];
    }

    public function onRequest(GetResponseEvent $event): void {

        // if conditions met
        //     301 redirect to some internal or external URL

        if(!$event->isMasterRequest()) return;
    }
}

If this were a controller I would return $this->redirectToRoute('route') or something like that but returning from the onRequest method is in a much different context.
How can I return a response (a redirect, in particular) from this event subscriber?

A: In my case the event had no setResponse method, but I could use the send method from the Response class.
$response = new RedirectResponse('https://stackoverflow.com/', 302);
$response->send();

A: Should be something like:
$event->setResponse(new RedirectResponse($route));

A: For me what worked was to inject the urlGenerator and then check for the user token and make a new RedirectResponse to my logout ourl.
public function onKernelController(ControllerEvent $event)
{
    if (!$event->isMainRequest()) {
        return;
    }

    $session = $event->getRequest()->getSession();
    $ssoSessionTime = $session->get('sso.expiration_time');
    if (($ssoSessionTime - time()) < 0) {
        $logoutUrl = $this->urlGenerator->generate('logout');
        $response = new RedirectResponse($logoutUrl);
        return $response->send();
    }
}

Here I check that the timestamp given by my authenticator is not smaller than current time. If it is I send a new RedirectResponse

A: Use the below method to set the redirect response / redirect url.
$event->setController(function() use ($redirectUrl) {
    return new RedirectResponse($redirectUrl);
});


text:
Q: Firebase child is not being remove, parent is I'm using react-native and am attempting to remove a child ref, my function is...
cancelSleep = ()=> {
  const rootRef = firebase.database().ref("SleepSettings/")
  rootRef.child(`${this.state.user}/`).remove().then( ()=>
  this.setState({sleepConfirmed: false}))
}

I've tried many different combinations either way the whole ref "SleepSettings" and all its children are removed as opposed to just the child ref, see pictures.

A: In Realtime Database, when a node no longer has any children, it is removed from display in the console.  What you are seeing is that the only child of SleepSettings is being removed, which means SleepSettings itself is removed from display.
In actuality, a node doesn't really exist in Realtime Database.  It's just part of a path to get to a value, such as this path:
SleepSettings/bill@bill/sleepConfirmed

Which has this value:
true

Any child that doesn't have a value attached to it is just an organizer for other children, and when all its child values are gone, the organizer is effectively gone, as there are no paths to values left to organize.
In other words, they don't work like filesystem folders at all, which exist and can be empty.


text:
Q: Error: Camlp4: Uncaught exception: Not_found I am working on an Ocsigen example (http://ocsigen.org/tuto/manual/macaque).
I get an error when trying to compile the program, as follows.
File "testDB.ml", line 15, characters 14-81 (end at line 18, character 4):
While finding quotation "table" in a position of "expr":
Available quotation expanders are:
svglist (in a position of expr)
svg (in a position of expr)
html5list (in a position of expr)
html5 (in a position of expr)
xhtmllist (in a position of expr)
xhtml (in a position of expr)

Camlp4: Uncaught exception: Not_found

My code is:
 module Lwt_thread = struct
 include Lwt
 include Lwt_chan
 end
 module Lwt_PGOCaml = PGOCaml_generic.Make(Lwt_thread)
 module Lwt_Query = Query.Make_with_Db(Lwt_thread)(Lwt_PGOCaml)

 let get_db : unit -> unit Lwt_PGOCaml.t Lwt.t =
 let db_handler = ref None in
 fun () ->
   match !db_handler with
      | Some h -> Lwt.return h
      | None -> Lwt_PGOCaml.connect ~database:"testbase" ()

let table = <:table< users (
  login text NOT NULL,
  password text NOT NULL
) >>
..........

I used eliom-destillery to generate the basic files.
I used "make" to compile the program.
I've tried many different things and done a google search but I can't figure out the problem. Any hints are greatly appreciated.

A: Generally speaking, the error message indicates that CamlP4 does not know the quotation you used, here table,  which is used in your code as <:table< ... >>. The quotations can be added by CamlP4 extensions pa_xxx.cmo (or pa_xxx.cma) modules. Unless you made a typo of the quotation name, you failed to load an extension which provides it to CamlP4.
According to http://ocsigen.org/tuto/manual/macaque , Macaque (or its underlying libraries? I am not sure since I have never used it) provides the quotation table.  So you have to instruct CamlP4 to load the corresponding extension. I believe the vanilla eliom-destillery is minimum for the basic eliom programming and does not cover for the extensions for Macaque.
Actually the document http://ocsigen.org/tuto/manual/macaque points out it:

We need to reference macaque in the Makefile :
SERVER_PACKAGE := macaque.syntax

This should be the CamlP4 syntax extension name required for table.


text:
Q: Has any mathematician constructed a physical, (global), ball model of $\Bbb R^3?$
Q: Has any mathematician constructed a physical, (global), ball model of $\Bbb R^3?$

For example, to map $\Bbb R^3$ inside $S^2$ you can do, $(x,y,z)\mapsto(x,y,z)/\sqrt{1+r^2}$ so, $\left(\dfrac x{\sqrt{1+x^2+y^2+z^2}},\dfrac y{\sqrt{1+x^2+y^2+z^2}},\dfrac z{\sqrt{1+x^2+y^2+z^2}}\right).$

A: I've made a small model of $\left(\dfrac x{\sqrt{1+x^2+y^2+z^2}},\dfrac y{\sqrt{1+x^2+y^2+z^2}},\dfrac z{\sqrt{1+x^2+y^2+z^2}}\right)$ for
 $x,y,z \in\{-2,1,0,1,2\}$ (ie. $5^3 = 125$ points in total) and the grid lines passing trough them with red length-wise parallel lines, blue width-wise parallel lines and green height-wise parallel lines. You can download the model
here
and view it with View3dscene.

Geometrically, I don't know if there's much to say about the model. The sphere which is the boundary of the ball represents infinity (the metric distance from a point in the interior of the ball to a hypothetical point on the boundary of the ball is infinite), so the closer you get to the boundary, the "denser" the points will be.
Also, parallel co-planar lines will intersect at infinity, at two radially opposite points of the sphere.

As expected, it looks "most" Euclidean when looking from the center.


text:
Q: ReSharper (or something like it) for Visual C++? I've seen ReSharper recommended a lot  Unfortunately, it doesn't support C++ in Visual Studio.  Is there anything out there you can recommend?  I already use Visual Assist, and it does its job very well, but it's quite limited in comparison with ReSharper.
Any suggestions?

A: Refactor Pro is available for Visual C++, this will give you some functionality. Also check out CodeRush, I think it also supports C++.

A: I tried both Refactor Pro and Visual Assist/X. Neither of them thrilled me in the same way that ReSharper does. I guess that mostly, this is because C++ is such a hard language to write automatic refactorings for.

A: IMHO - Visual Assist X is best but expensive code completion/refactoring tool for C++.
VAX has not so much features as ReSharper for C#, but it makes your C++ programming easier and faster... Just looked on CodeRush - it su%% as most of DevExpress libs & tools.

A: The solution is to code in Eclipse or NetBeans, but such IDEs are not Visual Studio.


text:
Q: How can I get rid of the error "Unsupported format of the sourcemap" while loading jquery-migrate.min.js? I am getting the following error message in the Visual Studio 2013 debug window:

'iexplore.exe' (Script): Loaded http://localhost:4453/Scripts/lib/jquery-migrate.min.js
Unsupported format of the sourcemap

Module load messages are turned on (debug window context menu). I know that there should be a jquery-migrate.min.js.map file, but that is unfortunately not distributed by the jQuery team.
Now I tried to simply use an empty file, and also I tried to use the jquery.min.map file (simply renaming a copy to jquery-migrate.min.js.map), but both don't work.
I have also looked on the jQuery site, they provide a map file for Jquery but not for jquery-migrate: Download the map file for jQuery 2.1.4
Since the file is not available for download (or did I look at the wrong location), how can I create such a file from scratch? It seems to look like a JSON formatted file.
NOTE: There is some information available @ StackOverflow about site map files (see bootstrap-3-1-1-what-is-the-map-extension-file-used-for). And to give you an idea about the syntax of sourcemaps, you can read this: Source Map Revision 3 Proposal
Unfortunately, trying to mimick a sourcemap by using the information from the proposal did not help, the error message is still shown.
What I tried was creating a file jquery-migrate.min.js.map in the same path as the minified file jquery-migrate.min.js:

{"version":3,
"file":"jquery-migrate.min.js",
"sources":["jquery-migrate.js"],
"names":["$"],"mappings":";EAAIzkC"}

(No idea how the mapping code is being calculated)
Unfortunately, this did not help.
Then I thought that it would suppress the error message by changing the file jquery-migrate.min.js in the following way:
I.e., I commented out the line

//@ sourceMappingURL=dist/jquery-migrate.min.map

so the file now looks like this (the code below is truncated for easier reading, just note the last line /*---disabled: //@ sourceMappingURL=dist/jquery-migrate.min.map ---*/):

/*! jQuery Migrate v1.1.1 | (c) 2005, 2013 jQuery Foundation, Inc. and other contributors | jquery.org/license */
jQuery.migrateMute===void 0&&(jQuery.migrateMute=!0),function(e,t,n){function r(n){o[n]||(o[n]=!0,e.migrateWarning....................
/---disabled: //@ sourceMappingURL=dist/jquery-migrate.min.map ---/

But the error message still occurred. Astro gave me the right hint (see his answer). Thank you!

NOTE (to the reviewers who changed the message above): This is an error message thrown by Visual Studio and the link is a local link which points to my IISExpress. Don't change the error message.

A: The jquery-migrate.min.js.map is there so you can debug the jquery minified library. It needs to be there for development purpose but for production you don't need that whole line. I dont know why they have included that line in the js.
You can just safely delete that whole line.
I dont know about VS2013 but for my php projects i run a gulp task on the file jquery.js to remove this line before concatenating with other js libraries,


text:
Q: Bootstrap popover "arrow" detached from popover on small screens I am using the Bootstrap 3.3.5 popover feature to display a popover when user clicks on the text inside a td element. It works fine except for one thing.
When the window width gets smaller and I reach my first responsive breakpoint, the arrow is detached from the popover (see image). You can see the arrow on the left. When the device width is wider, there is no problem. Any ideas how this could be fixed?

HTML:
    ...
Today

...

      Popover
      Content

JAVASCRIPT:
//Enables popover
$("#date-today").popover({
    html : true,
    content: function() {
      return $("#date-today-content").html();
    },
    title: function() {
      return 'Today';
    },
    placement: function() {
        return 'bottom';
    },
    container: 'body'
});

Thanks for any help!


text:
Q: I have tried to set my ViewController3 as rootVC for my logged in users and vc for non logged in, but instead it turns black When I tried it out on my Iphone, and instead of showing VC3 or VC, my rootVC was completely black and I don't know how to get VC3 and VC instead depending on if the user is logged in.. Have tried self.view.backgroundColor = UIColor.red but my simulator doesn't respond to the code
Thank you in advance and sorry if it's a stupid question but I am new to this.
 AppDelegate

    window = UIWindow(frame: UIScreen.main.bounds)
    let sb = UIStoryboard(name: "ViewController3", bundle: nil)
    var initialViewController = sb.instantiateViewController(withIdentifier: "Onboarding")
    let userDefaults = UserDefaults.standard
    if userDefaults.bool(forKey: "LoginComplete") {
        initialViewController = sb.instantiateViewController(withIdentifier: "ViewController3")
    }
    window?.rootViewController = initialViewController
    window?.makeKeyAndVisible()

ViewController3

override func viewDidLoad() {
    super.viewDidLoad()

       infoView.isHidden = true

        let userDefaults = UserDefaults.standard
        userDefaults.set(true, forKey: "LoginComplete")
        userDefaults.synchronize()

}


text:
Q: how to remove the Brackets in a json file at the end and beginning in Apache Nifi i have a json file like this one below and try to remove the array's brackets at the beginning and the end
[
  {
    "a": "1",
    "b": "2"
  }
]

and i only want the map:
{
  "a": "1",
  "b": "2"
}

anyone knows which processor to use and how to configure?
Thanks, Lukas

A: You can use SplitJson Processor.
I've used the following settings for the Processor.

Or you can also use EvaluateJsonPath. Here is my configuration for EvaluateJsonPath.

A: An alternative way might be adding a JoltTransformJSON processor which will contain this spec
[
  {
    "operation": "shift",
    "spec": {
      "*": ""
    }
  }
]


text:
Q: Why I don't see excel range in UIpath studio Why I don't see excel range in UIpath studio . Should I use excel file in sequence and search for this activity
Searched in activities

A: The "Excel Range" activity may not be visible in UiPath Studio if the Excel activities package is not installed. To check if the package is installed, go to the Manage Packages section in the Studio's activity panel and search for "UiPath.Excel.Activities". If it's not installed, you can install it from the official UiPath repository.
Once the package is installed, you should be able to find the "Excel Range" activity in the Studio's activity panel under the "Excel" category. To use it, you need to have an Excel file open, and then you can select the desired range of cells in your workflow.
If you still cannot find the activity, make sure that the version of UiPath Studio you are using is up to date, and if the issue persists, you may want to consider reinstalling the package or reaching out to UiPath support for further assistance.


text:
Q: How do I debug functions registered by `atexit` using `pdb` in Python? Main question
My understanding is that atexit will run registered functions in reverse order as soon as the program is killed by a signal handled by Python. One example of such a signal is when the interpreter is quit. So if I have a file called register-arguments.py as follows:
def first_registered():
    print('first registered')

def second_registered():
    print('second registered')

import atexit

atexit.register(first_registered)
atexit.register(second_registered)

Running python register-arguments.py will trigger the following steps:

*

*Interpreter is started

*Functions are registered, which generates no output in the terminal

*The interpreter is terminated, and the registered functions are called
in reverse order.

The output is as follows:
second registered
first registered

Which makes sense. However, if I try to debug one of these functions with Python's native debugger pdb, here's what I get:
$ python -m pdb .\register-arguments.py
> ...\atexit-notes\register-arguments.py(1)<module>()
-> def first_registered():
(Pdb) b 2
Breakpoint 1 at c:\users\amine.aboufirass\desktop\temp\atexit-notes\register-arguments.py:2
(Pdb) c

As you can see the program starts and stops at line 1 of the source file. I then intentionally place a breakpoint at line 2, then use the c command to continue execution.
I expected the debugger to stop after the registered function is called (upon pdb exiting the terminal). However, that doesn't happen, and I get the following message:

The program finished and will be restarted.

How do I debug functions registered by atexit using pdb in Python?
On pdb.set_trace
It seems that explicitly adding a trace inside the source code does work:
import pdb

def first_registered(arg):
    pdb.set_trace()
    print(f'first registered, arg={arg}')

def second_registered():
    print('second registered')

import atexit

atexit.register(first_registered, arg="test")
atexit.register(second_registered)

Debugging with python register-arguments.py will land you in the line where the breakpoint is explicitly added, and the value of the variable arg at that breakpoint is indeed 'test'.
I have a strong preference for not editing the source code, so this unfortunately won't work for me. I'm curious to see whether there's a way to do it without editing the source code.


text:
Q: AngularJs ng-repeat does not dispay values even when model has values I am using AngularJs to display list of names provided by a nodejs route 'api/getItems'
which returns  following
router.get('/getItems',function(req,res,next){

var model = [{"_id":"53f4cde40864fca70c2434cf","name":"John Smith"},
                 {"_id":"23f4bde40864fba70c2434cf","name":"Smith John"},
                 {"_id":"592f4cde40864fca70c2434cf","name":"Albert Test"}];
      res.json(model);

});

Please find my html code and angular code ( app.js) in this fiddle here
This code appears to be pretty straightforward  and simple . I am new to angularjs and hence i cant make out what is the issue. The list iterates for the number of objects but does not display name.I have tried debug using Angular Batarang and found the following.

Can someone help me with what i am doing wrong here?  Thank you very much
adding my angular code below.
var app = angular.module('sampleApp', []);

app.factory('TestService', function ($http, $q) {

    return ({
        getItems : getItems
    });

    function getItems(){

        var request = $http({
                             method: "Get",
                             url: "api/getitems"
                            });

        return( request.then( handleSuccess, handleError ) );
    }

    function handleError( response ) {

        if (! angular.isObject( response.data ) ||! response.data.message) {

            return( $q.reject( "An unknown error occurred." ) );
        }
        return( $q.reject( response.data.message ) );
    }

    function handleSuccess( response ) {
        return( response.data );
    }

});

app.controller('TestController', ['$scope', 'TestService', function ($scope, TestService) {

    $scope.model= [];
    $scope.model.TestList= [];

    loadRemoteData();

    function loadRemoteData(){
        TestService.getItems().then(function(data){
                applyRemoteData(data);
        });
    }

    function applyRemoteData( WorkItems ) {
        $scope.model.TestList = WorkItems;
    }

}]);

html snippet :

Name :
 {{item.name}}

A: I checked with your jsfiddle , there will be a problem with your $http.get(url);
as i see your are not getting correct promise object check with get call.
So i tried with mock data By forking and did few changes in jsfiddle and removed some script tags in html.
here is the updated jsfiddle which works fine which your looking for


text:
Q: Filling a certain amount of whitespace on website In my web app I use the following CSS to provide notices/error messages:
#notice {
  border: 1px solid green;
  padding: 1em;
  margin: 1em;
  margin-bottom: 2em;
  background-color: lightgreen;
  font: bold sans-serif;
  color: darkgreen
}

But when a notice isn't required, I want to have white space equal to the amount of space that this notice would've taken up. I want to do this so that my web pages look consistent, and items on the page aren't shifted up/down according to whether there is a notice or not.

A: I have done this by setting a fixed height.
I've also heard the argument that its okay to have the page bump down, (that's how stackoverflow works) because it draws attention to the message and that is a good thing.

A: The solution can depend on how you want to / have to implement this notice block. If you update the page with Ajax (without graceful degradation, a JS off fallback to normal state) I strongly recommend to do this with modal windows like Facebook - its nice and handy. If you did not have the chance to use modal windows it could be something like:
#notice{ height: 100px; margin: 1em 1em 2em } /* #notice can be a wrapper with basic dimensions */
.error{ border: 1px solid red; } /* reuse the same block */
.info{ border: 1px solid green; } /* reuse the same block */

And the HTML respectively:

Error state:

 Your error message

Info state:

 Your info message

Of course you can run into problems with the #notice div height when the message is too long but that is an other problem :)

A: You can set a fixed height and width for the div.
#notice {
   ....
   height: 200px;
   width: 100%;
}

Alternatively, you may use min-height and min-width.

A: I'm assuming the div with #notice won't be there if you don't need it.  Why not use the adjacent selector like this.  It won't work in some browsers like IE6.  Give the element following it the class of "following" or something similiar.  There will still be a bit of a difference because you have the 2px from the border in there.
#notice {
  border: 1px solid green;
  padding: 1em;
  margin: 1em;
  margin-bottom: 2em;
  background-color: lightgreen;
  font: bold sans-serif;
  color: darkgreen
}
.following {
    margin-top:4em
}
#notice + .following {
    margin-top:2em;
}


text:
Q: how to select same column twice in mongodb Generally we can select a column in mongodb like follows,
db.TestData.find({"_id" : ObjectId("53eba30740adad086ce3599e")},{_id:1})

In sql we are selecting a same column twice like follows,
Select column1,column1 from table1

I need a mongodb query to select like above.
How can I do that?
thanks in advance. . . .

A: You could either use a javascript function to manipulate it, or do a basic aggregate query using the project operator:
db.accounts.aggregate({ $project: { _id: 1, _id2: '$_id' }});

// Or using a match to filter the results first
db.accounts.aggregate(
    { $match: { _id: ObjectId("53eba30740adad086ce3599e") } },
    { $project: { _id: 1, _id2: '$_id' } }
);


text:
Q: Mounting docker volume using rexray driver in GCE fails I have been trying to create docker volume using RexRay driver in GCE VM instance following the steps mentioned at http://collabnix.com/building-persistent-storage-solution-with-dellemc-rexray-0-8-docker-17-03-managed-plugin-system-for-cloud-platforms/
Here the rexray is installed and enabled as docker plugin.
I am stuck at volume creation step. The command for the same is as below:
sudo docker volume create --driver rexray/gcepd --name storage1 --opt=size=32

Below is the error I am receiving executing the command:
Error response from daemon: create storage1: VolumeDriver.Create: docker-legacy: Create: storage1: failed: error querying for existing volume

Could not find anything on the web for the above error string.
I got the same error while I was trying the same steps in VM instance with Container Optimized OS.
Below are further details of my setup:

*

*GCE instance with Debian OS

*Instance Service account with Project Editor permission

*Docker version 18.03.1-ce, build 9ee9f40

A: It worked for me, I was able to create a volume on my project.
Your instance should have the storage scopes as read and write, to do, you need to stop the instance and edit the details on Cloud API access scopes or you can select Allow full access to all Cloud APIs and save.
After restart your instance and SSH run the below command line:
$ sudo docker volume create --driver rexray/gcepd --opt size=50 --name test-volume

Container Optimized OS have some limitation and the kernel is not enabled.


text:
Q: Describe Kafka Consumer Groups Response I have a Kafka 0.10.2.0 cluster and I'm using the Apache Kafka command line tools to debug why a particular Consumer Group is not receiving messages.
Using the $KAFKA_HOME/bin/kafka-consumer-groups.sh --bootstrap-server <kafka_brokers> --list I get a response that includes the Consumer Group ID I'm trying to debug.
Next, I use $KAFKA_HOME/bin/kafka-consumer-groups.sh --bootstrap-server <kafka_brokers> --describe –group <consumer_group_id> to retrieve details about topics, consumers, and offsets in relation to my misbehaving Consumer Group. I see a response I don't understand:
TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG        CONSUMER-ID                                       HOST                                      CLIENT-ID
-                              -          -               -               -          external-ems-link-status-f3ecd2cb-ab84-4043-b4f5-aa0c7d7d6bf0/10.100.0.18                 external-ems-link-status
-                              -          -               -               -          external-controller-topo-notification-b87e5e28-3cd2-48cf-ac6b-ed9a04b3881c/10.100.0.18    external-controller-topo-notification
-                              -          -               -               -          external-interface-status-alrm-c0190022-d359-4cd6-a872-8c50852f4c53/10.100.0.18            external-interface-status-alrm
-                              -          -               -               -          external-ctlr-link-status-5b34eefa-6a06-45cd-ad13-b78fa6c499a7/10.100.0.18                 external-ctlr-link-status
-                              -          -               -               -          external-flow-ctrl-status-2712c302-d7de-4d50-8dc8-473c05205b4b/10.100.0.18                 external-flow-ctrl-status
-                              -          -               -               -          external-ctrl-status-e9a9d77a-6dc5-445d-9e38-0d9c5c3a4af4/10.100.0.18                       external-ctrl-status
-                              -          -               -               -          external-bw-util-notification-4f746863-0c10-4d4c-8785-93401e904777/10.100.0.18             external-bw-util-notification
link-status                    0          2602            2602            0          -                                                 -                              -

What does it mean when I see no topic, or partition information for a particular consumer/host, client ID?
I can confirm that messages are being produced on those topics when I create a console consumer using the --zookeeper flag.
Any help would be greatly appreciated.

A: This tells you that there are a number of consumers in the group with no partitions assigned to them. If your link-status topic has only one partition, and the other consumers are subscribed to the same topic, this is the expected result (simply because each partition in the group can be consumed by one and only one consumer).


text:
Q: Use a temp table's result in a view I am using a temp table in a stored procedure.
I need to use that temp table's result in my view.
How can I do that?

A:
I need to use that temp table's result in my view.

Why?
Creating views on temporary tables is not allowed.
create table #foo(id int)
go
create view vfoo
as
select * from #foo

fails with
Msg 4508, Level 16, State 1, Procedure vfoo, Line 4 [Batch Start Line 9]
Views or functions are not allowed on temporary tables. Table names that begin with '#' denote temporary tables.


text:
Q: When are $ r_1: ax + by + c=0 $ and $ r_2: a'x + b'y + c'=0$ distinct? When are $ r_1: ax + by + c=0 $ and $ r_2: a'x + b'y + c'=0$ distinct? I think, if $$rank\left(\begin{array}{cc}
a & b \\
a' & b'
\end{array} \right)\neq 1$$ then $r_1$ and $r_2$ are distinct. Is correct?
Thanks in advance!

A: case1: rnk=1 and c/c′ in not an integer,
case2: rnk≠1 and c=c′.
In the first case they are parallel and distint and in the second case they are not parallel and distinct. Consider any two lines they should be parallel ,coincide or not parallel. Thus these two are the only possibibilities for r1 and r2 to be distinct.


text:
Q: Como selecionar o atributo logUser apenas no objeto principal do JSON usando Regex Preciso selecionar o atributo logUser apenas no Objeto principal do JSON caso o mesmo venha com valor ou null.
Ex: logUser: 100 | logUser: null
{
    "id": 1,
    "numeracao": "001",
    "logUser": 100,
    "permissionario": {
        "id": 3113715,
        "nome": "ARTHUR MATHEUS SÉRGIO DA SILVA",
        "dataDeNascimento": "2000-12-10",
        "endLogradouro": "RUA TERESINA",
        "endNumero": "89465468",
        "endBairro": "ROSA DOS VENTOS",
        "endCidade": "PARNAMIRIM",
        "endUf": "RN",
        "endCep": "59142125",
        "endComplemento": null,
        "telefoneFixo": null,
        "telefoneMovel": "(94) 949849849",
        "email": null,
        "logDate": "2019-01-16",
        "logUser": null,
        "sexo": "MASCULINO",
        "foto": null,
        "cpf": "10322314593",
        "estadoCivil": "CASADO",
        "cnhNumero": null,
        "cnhCategoria": null,
        "cnhValidade": null,
        "rgNumero": "64684654",
        "rgOrgaoExpeditor": "SSP",
        "rgDataEmissao": null,
        "rgUF": "RN",
        "status": true
    },
    "veiculo": {
        "id": 3,
        "placa": "JUQ9196",
        "marca": "RENAULT",
        "modelo": "SC",
        "renavam": "54840252144",
        "anoDeFabricacao": "2006",
        "corPredominante": "BRANCO",
        "logCidadao": null,
        "status": true,
        "logUser": null,
        "logDate": "2019-01-16T11:05:10.425",
        "version": 1
    },
    "logDate": "2019-01-16T11:05:13.264",
    "status": true,
    "version": 0,
    "motorista": {
        "id": 3113717,
        "nome": "DAVI LEVI GALVÃO",
        "dataDeNascimento": "1996-10-20",
        "endLogradouro": "RUA FRANCISCO FERREIRA DA SILVA",
        "endNumero": "911",
        "endBairro": "VALE DO SOL",
        "endCidade": "PARNAMIRIM",
        "endUf": "RN",
        "endCep": "59143025",
        "endComplemento": null,
        "telefoneFixo": "8429884472",
        "telefoneMovel": "84995302167",
        "email": "ddavilevigalvao@mtic.net.br",
        "logDate": "2019-01-16",
        "logUser": null,
        "sexo": "MASCULINO",
        "foto": null,
        "cpf": "98842966428",
        "estadoCivil": "CASADO",
        "cnhNumero": null,
        "cnhCategoria": null,
        "cnhValidade": null,
        "rgNumero": "184962122",
        "rgOrgaoExpeditor": "SSP",
        "rgDataEmissao": null,
        "rgUF": "RN",
        "status": true
    }
}

A: Não use regex para isso
Você pode até achar que regex é uma boa ideia para este caso, mas acredite, não é.
Provavelmente você pensou que seria algo simples como "logUser"\s*\:([^\,]+), (a palavra logUser entre aspas, seguido ou não de espaços, seguido de :, seguido de vários caracteres que não são vírgula, seguido de vírgula). E aparentemente "funciona".
O problema é que esta regex não valida se toda a string de fato é um JSON, o que já é uma grande desvantagem. Você não quer apenas verificar se existe uma linha cujos caracteres estejam em um determinado formato. Você quer verificar se os dados são de fato um JSON válido (que é um tipo específico de dados, com formato e tipos bem definidos), e se este JSON possui determinada chave. E isso a regex não faz.
É até possível validar um JSON usando regex, mas sinceramente, é tão complicado que na minha opinião não vale a pena (talvez apenas como curiosidade e/ou para se aprofundar na sintaxe de regex).
Além disso, a regex que sugeri é ingênua demais. Primeiro que ela aceita JSONs inválidos como:
{ "logUser":::::::123, "etc" ... }
{ "logUser":  , }

Isso por causa do [^,], que significa "qualquer caractere que não seja vírgula", ou seja, se tiver vários espaços ou vários :, a regex considera válido. Podemos criar expressões mais complicadas (como a do link já citado), que validam corretamente strings, números, etc, mas mesmo assim ainda há outros problemas.
Por exemplo, você só quer o "logUser" do primeiro nível. Mas a regex não consegue verificar em qual nível a chave está:
{
    "abc": 123,
    "logUser": 123, <-- deveria pegar só esse
    "segundoNivel": {
        "logUser": 123, <-- não deveria pegar esse, pois não está no primeiro nível (mas pega)
    },
    ...
}

Claro, eu poderia fazer com que a regex só pegue a primeira ocorrência de "logUser", mas o JSON também poderia estar assim:
{
    "abc": 123,
    "segundoNivel": {
        "logUser": 123, <-- não deveria pegar esse, pois não está no primeiro nível (mas pega)
    },
    "logUser": 123, <-- deveria pegar só esse
    ...
}

Lembre-se que um objeto JSON é um unordered set (conjunto não-ordenado) de pares chave/valor, o que significa que a ordem das chaves não é garantida, e dependendo da biblioteca/linguagem utilizada, pode ser que o "logUser" apareça da maneira acima. E a regex não vai te salvar nestes casos (a menos que você se aventure com regex recursivas, que além de complicado, nem todas as linguagens suportam).
Claro que você poderia verificar se a linha começa com 4 espaços (uma forma de "garantir" que está no primeiro nível), mas aí você teria que garantir que o JSON sempre estará formatado desta maneira (e essa garantia tem que ser feita fora da regex). Mas já que você vai formatar o JSON - de preferência usando alguma biblioteca - por que já não aproveita e usa esta biblioteca para validá-lo e verificar/obter o campo que precisa?
Enfim, neste link você pode ver a regex "funcionando" para estes casos. Evidentemente dá para melhorá-la, trocando a vírgula por [,}] ("vírgula ou }", pois "logUser" pode ser o último elemento, aí não vai ter vírgula, e sim }), ou colocando algo como "\w+"|\d+ (caracteres entre aspas ou números) para restringir mais os valores, etc. Mas no fim você vai acabar com expressões gigantescas como as deste link, o que na minha opinião faz com que não valha a pena usar regex.

Use a ferramenta certa
Regex é uma ferramenta poderosa e muito legal, mas nem sempre é a melhor solução.
Se seus dados são um objeto JSON, use uma biblioteca dedicada. Você não especificou qual linguagem está usando, mas a grande maioria delas (se não todas) possui alguma biblioteca para manipular/ler/validar/converter JSON.
Aí bastaria ler os dados e verificar se existe a chave "logUser" no primeiro nível (e obter seu valor facilmente para compará-lo com o que você quiser, etc), sem precisar se preocupar com todos os problemas citados anteriormente, e sem precisar construir uma regex super-complicada (não só de fazer, mas de manter futuramente também).
Usar a ferramenta errada só vai - desnecessariamente - te trazer problemas que você não teria se usasse a ferramenta correta.

Apenas alguns exemplos para você ver como é muito mais simples não usar regex. Como você não especificou qual linguagem está usando, escolhi algumas "aleatoriamente". O JSON foi simplificado para não deixar o código muito longo, mas todos funcionam para o seu JSON também.
Em Python, basta usar o módulo json:
import json

def test(texto):
    # transforma o texto em um objeto JSON
    json_obj = json.loads(texto)
    # verifica se possui logUser no primeiro nível
    if 'logUser' in json_obj:
        print('logUser está no primeiro nível, valor=', json_obj['logUser'])
    else:
        print('logUser não está no primeiro nível')

# logUser no primeiro nível
test("""
    {
      "abc": "cde",
      "logUser": "xyz",
      "segundoNivel": {
        "etc": 123
      }
    }""");

# logUser no segundo nível
test("""
    {
      "abc": "cde",
      "segundoNivel": {
        "logUser": "xyz",
        "etc": 123
      }
    }""")

Em Java, há várias bibliotecas disponíveis, como o pacote org.json, o Gson do Google, etc. Todas funcionam de maneira bem parecida (recebem uma string e convertem para um objeto JSON, que pode ser usado para verificar se a chave existe e obter seu valor). Um exemplo com org.json.JSONObject:
public void verifica(String texto) {
    // transforma a string em um objeto JSON
    JSONObject obj = new JSONObject(texto);
    // verifica se possui logUser no primeiro nível
    if (obj.has("logUser")) {
        System.out.println("possui logUser no primeiro nível, valor=" + obj.getString("logUser"));
    } else {
        System.out.println("não possui logUser no primeiro nível");
    }
}

// possui logUser no primeiro nível
verifica("{ \"abc\": \"cde\", \"logUser\": \"xyz\", \"segundoNivel\": { \"etc\": 123 } }");
// não possui logUser no primeiro nível
verifica("{ \"abc\": \"cde\", \"segundoNivel\": { \"logUser\": \"xyz\", \"etc\": 123 } }");

Em PHP, você pode usar json_decode:
function verifica($texto) {
    // converte o texto para objeto JSON
    $json = json_decode($texto);
    // verifica se logUser está no primeiro nível
    if (array_key_exists('logUser', $json)) {
        echo "\nlogUser está no primeiro nível, valor=". $json->logUser;
    } else{
        echo "\nlogUser não está no primeiro nível";
    }
}

// logUser no primeiro nível
verifica('{ "abc": "cde", "logUser": "xyz", "segundoNivel": { "etc": 123 } }');

// logUser no segundo nível
verifica('{ "abc": "cde", "segundoNivel": { "logUser": "xyz", "etc": 123 } }');

Como você disse que quer verificar se logUser existe, mesmo que o valor seja nulo, eu usei array_key_exists, que verifica se a chave existe, independente do valor. Se quiser descartar valores nulos, pode trocar por isset.
Por fim, em JavaScript, use o objeto JSON:

function verifica(elemento){
  // pega o texto do elemento
  let texto = document.querySelector(elemento).value;

  // transforma o texto em um objeto JSON
  let json = JSON.parse(texto);

  // verifica se possui logUser no primeiro nível
  if (json.logUser) {
    console.log(`${elemento} possui logUser no primeiro nível, valor=${json.logUser}`);
  } else {
    console.log(`${elemento} não possui logUser no primeiro nível`);
  }
}

verifica('#logUserPrimeiroNivel');
verifica('#logUserSegundoNivel');
<textarea id="logUserPrimeiroNivel" rows="8">
{
  "abc": "cde",
  "logUser": "xyz",
  "segundoNivel": {
    "etc": 123
  }
}
</textarea>

<textarea id="logUserSegundoNivel" rows="8">
{
  "abc": "cde",
  "segundoNivel": {
    "logUser": "xyz",
    "etc": 123
  }
}
</textarea>

Enfim, a maioria das linguagens possui alguma biblioteca para lidar com JSON, e todas costumam funcionar de maneira similar (transforme a string em objeto JSON, verifique se a chave existe, pegue seu valor). E repare nos exemplos acima que o código é bem simples, muito mais fácil de entender e manter do que isso:
$pcre_regex = '
  /
  (?(DEFINE)
     (?<number>   -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )
     (?<boolean>   true | false | null )
     (?<string>    " ([^"\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
     (?<array>     \[  (?:  (?&json)  (?: , (?&json)  )*  )?  \s* \] )
     (?<pair>      \s* (?&string) \s* : (?&json)  )
     (?<object>    \{  (?:  (?&pair)  (?: , (?&pair)  )*  )?  \s* \} )
     (?<json>   \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* )
  )
  \A (?&json) \Z
  /six
';

E isso é somente para verificar se a string é um JSON válido. Você ainda precisa modificá-la para encaixar a verificação de logUser apenas no primeiro nível. Lembrando que a regex acima faz uso de recursão, que não é suportado por todas as linguagens.
Definitivamente, regex não é a melhor opção para o seu caso.

A:
"- Preciso selecionar o atributo logUser apenas no Objeto principal do JSON"

É possível, mas não recomendado!

@off-topic: Existem bibliotecas de JSON para quase todas (se não todas) as principais linguagens de programação. É muito melhor, e mais seguro, retornar o valor de tal propriedade direto com o JSON.

Não vou estender muito sobre, já que a resposta do @hkotsubo já explica precisamente as vantagens de utilizar uma biblioteca JSON e as desvantagens de utilizar expressão regular.
Mas, se ainda assim, você quiser utilizar expressão regular, pode fazer assim:
/\"logUser\"(?=.*\:)([\s\:]+)([^\,}]+?)(\,|\})/

Explicando:

*

*Busca "logUser";

*Busca espaço (\s) e dois pontos (:) uma ou mais vezes, e o positive lookahead força a ter dois pontos (:);

*Busca qualquer coisa diferente de vírgula (,) ou fecha-chave (}), que é o valor que você precisa;

*Busca o delimitador do valor, que pode ser uma vírgula (,) ou fecha-chave (});

Veja este exemplo funcional.
Note que não utilizei o modificador global, já que você quer apenas o objeto principal. O valor que você precisa é capturado no segundo grupo: $2.
Agora basta você capturar o "match" no seu projeto. Não vou exemplificar, já que você não mencionou qual a linguagem está usando, etc...
Devo reiterar que a melhor solução é utilizar uma biblioteca JSON!
Mas se quer mesmo utilizar a expressão regular, certifique-se de que esse JSON sempre será válido e seguirá tal estrutura.
Se sempre estiver com esse padrão de indentação, pode adicionar uma busca de 4 espaços (\s) no início da linha para certificar-se que seja mesmo no "primeiro nível" do JSON. Veja neste link.

Sou pato em expressão regular. Formulei esta resposta a fim de exercitar e "demonstrar possibilidades". Considere seguir as recomendações da mencionada resposta, ao invés de "reinventar a roda"...

Agradecimentos especiais pelas colocações do @hkotsubo.


text:
Q: Why does jar file that created by assembly:single cannot find main class ? I have a Maven project. The content of pom.xml file is:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>BestOfferz</groupId>
    <artifactId>BestOfferz</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>BestOfferz</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-core</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-web</artifactId>
            <version>3.4.1</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.vertx</groupId>
            <artifactId>vertx-web-client</artifactId>
            <version>3.4.1</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.company.Main</mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>

    </build>

</project>

I create a jar file by the command:

mvn clean compile assembly:single

and then I try to run the jar extracted by:

java -cp target/BestOfferz-1.0-SNAPSHOT-jar-with-dependencies.jar
  com.company.Main

and I get an error:

Error: Could not find or load main class com.company.Main

My Main class looks this way:
package com.company;
public class Main {
    ....
    public static void main(String[] args) throws FileNotFoundException {
       ....
    }
}

A:
Compile is not enough, when creating a JAR, you need to "package",
i.e call -
mvn package

Please read here -
Build lifecyle

A: You can just say
     mvn install

or
     mvn clean install

then your jar is built and executable through
     java -jar YourJar.jar

A: The following pluginRepository made that job:
<pluginRepositories>
    <pluginRepository>
        <id>onejar-maven-plugin.googlecode.com</id>
        <url>http://onejar-maven-plugin.googlecode.com/svn/mavenrepo</url>
    </pluginRepository>
  </pluginRepositories>

It's a direct node of project node.
Thanks to Yair Zaslavsky.


text:
Q: why does aws alb report elb_status_code of 460 for requests that the api has resolved I have betteruptime setup to periodically ping my api. Today it reported the api was down for 2 seconds and i wanted to understand why.
After querying the aws alb logs i can see that there are logs corresponding that return a status code of 460. Note the target_status_code is empty.

if i search for these requests in my api, i can see it received the request and responded accordingly based on the trace_id.

Can you help me understand what might be happening here?


text:
Q: Adding dates to an array through a loop I am going through a for loop, adding a time onto the current date, and adding the new date into an array.
However, when I output the array once the loop is completed, it is filled with 50 instances of the same date.
Logging these dates from within the loop however shows them being incremented correctly.
Is this something to do with the data being updated after it has already been pushed into the array?
var dates = new Array();
var currentDate = new Date();
for (var i =0; i < 50;i++){
    currentDate.setDate(currentDate.getDate()+2);
    console.log(currentDate);
    dates.push(currentDate);
}
console.log(dates);

A: Move var currentDate = new Date(); inside for loop. Otherwise you are modifying the same object and adding  50 references of it in the array.
In the end you see the the same object printed 50 times with the last updated date value.

A: You can do as Yogendra suggests, or change:
> dates.push(currentDate);

to
dates.push(new Date(currentDate));

to get a different date object for each member of the array.


text:
Q: How to get index of observations in each node of a tree? In R,
how do u retrieve for each node of a tree, the index of observations in each node in the tree, without recoding all the tree iterative procedure?
For example in rpart (an r package):
library(rpart)
fit <- rpart(Kyphosis ~ Age + Number + Start, data = kyphosis, cp = -1)
fit$splits

I would like to know for each splits, which observations go to the right node and which go to the left node.


text:
Q: How to use array of objects as NSCollectionview Datasource in Xcode MacOS Hiii.
As a beginner, I have an array of imageViews with this code:
var imageViews = [NSImageView]()

and they are filled with images from a folder in my system. I want a way to use them in a collectionView as data source. Is it possible?


text:
Q: navigator notification alert not working in Cordova I'm trying to print an alert with Cordova and it only works if I emulate my app with Ripple Chrome extension.
In my Samsung Galaxy S3, nothing happens when I click the button.
I'm using Cordova 3.6.3-0.2.13.
I've added to my project the following plugins:
org.apache.cordova.dialogs and
org.apache.cordova.vibration.
(if I type "cordova plugins ls" they both appear)

    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />

    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <title>Hello World</title>

Apache Cordova

Connecting to Device

Device is Ready

        <button id="gobutton" type="button" onclick="getInfo()">CLICK ME</button>

While my index.js is:
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};

app.initialize();

Could you help me? Thanks in advance

A: Dawson's comment should work.
As you can see at the Cordova documentation page:
http://docs.phonegap.com/en/2.2.0/cordova_notification_notification.md.html#notification.alert
The code:
navigator.notification.alert

is AFTER loading the cordova library.


text:
Q: how to prove the operator $L$ is zero. Problem
For
$f, g \in C([0; 1])$
define
$$d(f,g):= \int_{0}^{1}\min\{1,\vert f(x)-g(x)\vert\}dx $$
(a) Prove that $d$ is a distance on $C([0,1]).$
(b) Let $L: C([0,1])\to \mathbb{R}$
be a linear operator, continuous with respect to the topology induced by
$d$. Prove that $L = 0.$
The part (a) is easy to solve. But I have no idea how to start for part (b). Please leave some hints, not a whole solution, to me.

A: Using the continuity of $L$, pick $\delta > 0$ such that $|L(f)|<1$ whenever $d(f,0)<\delta$. One sufficient condition for $d(f,0)<\delta$ is that $f$ satisfy the following property:

Property $P_{\delta}$. The support of $f$ is contained in an interval of length $<\delta$. To be precise, there exists an interval $I\subseteq [0,1]$ of length $<\delta$ such that $ \{x : f(x) \neq 0 \} \subseteq I $.

If $f$ has this property, then so is any scalar multiple of $f$, hence
$$ |L(f)| = \frac{1}{n}|L(nf)| \leq \frac{1}{n} $$
and we have $L(f)=0$ by letting $n\to\infty$.
Now the key idea is that any continuous function $f$ can be uniformly approximated by linear combinations of functions having poperty $P_{\delta}$.
For instance, for each $n$ satisfying $n>2/\delta$, we notice that the linear interpolation $f_n$ of points $(\frac{k}{n}, f(\frac{k}{n}))$ for $k = 0, \cdots, n$ can be written by
$$f_n(x) = \sum_{k=0}^{n} f\left(\frac{k}{n}\right)\varphi_{n,k}(x), \qquad \varphi_{n,k}(x) := \max\left\{0, 1-n\left|x-\frac{k}{n}\right|\right\}.$$
Since each $\varphi_{n,k}$ is supported on the interval $[\frac{k-1}{n}, \frac{k+1}{n}]$ whose length is $=\frac{2}{n} < \delta$, it has property $P_{\delta}$ and hence $L(\varphi_{n,k})=0$. So it follows that $L(f_n) = 0$. On the other hand, we can easily check that $f_n \to f$ uniformly and hence $f_n \to f$ under the metric $d$. So we have $L(f)=0$ as desired.


text:
Q: when you click on of the item, it should take you to other screen, but error on if condition? package com.example.Calc;

import android.R.string;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class modes extends ListActivity {

/** Called when the activity is first created. */

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        // Create an array of Strings, that will be put to our ListActivity
        String[] names = new String[] { "Simple Calculator", "Tip Calculator", "Mortgage Calculator", "BMI",
                "GPA Calculator"};
        // Create an ArrayAdapter, that will actually make the Strings above
        // appear in the ListView
        this.setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, names));
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        string content;
        if( content ="Simple Calculator")
        {
             // When clicked, Open the Next Screen
             Intent r=new Intent(modes.this ,simplecalculator.class );
        }
    }
}

Getting error on if( content ="simple calculator")
I want when i click simple calculator it should take me to other screen.. i have defined everything, but i forgot the if condition thing.. everything is done.. its just whats the condition for if..
please help and thanks for your time.

A: I think you want if (content.equals("Simple Calculator")), not if (content = "Simple Calculator")

A: protected void onListItemClick(ListView l, View v, int position, long id) {

    String content = ((ArrayAdapter<String>)l.getAdapter()).getItem(position);
    if( content.equals("Simple Calculator"))
    {
         // When clicked, Open the Next Screen
         Intent r=new Intent(this ,simplecalculator.class );
         startActivity(r);
    }
}

A few things:
1) Please use CamelCase for your class names.
2) String starts with a captial letter (as should all Java classes).
That's it.


text:
Q: How to control tsc output formatting? Sometimes I get this:
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }

Other times I get this:
var __awaiter =
  (this && this.__awaiter) ||
  function (thisArg, _arguments, P, generator) {
    function adopt(value) {
      return value instanceof P
        ? value
        : new P(function (resolve) {
            resolve(value);
          });
    }

I haven't figured out why but it seems to toggle a lot.  I know many of the changes I'm seeing are when I update a dependency but I believe the snippet above is directly from typescript.  Is there a way to lock down the formatting rule?


text:
Q: Javascript: What is the benefit of using function context vs passing as parameter Other than tricking existing functions that already implement this as something, why would you want to write a javascript function so that you need to alter its context (via .call or .apply) rather than explicitly passing the "context" as another parameter?  Is there a performance benefit?
Example:
function tryIncrement(inc, context) {
    context = context || this; // just so we can reuse same fn for the example

    if( typeof context.val!= typeof 1|| typeof inc != typeof 1 ) return false;
    context.val += inc;
    return true;
}

var a = {name: 'A', val: 5}, b = {name: 'B', val: 20};

// reassign internal context
for(var i = 0, n = [1,3,"not a num",5]; i < n.length; i++) {
    if( tryIncrement.call(a, n[i]) ) console.log('incremented', i, n[i], a);
    else console.log('failed to increment', i, n[i], a);
}

// provide explicit context;
// could just as easily declared function so context was first param
// so it looked the same as previous implementation
for(var i = 0, n = [1,3,"not a num",5]; i < n.length; i++) {
    if( tryIncrement(n[i], b) ) console.log('incremented', i, n[i], b);
    else console.log('failed to increment', i, n[i], b);
}

A:
As far as I can tell the use of this isn't really any different than
  another parameter, it just has a more complicated way of being
  modified.

I think the easiest way to answer your question is to imagine if the creator of the base Javascript language had followed your conventions.
A world without this
A world without this is a scary noisy place with lots of excessive duplication:
var arr = [1,2,3,4];
arr.reverse(arr); //4321

More opportunities for misleading or verbose syntax
var str = "stringtobesplit";
"abiglongstringnotbeingsplit".split(str,":");
String.prototype.split(str,":");

And its not at all rid of apply at least:
Math.max.apply(arr);  //didn't add the initial `this` since it doesn't exist

Effectively there would be a choice between creating only global functions, or creating functions on prototypes or objects that made assumptions about the types of the arguments it was receiving but didn't enforce those assumptions.  For instance imagine the toString method in our fantasy world.
You could either create a global toString method which would take in an object of every type ever, and try to make them all work, or you could have a function on the prototypes of each type as it works currently, with no enforcement that it would be called on that type.  Someone could call
Array.prototype.toString(str)

And we would need to handle it gracefully (for what its worth doing this with apply seems to revert to the Object.prototype.toString and returns [Object String]).  So we would need to identify the correct prototype method to call in those cases, which means my guess is that the convention would be to call
str.toString(str)

or something along those lines.
So whats the point?
this is built to handle the common case for javascript methods on the prototype chain.  It gives us a shorthand to allow an object to act on itself without duplicating the call to it or having to know exactly what its prototype is.  Without it, we would either have to have no functions on objects, or would have to explicitly call the function on itself every time, introducing extra syntax and potential errors.
call and apply are the exception cases, and apply at least would have uses even if this went away.  Its never a good idea to write your apis to the exception cases.  If you're creating object oriented code, you should use this as an easy way to refer to the object that is the context for the call.  If you write this well, then call and apply should be used rarely and in special situations.
TL;DR - this was designed as part of Javascript for a reason, use it when you're creating methods on objects for more clear and understandable syntax.

A: There are many cases where you may wish to use this instead of passing an extra parameter. Consider the following function for example:
Function.prototype.async = function () {
    setTimeout.bind(null, this, 0).apply(null, arguments);
};

This function allows us to defer a function call as follows:
alert.async("This will display later.");
alert("This will display first.");

You can see the demo here: http://jsfiddle.net/AjwQu/
Instead of binding the function to this we could have passed it as a parameter instead:
function async(funct) {
    setTimeout.bind(null, funct, 0).apply(null, [].slice.call(arguments, 1));
}

We would use it like this now:
async(alert, "This will display later.");
alert("This will display first.");

The result is the same: http://jsfiddle.net/63dBF/
However to get the arguments we have to use [].slice.call(arguments, 1) instead. In the first example we could simply use arguments as the function was not a part of the argument list.
Everything has it's advantages and disadvantages. You just need to know what to use when. Hope this helps a bit.
Bonus: It's really easy to convert a function that uses this into a function that accepts an extra parameter and vice versa. First let's define a few utility functions:
var functProto = Function.prototype;

var bind = functProto.bind;

var bindable = bind.bind(bind);
var callable = bindable(functProto.call);
var appliable = bindable(functProto.apply);

The bindable function allows you to create a bindable version of an existing function which when called returns a new function bound to the given arguments.
The callable function allows you to create a callable version of an existing function which when called calls the existing function with the given arguments and this pointer.
The appliable function allows you to create an appliable version of an existing function which when called applies the given arguments and this pointer to the existing function.
Then given the function in the first example we can create the function in the second example as follows:
var async = callable(functProto.async);

See the demo here: http://jsfiddle.net/3dSBS/
Similarly we can convert the function in the second example into the function in the first example as follows:
Function.prototype.async = function () {
    return async.apply(null, [this].concat([].slice.call(arguments)));
};

See the demo here: http://jsfiddle.net/rJQyS/
As you can see it's much easier to write a function using this and then construct the function accepting the context as a parameter from it than the other way around.

A: When you do object oriented programming your functions WILL depend on the context and it does not make sense do provide it as a parameter, as this would deafeat the purpose of object oriented programming.
It also makes sense to provide an implicit context for callbacks. You do not have to remember the correct order of the parameters if you only need the context. You would not have to use parameters at all in that case. So instead of
function mayCallback(param1, param2, context)
you could just write
function myCallback()
and use this, if you do not need param1 and param2.

A: To address my main purpose -- is there a performance benefit using this over a function parameter? -- the answer seems to be no:
http://jsperf.com/function-context-vs-parameter
Although there seems to be a slight benefit (may not be significant, however) around using parameter values instead of instance (this) variables within objects.
(Please test for yourself and comment if it's different)
Regarding the purpose being addressed by the other answers: there are some neat use cases as pointed out by @Aadit, maintainability is debatably a personal preference, but like @ben336 said if you're working with Objects (and thus OOP) then this can be more useful.
The ECMAScript 5th-edition native function bind may be an interesting bridge between the two worlds, or at least a time-sucking tangent to explore.
The instance vs parameter values test referenced above may also be a good example of my point -- if you're building a static library of functionality, you can "hijack" obj.callback2 by scoping to a different this, or just call obj.callback directly on your alternate context.


text:
Q: Section Titles in Margin Notes I am struggling to reproduce the following layout in Latex. I have tried using the package marginnote, and playing around with geometry and fancyhdr. I end up going around and around in circles, getting one bit right, then breaking some other aspect.

*

*This page is the default style for all pages except the first and last.

*The Blue Box in the margin is the current section title.

*The blue box should appear every time the section changes.

*Ideally the blue box would also appear each new page if the current section is multipage.

Any help would be greatly appreciated!
Kind Regards,
Nick

% -*- program: xelatex -*-

\documentclass[a4paper,10pt]{article}
%\usepackage{aca_report_digital}
\usepackage[utf8x]{inputenc}
\usepackage[english]{babel}

\usepackage{fontspec}
\newfontfamily\kelsonSans{Kelson Sans Regular}
\newfontfamily\museoSansB{Museo Sans 700}
\newfontfamily\museoSansSB{Museo Sans 500}
\newfontfamily\museoSansR{Museo Sans 300}

\usepackage{xcolor}
\definecolor{acagrey}{cmyk}{0.50, 0.36, 0.44, 0.20}
\definecolor{acablue}{cmyk}{0.77, 0.64, 0.42, 0.59}
\definecolor{acaoverlay}{cmyk}{0.100, 0.83, 0.68, 0.83}

\usepackage{tikz}

\usepackage{graphicx}
\def\acalogo{\hspace*{-0.0in} \includegraphics[width=50mm]{aca_logo.eps}}
\def\acaicon{\hspace*{-0.0in} \includegraphics[width=12.75mm]{aca_icon.eps}}

\usepackage{marginnote}
\reversemarginpar % To put the margin pars on the left
\renewcommand*{\marginfont}{\normalfont\normalsize}
\setlength{\marginparwidth}{5cm}

\author{Nick}
\date{}                                 % Activate to display a given date or no date

\usepackage{geometry}
\geometry{
  lmargin=2.0cm,     % Left margin on odd-numbered pages.
  rmargin=2.0cm,     % Left margin on even-numbered pages.
  bmargin=4.39cm,
  tmargin=6.3cm,
  marginparwidth=4.6cm,
  marginparsep=3mm,
}

\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\renewcommand{\headrulewidth}{0pt}
\lhead{\noindent\acaicon}
\lfoot{\museoSansR\fontsize{8pt}{0pt}\selectfont Foo Chartered Accountants\museoSansB\selectfont\space NFP Financial Accounting Template\museoSansR\selectfont\space 2015}
\rfoot{\museoSansR\fontsize{8pt}{0pt}\selectfont Page \thepage}

\begin{document}

\tableofcontents

\section*{About\marginnote{About}}
Foo
\subsection{Best Practices}
\subsection{Version Information}
\section{System Requirements}
\section{Getting Started}
\section{Income}
\section{Expenses}
\section{Bank Statement}
\section{Membership}
\section{Reporting}
\subsection{Filtering}
\subsection{Detailed Transaction Report}
\subsection{Transaction Summary Report}
\section{Customisation}

\end{document}

A: I'm not sure if I understood your requirements correctly, but here a starting point for you with titlesec.sty and titletoc.sty.  The idea is to hook your blue boxes into a new page style main with a 0pt width/height picture environment to position the blue box on the page with a \put command.
\documentclass[a4paper,10pt,oneside]{article}
\usepackage[utf8]{inputenc}
\usepackage{lmodern,lipsum,xcolor,geometry}

\geometry{%
  lmargin=5.0cm,
  rmargin=2.0cm,
  bmargin=4.39cm,
  tmargin=6.3cm,
  marginparwidth=4.6cm,
  marginparsep=3mm,
}

\usepackage[pagestyles]{titlesec}

\titleformat{\section}[hang]
  {\huge\sffamily}
  {}
  {0pt}{}[\vspace*{-1ex}\rule{1\linewidth}{3pt}]

\titleformat{\subsection}[hang]
  {\large\bfseries\sffamily}
  {}
  {0pt}{}

\newpagestyle{main}[\sffamily]{%
  \sethead
    {%
      \setlength{\unitlength}{1mm}%
      \begin{picture}(0,0)
        \put(-48,-20){%
          \makebox(0,0)[l]{%
            \colorbox{blue}{%
              \parbox[c][1cm][c]{4.5cm}{%
                \color{white}\hspace*{2em}\LARGE\sectiontitle}%
            }%
          }%
        }%
      \end{picture}%
    }
    {}
    {}
  \setfoot{}{}{\footnotesize Page~\thepage}
}

\pagestyle{main}

\usepackage{titletoc}

\titlecontents{section}[0em]
  {\addvspace{0.3pc}\bfseries\filright}
  {}{\hspace*{0em}}
  {\mdseries\titlerule*[0.7pc]{.}\bfseries\contentspage}

\titlecontents{subsection}[4em]
  {\addvspace{0.1pc}\filright}
  {}{\hspace*{0em}}
  {\titlerule*[0.7pc]{.}\contentspage}

\begin{document}
\tableofcontents
\clearpage
\section{About}
\lipsum
\subsection{Version Information}
\lipsum
\section{Best Practices}
\end{document}


text:
Q: Multithreading does not change speed I am currently working on speeding up one of my c++ program, and trying to discover the beautiful world of multithreading.
std::vector<std::thread> threadPool;
threadPool.clear();
for(int t = 0; t < nbThreads; ++t){
    threadPool.push_back(std::thread(myFunction, std::ref(rep), std::ref(branch1));
}
for(auto t = threadPool.begin(); t < threadPool.end() ; ++t){
    t->join();
}

What I don't understand is that whatever the number of threads I use, the speed does not change! (about 30sec).
To sum up : If my code is wrong, what is wrong? If it is not wrong, in what case should I use multithreading to speed up the computation?
Edit :  I run on a i7-4810MQ machine
Edit 2 : here is what myFunction does (it parses xml files)
void myfunction(DIR*& rep, struct dirent*& branch1){
mtx.lock();
while ((branch1 = readdir(rep)) != NULL){
    mtx.unlock()

    TiXmlDocument doc(branch1->d_name);
    if(doc.LoadFile()){
            //parse file
    }

    mtx.lock();
}
mtx.unlock();
}

A: There's a good chance that your code is limited by file I/O. There's also a good chance that your XML parser makes lots of memory allocations, and memory allocations may slow down if many threads allocate memory simultaneously.


text:
Q: Solve $(x+1)^y-x^z=1$ I want to know if there is another way to solve the equation:
$$(x+1)^y-x^z=1$$
for positive integers $x,y,z$ greater than $1$ without using the Catalan identity. Does exist? By now I only know that $x\mid y$.

A: $(x+1)^y=x^z+1^z$ with $x,y,z\ge 2$.
By Zsigmondy's theorem, unless $(x,y,z)=(2,2,3)$, $x^z+1^z$ has a prime divisor that does not divide $x+1$, which is impossible.

A: In Which is greater, 9899 or 9998? it was stablished that $(x+1)^x<x^{x+1}$ for all real $x>2.293$. On the other hand, $(x,y,z)=(1,1,1)$ ,$(2,2,3)$ and $(1,1,z)$ with $z\ge1$ are clearly solutions.
We have  $$(x+1)^y-x^z=1 \Rightarrow (x+1)^y>x^z\Rightarrow y<z$$ From
$$\begin{cases}(x+1)^x<x^{x+1}\text{ for all x>2.293}\\(x+1)^y>x^z\\y<z\end{cases}$$ we deduce easily $y<2.293$ then $y=1$ or $2$ which gives the only solutions above.

A: Two obvious remarks : first, we have a whole bunch of solutions given by $y=z=1$ (since $(x+1)-x = 1$), and there is a solution with $y \neq z$, namely $(x,y,z) = (2,2,3)$ since $(2+1)^2 - 2^3 = 9-8 = 1$, which you can find by inspection (I just started putting low exponents and figured it out by guessing).
Second, a solution must satisfy $y \le z$, for if $y > z$, then since $x \ge 1$,
$$
(x+1)^{y+1} = (x+1)^y (x+1) \ge (x+1)^y + 1 > x^z+1.
$$
(Which makes sense, the bigger number should have a smaller exponent so that their difference can be small, e.g. $1$.)
Added : third remark, if $y=z > 1$, we have no solutions by the $a^n-b^n$ identity, for if $x \ge 1$, we have
$$
(x+1)^z - x^z = ((x+1)-x)\left( \sum_{i=0}^{z-1} x^i (x+1)^{z-1-i} \right) \ge x^{z-1} + (x+1)^{z-1} > 1.
$$
(This wasn't meant to be a full answer, just too big for a comment.)
Hope that helps,


text:
Q: Is this function really tail-recursive? I read about recursion in Programming Interviews Exposed (3rd ed.) where they present the following recursive factorial function:
int factorial(int n){
    if (n > 1) { /* Recursive case */
        return factorial(n-1) * n;
    } else {     /* Base case */
        return 1;
    }
}

On the bottom of the same page (page 108) they talk about tail-recursive functions:

Note that when the value returned by the recursive call is itself immediately returned, as in the preceding definition for factorial, the function is tail-recursive.

But is this really the case here? The last call in the function is the * call, so won't this stack frame be preserved (if we don't take compiler optimization into account)? Is this really tail-recursive?

A: You can rewrite it to be tail-recursive:
int factorial(int n){
    return factorial2(n, 1);
}
int factorial2(int n, int accum) {
    if (n < 1) {
       return accum;
    } else {
        return factorial2(n - 1, accum * n);
    }
}

A: No, it's not tail-recursive.  The result being returned by factorial(n-1) still has to be multiplied by n, which requires that factorial(n) regain control (thus mandating that the call to factorial(n-1) be a call rather than a jump).
With that said, even if it were tail-recursive, the compiler still might not do TCO on it.  Depends on the compiler and the optimizations that you ask it to do.

A: Quoting from this link: tail recursion using factorial as example
 factorial(n) {
    if (n == 0) return 1;
    return n * factorial(n - 1);
 }//equivalent to your code

 This definition is NOT tail-recursive since the recursive call to
 factorial is not the last thing in the function
 (its result has to be multiplied by n)

A: Tail Recursive is a special case of recursion in which the last operation of the function is a recursive call. In a tail recursive function, there are no pending operations to be performed on return from a recursive call.
The function you mentioned is not a tail recursive because there is a pending operation i.e multiplication to be performed on the return from a recursive call.
In case you did this:
    int factorial(int n,int result)
    {
        if (n > 1)
        { /* Recursive case */
             return factorial(n-1,n*result);
        }
        else
        {     /* Base case */
            return result;
        }
    }

would be a tail recursive function. since it has no pending operation on return from a recursive call.


text:
Q: Java jackson json with hierarchical data. How to remove duplicates I am trying to do some repository of files and folders. I'would like to use java script  library to print tree, so I have to apply Json object to it. But unfortunatelly when I am trying to make my object to json, I get duplicates. Here is json output from my main object:
[{"id":5,"name":"Folder2.2","parent":
    {"id":2,"name":"Folder1.1","parent":
      {"id":1,"name":"Folder1","parent":null}}},
  {"id":1,"name":"Folder1","parent":null},
  {"id":2,"name":"Folder1.1","parent":
    {"id":1,"name":"Folder1","parent":null}},
      {"id":3,"name":"Folder2","parent":null},
  {"id":4,"name":"Folder2.1","parent":
    {"id":3,"name":"Folder2","parent":null}}
]

As You can see there is a lot of duplicates. And I would like to print from this data hierachical tree. Should be something like this:
[
{"id":1,"name":"Folder1","children":
  {"id":2,"name":"Folder1.1","children":null}
},
{"id":3,"name":"Folder2","children":
  {"id":4,"name":"Folder2.1","children":null},
  {"id":5,"name":"Folder2.2","children":null}
}
]

Can it be done with some out of the box api from Jackson?
Here is my entity
@Entity
public class Folder {
  Long id;
  String name;
  @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  Folder parent;
}


text:
Q: JS Date YYYY-MM-DD Returning incorrect value I have HTML Date inputs that return a string in the format of 'YYYY-MM-DD'
I then want to put this into the Date Constructor so that I can get it converted into ISOFormat (for use of Mongo Querying)
However, the results are unexpected.
Doing new Date('2020-06-25') returns "Wed Jun 24 2020 20:00:00 GMT-0400 (Eastern Daylight Time)". Note that this is the day prior. Why does this happen and how can I change this to get the current date? THanks

A: When you create a new Date object in JavaScript, it expects the argument to be in GMT. It then converts it to your local timezone GMT-0400, which explains why its 4 hours off. You can set the timezone by appending it to the date string: new Date('2020-06-25 GMT-0400') should give you "Thu Jun 25 2020 00:00:00 GMT-0400".


text:
Q: How to populate the EditText with the button click? I want to get the values in the button to be populated in the edit text box. i.e I am creating a login page in which the pin has to entered I have given a set of numbers as buttons, when I click the button the corresponding values has to be populated in the edit text box( just like the ATM action).
I am now using:
 b1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View paramView) {
                // TODO Auto-generated method stub
                String text=(String) b1.getText();
                        pincode.setText(text);
            }
        });

with the above code I am getting the values populated, but I have a set of buttons, so is there any simplified way to get the values populated?
*The values currently replacing the previous one , I need multiple values in the edit text like if we press buttons 1,2,3 (values) the values in the edit text should be 123 *

A: onClick(View v)
{
    editText.setText(editText.getText() + v.getText());
    //plz adjust casting and spanned as per requirement
}

A: on your button onClick you got to do this
button1.setOnClickListener(new View.OnClickListener() {
yourEditText.setText(yourEditText.getText().toString+"1");
});

button2.setOnClickListener(new View.OnClickListener() {
yourEditText.setText(yourEditText.getText().toString+"2");
});

this way your buttons will work

A: To do this, in your activity implements OnClickListener
then add this listener to all your button as
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);

and write onClick event as
public void onClick(View v) {

    Button b1 = (Button)v;
    editText.setText(editText.getText().toString()+b1.getText().toString());
}

and you are done :)

A: You can add text like this:
String a = "random text";
input = your_edit_text_box;
input.setText(a);

Link: http://developer.android.com/reference/android/widget/EditText.html#setText%28java.lang.CharSequence,%20android.widget.TextView.BufferType%29

A: Button btnNO = (Button) findViewById(R.id.btn);
EditTExt edtText = (EditText) findViewById(R.id.editText);

btnNO.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
     String text= btnNo.getText();
     edtText.setText(text);

    // or direct use like, edtText.setText(btnNo.getText());
    }

});


text:
Q: PostgreSQL query error when using PHP When I run a PostgreSQL query containing ::geometry casting, I get a type "geometry" does not exist error. I am using php5-pgsql V5.3.10, php5-fpm 5.4.13, Laravel 4, Postgresql 9.1, PostGIS 2.0.1 on Ubuntu 12.04. geometry type is PostGIS-specific.
Without the casting, the query runs fine. The original query also works fine when queried directly against the PostgreSQL database using pgAdmin3. Why is this?
Query
$busstops = DB::connection('pgsql')
    ->table('locations')
    ->select(DB::raw('geog::geometry as lat, geog::geometry as lng'))
    ->get();

Query without casting (No errors)
$busstops = DB::connection('pgsql')
    ->table('locations')
    ->select(DB::raw('geog as lat, geog as lng'))
    ->get();

Error:
Exception: SQLSTATE[42704]: Undefined object: 7 ERROR: type "geometry" does not exist
LINE 1: select geog::geometry as lat from "locations"
^ (SQL: select geog::geometry as lat from "locations") (Bindings: array (
))

\dT geometry
                     List of data types
 Schema |   Name   |               Description
--------+----------+-----------------------------------------
 public | geometry | postgis type: Planar spatial data type.
(1 row)

A: The application is switching the search_path around so that public isn't on the search_path. By default extensions are installed into public, so you're finding that geometry and the other PostGIS types and functions become unavailable from the application when it switches the search_path.
You need to:

*

*Create a new schema postgis;

*Move the PostGIS extension into the postgis schema; and

*Make sure that the new postgis schema is always on the search_path, probably using application-specific settings


text:
Q: Adding individual product pages for ruby on rails e-commerce site Hi I am having trouble showing an individual page for a product on ruby on rails for an e-commerce site, my code is as follows for the show view:

  <%= @product.name %>

  <%= @product.description %>

<%= @product.image_url %>

  <%= @product.image_url1 %>

  <%= @product.image_url2 %>

  <%= @product.image_url3 %>

   <%= @product.price %>

Here is the code for the controller:
def show
@product = Product.find(params[:id])

respond_to do |format|
format.html # show.html.erb
format.json { render json: @product}
end
end

What should I add to be able to see an individual products page which shows the name images, description, price as it works fine when I am indexing the products?

A: You need an  tag to show an image, which can be generated with the image_tag method.
Try this:

  <%= image_tag(@product.image_url) %>

Here's more information on the image_tag method
You may also want to hide that div if one of the images doesn't exist:
<% if !@product.image_url3.nil? && !@product.image_url3.blank? %>

    <%= image_tag(@product.image_url3) %>

<% end %>

A: I got it to work finally I was making changes to the wrong view file.


text:
Q: Doors dxl create link between modules i have the following issue and would like to ask for your help.
First of all, i am new to dxl and have never done that before.
I have 3 modules which are linked with each other.
Module 1 -> Module 2 -> Module 3
now we want to delete module 2 and do the direct link from module 1 to module 3.
How should i do this in dxl? We don't want to do it manually so i am trying to find out a way with dxl.
My idea is i will check for every objects in module 2 if each object in module 2 includes link 1 and 3 then connect 3 and 1 with eachother. But i don't know how the code look like. I have been searching it but there weren't so many infos about syntax and stuff :(

A: You can do it without DXL.

*

*In Module 1 in exclusive edit mode, start the -> Analysis -> Wizard with the parameters:

*

*Link direction: Out links

*Link types: DOORS links

*Select formal module: All modules

*Select link module: All modules

*attributes to display: Only Object Number

*Width: any value is ok

*Options: only one attribute per line

*Recursive analysis: on

*Multiple columns: on

*depth of analysis: 2

*Finish

*You should now see two now columns. The column "Out-links at depth 2" shows the destination object that will be the link target of the new link to be created.

*Start -> Tools -> Support Tools -> Convert Layout DXL to Attribute DXL, choose "Out-links at depth 2" -> Convert

*Start -> Link -> Advanced -> Link by Attribute with the parameters:

*

*Target Module: Module 3

*Link Module: choose the Link module that you need

*Existing attributes: choose "DXL for Out-links at depth 2"

*Link direction: Source to target

*Objects to be linked in target module: All Objects

*OK

*Now all links from Module 1 to Module 3 should be created. Check all created links thoroughly. Then delete Module 2
Good luck